Alexis Lapeze
Alexis Lapeze

Reputation: 41

Why bitwise and send error in OpenCV Python?

I am trying to pass the mask of my second image on the first image.

I am getting the following error:

cv2.error: OpenCV(4.2.0) /io/opencv/modules/core/src/arithm.cpp:250: error: (-215:Assertion failed) (mtype == CV_8U || mtype == CV_8S) && _mask.sameSize(*psrc1) in function 'binary_op'

I followed this tutorial: https://theailearner.com/tag/cv2-addweighted/ and getting another error.

Code:

listFileEtiFinal = getImagesRGB("ImgResult","ETIFinal.png") + getImagesRGB("ImgEtiSelect","ETIFinal.png")
listFileEti = getImagesRGB("ImgResult","ETI.png") + getImagesRGB("ImgEtiSelect","ETI.png")

for fileImgF in listFileEtiFinal:
    for fileImgG in listFileEti:
            dos = fileImgF[0] + "/"
            fileEti = fileImgF[1]
            dosTwo = fileImgG[0] + "/"
            fileEtiG = fileImgG[1]
            nb = int(re.findall('\d+', fileEti)[0])
            img = cv2.imread(dos + fileEti)
            img2 = cv2.imread(dos + fileEtiG)
            img_gauss = cv2.GaussianBlur(img2, ksize=(11,11),sigmaX=5)
            _, img_gauss_th = cv2.threshold(img_gauss, thresh=243, maxval=255, type=cv2.THRESH_BINARY)
            img2gray = cv2.cvtColor(img_gauss_th,cv2.COLOR_BGR2GRAY)
            _, mask = cv2.threshold(img2, 200, 255, cv2.THRESH_BINARY_INV)
            mask_inv = cv2.bitwise_not(mask)
            rows,cols,_ = img2.shape
            roi = img[0:rows, 0:cols ]
            img1_bg = cv2.bitwise_and(roi,roi,mask = mask_inv)
            img2_fg = cv2.bitwise_and(roi,roi,mask = mask)  
            out_img = cv2.add(img1_bg,img2_fg)
            img[0:rows, 0:cols ] = out_img
            cv2.imwrite(dos + img , out_img)

Upvotes: 1

Views: 2025

Answers (2)

mohamadreza
mohamadreza

Reputation: 1

and make both pictures same size as eachother by use numpy for example: first,second=first[0:x,0:y,:],second[0:x,0:y,:] then delete mask type it's not main answering but it answers temporarily...

img1_bg = cv2.bitwise_and(roi,roi)

img2_fg = cv2.bitwise_and(roi,roi)

Upvotes: 0

Rotem
Rotem

Reputation: 32124

According to cv2.bitwise_and, mask must be single channel array.

mask – optional operation mask, 8-bit single channel array, that specifies elements of the output array to be changed.

The code you have posted uses mask with 3 channels.
You may check mask_inv.shape and mask.shape.

You may use only one channel of the mask (just for testing):

img1_bg = cv2.bitwise_and(roi,roi,mask=mask_inv[:,:,0])
img2_fg = cv2.bitwise_and(roi,roi,mask=mask[:,:,0])

Or better, convert image to Grayscale before threshold:

_, mask = cv2.threshold(cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY), 200, 255, cv2.THRESH_BINARY_INV)

Upvotes: 1

Related Questions