English 中文(简体)
OpenCV Python - Bitwise Operations
  • 时间:2024-12-22

OpenCV Python - Bitwise Operations


Previous Page Next Page  

Bitwise operations are used in image manipulation and for extracting the essential parts in the image.

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.

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()

Output

Bitwise Operators Bitwise Operators Bitwise Operators

Example 2

In another example involving bitwise operations, the opencv logo is superimposed on another image. Here, we obtain a mask array calpng threshold() function on the logo and perform AND operation between them.

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()

Output

The masked images give following result −

Bitwise Operators Mask Advertisements