python - 为什么在 OpenCV Python 中按位发送错误?

标签 python opencv cv2 bitwise-and opencv4

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

我收到以下错误:
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)

最佳答案

根据cv2.bitwise_and , mask必须是 单 channel 阵列 .

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



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

您只能使用一个 channel 的掩码(仅用于测试):
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)

关于python - 为什么在 OpenCV Python 中按位发送错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60832679/

相关文章:

python - 如何使用 GPU 实现更快的 convolve2d

python - seaborn中没有线性拟合的散点图

opencv - 使用FERNS进行目标检测

python-3.x - OpenCV图像形状元组解压缩

python - 使用 python/opencv/深度学习 从图像中删除给定位置的 Logo /水印

python - 如何将视频流从一个 python 传递到另一个?

Python help() 函数和 string.title 函数

带有 RegistrationSupplementBase 的 Django 导入错误的 Python 无法导入名称 'ugettext_lazy'

python - 生成列表元素对的每个排列,不重复或倒置对

python - opencv2 中阈值 32 uint 图像的轮廓和凸包