What does cv2.bitwise_and do? What are its parameters? [closed]

asked 2018-02-06 05:35:43 -0500

updated 2018-02-06 05:55:07 -0500

berak gravatar image

I'm just starting out with OpenCV and following this tutorial: http://opencv-python-tutroals.readthe...

Here's the code:

# Load two images
img1 = cv2.imread('messi5.jpg')
img2 = cv2.imread('opencv_logo.png')

rows,cols,channels = img2.shape
roi = img1[0:rows, 0:cols ]

# Now create a mask of logo and create its inverse mask also
img2gray = cv2.cvtColor(img2,cv2.COLOR_BGR2GRAY)
ret, mask = cv2.threshold(img2gray, 10, 255, cv2.THRESH_BINARY)
mask_inv = cv2.bitwise_not(mask)

# Now black-out the area of logo in ROI
img1_bg = cv2.bitwise_and(roi,roi,mask = mask_inv)

# Take only region of logo from logo image.
img2_fg = cv2.bitwise_and(img2,img2,mask = mask)

# Put logo in ROI and modify the main image
dst = cv2.add(img1_bg,img2_fg)
img1[0:rows, 0:cols ] = dst


I understand everything here except the 2 lines of code containing "bitwise_and" .

edit retag flag offensive reopen merge delete

Closed for the following reason the question is answered, right answer was accepted by sturkmen
close date 2020-10-26 12:00:29.082596


to start with , please use latest opencv docs and tutorials , not the outdated tutroals !

berak gravatar imageberak ( 2018-02-06 05:53:37 -0500 )edit

Thanks! I checked out the newer documentation for bitwise_and but I still don't understand what it does.

surajsirohi1008 gravatar imagesurajsirohi1008 ( 2018-02-06 06:08:07 -0500 )edit

is it a maths problem ?

berak gravatar imageberak ( 2018-02-06 06:28:53 -0500 )edit

@berak like in that example, in bitwise_not(), we passed in the mask as the parameter, it inverted the mask (apparently turned black to White and vice versa). But what does bitwise_and do when we pass the img and the mask as parameters?

surajsirohi1008 gravatar imagesurajsirohi1008 ( 2018-02-06 06:34:26 -0500 )edit

pixels in img2 will only be retained, where the mask is ON(255)

berak gravatar imageberak ( 2018-02-06 06:49:59 -0500 )edit