1

我正在尝试在第一张图像上传递我的第二张图像的蒙版。

我收到以下错误:

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'

我遵循本教程:https ://theailearner.com/tag/cv2-addweighted/并得到另一个错误。

代码:

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

1 回答 1

1

根据cv2.bitwise_andmask必须是单通道数组

mask – 可选操作掩码,8 位单通道数组,指定要更改的输出数组的元素。

您发布的代码使用具有 3 个通道的掩码。
您可以检查mask_inv.shapemask.shape

您只能使用一个通道的掩码(仅用于测试):

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

或者更好的是,在阈值之前将图像转换为灰度:

_, mask = cv2.threshold(cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY), 200, 255, cv2.THRESH_BINARY_INV)
于 2020-03-24T16:50:39.123 回答