Opencv Python 简明教程
OpenCV Python - Bitwise Operations
位操作用于图像处理和提取图像中的基本部分。
Bitwise operations are used in image manipulation and for extracting the essential parts in the image.
OpenCV 中实现了以下运算符:
Following operators are implemented in OpenCV −
-
bitwise_and
-
bitwise_or
-
bitwise_xor
-
bitwise_not
Example 1
为了演示如何使用这些运算符,获取了两张带有已填充和未填充圆圈的图像。
To demonstrate the use of these operators, two images with filled and empty circles are taken.
以下程序演示了如何在 OpenCV-Python 中使用位运算符:
Following program demonstrates the use of bitwise operators in OpenCV-Python −
import cv2
import numpy as np
img1 = cv2.imread('a.png')
img2 = cv2.imread('b.png')
dest1 = cv2.bitwise_and(img2, img1, mask = None)
dest2 = cv2.bitwise_or(img2, img1, mask = None)
dest3 = cv2.bitwise_xor(img1, img2, mask = None)
cv2.imshow('A', img1)
cv2.imshow('B', img2)
cv2.imshow('AND', dest1)
cv2.imshow('OR', dest2)
cv2.imshow('XOR', dest3)
cv2.imshow('NOT A', cv2.bitwise_not(img1))
cv2.imshow('NOT B', cv2.bitwise_not(img2))
if cv2.waitKey(0) & 0xff == 27:
cv2.destroyAllWindows()
Example 2
在另一个涉及位运算的示例中,将 opencv 标志叠加到另一张图像上。在这里,我们通过 threshold() 函数调用从标志中获得一个掩码数组,并在它们之间执行 AND 操作。
In another example involving bitwise operations, the opencv logo is superimposed on another image. Here, we obtain a mask array calling threshold() function on the logo and perform AND operation between them.
类似地,通过 NOT 操作,我们得到一个反向掩码。此外,我们还可以用背景图像进行 AND 操作。
Similarly, by NOT operation, we get an inverse mask. Also, we get AND with the background image.
以下程序确定了位操作的使用:
Following is the program which determines the use of bitwise operations −
import cv2 as cv
import numpy as np
img1 = cv.imread('lena.jpg')
img2 = cv.imread('whitelogo.png')
rows,cols,channels = img2.shape
roi = img1[0:rows, 0:cols]
img2gray = cv.cvtColor(img2,cv.COLOR_BGR2GRAY)
ret, mask = cv.threshold(img2gray, 10, 255, cv.THRESH_BINARY)
mask_inv = cv.bitwise_not(mask)
# Now black-out the area of logo
img1_bg = cv.bitwise_and(roi,roi,mask = mask_inv)
# Take only region of logo from logo image.
img2_fg = cv.bitwise_and(img2,img2,mask = mask)
# Put logo in ROI
dst = cv.add(img2_fg, img1_bg)
img1[0:rows, 0:cols ] = dst
cv.imshow(Result,img1)
cv.waitKey(0)
cv.destroyAllWindows()