如何在 OpenCV Python 中对两幅图像执行按位或运算?
opencvpythonserver side programmingprogramming
在 OpenCV 中,彩色 (RGB) 图像表示为三维 numpy 数组。图像的像素值使用 8 位无符号整数 (uint8) 存储,范围从 0 到 255。两个图像的按位或运算是在相应图像的这些像素值的二进制表示上执行的。
语法
以下是对两个图像执行按位或运算的语法 −
cv2.bitwise_or(img1, img2, mask=None)
img1 和 img2 是两个输入图像,mask 是掩码操作。
步骤
要计算两个图像之间的按位或,您可以使用下面给出的步骤 −
导入所需的库 OpenCV、Numpy 和 Matplotlib。确保您已经安装了它们。
import cv2 import numpy as np import matplotlib as plt
使用 cv2.imread() 方法读取图像。图像的宽度和高度必须相同。
img1 = cv2.imread('waterfall.jpg') img2 = cv2.imread('work.jpg')
使用 cv2.biwise_or(img1, img2) 对两个图像进行按位或运算。
or_img = cv2.bitwise_or(img1,img2)
显示按位或运算后的图像
cv2.imshow('Bitwise OR Image', or_img) cv2.waitKey(0) cv2.destroyAllWindows()
我们将在示例中使用以下图像作为输入文件下面。
示例 1
在下面的 Python 程序中,我们计算两个彩色图像的按位或。
# import required libraries import cv2 # read two images. The size of both images must be the same. img1 = cv2.imread('waterfall.jpg') img2 = cv2.imread('work.jpg') # compute bitwise OR on both images or_img = cv2.bitwise_or(img1,img2) # display the computed bitwise OR image cv2.imshow('Bitwise OR Image', or_img) cv2.waitKey(0) cv2.destroyAllWindows()
输出
运行此 Python 程序时,它将产生以下输出 -
示例 2
此 Python 程序展示了对两幅图像进行按位或运算的应用。我们创建了两幅图像,第一幅是圆形,第二幅是相同大小的正方形。
# import required libraries import cv2 import numpy as np import matplotlib.pyplot as plt # define first image as a circle img1 = np.zeros((300, 300), dtype = "uint8") img1 = cv2.circle(img1, (150, 150), 150, 255, -1) # define second image as a square img2 = np.zeros((300,300), dtype="uint8") img2 = cv2.rectangle(img2, (25, 25), (275, 275), 255, -1) # perform bitwise OR on img1 and img2 or_img = cv2.bitwise_or(img1,img2) # Display the bitwise OR output image plt.subplot(131), plt.imshow(img1, 'gray'), plt.title("Circle") plt.subplot(132), plt.imshow(img2,'gray'), plt.title("Square") plt.subplot(133), plt.imshow(or_img, 'gray'), plt.title("Bitwise OR") plt.show()
输出
当你运行这个 Python 程序时,它将产生以下输出 -