【问题标题】:Image mask not working when I invert it using bitwise_not (OpenCV-Python)当我使用 bitwise_not (OpenCV-Python) 反转它时,图像掩码不起作用
【发布时间】:2021-08-15 04:33:03
【问题描述】:

我正在尝试使用按位运算。在下面的代码中,我使用了 2 个图像(img1,img2)。我使用 img2 创建了两个蒙版(gray_inv 和 gray_test)。

img1 = cv2.imread('Computer-Vision-with-Python/DATA/dog_backpack.jpg')
img1 = cv2.cvtColor(img1,cv2.COLOR_BGR2RGB)
img1 = img1[0:600,0:600]

img2 = cv2.imread('Computer-Vision-with-Python/DATA/watermark_no_copy.png')
img2 = cv2.cvtColor(img2,cv2.COLOR_BGR2RGB)
img2 = cv2.resize(img2,(600,600))

gray = cv2.cvtColor(img2,cv2.COLOR_BGR2GRAY)
gray_inv = cv2.bitwise_not(gray)
gray_test = cv2.bitwise_not(gray_inv) 

我使用 bitwise_or 函数与 img1 合并。第一个面具工作正常。然而第二个没有。我错过了什么吗?理想情况下,由于它们是反向的 gray_inv 应该显示带有黑色文本的背景。

plt.imshow(cv2.bitwise_or(img1,img1, mask=gray_inv))

plt.imshow(cv2.bitwise_or(img1,img1, mask=gray_test))

【问题讨论】:

    标签: python-3.x opencv image-processing computer-vision opencv-python


    【解决方案1】:

    您需要“二值化”掩码。

    为了让您的代码正常工作,掩码应该是二进制图像。
    在 OpenCV 中,二值图像的约定是具有所有值 0255(并键入 np.uint8)的图像。

    仅使用0255 不是“必须”,但在使用cv2.bitwise_not(mask) 时,重要的是mask 是二进制的(然后所有零都反转为255,所有255 反转归零)。

    代码gray = cv2.cvtColor(img2,cv2.COLOR_BGR2GRAY),将img2 转换为灰度,但不转换为二值图像(并非所有值都是0255)。

    您可以应用阈值将gray 转换为二进制:

    thres_gray = cv2.threshold(gray, 0, 255, cv2.THRESH_OTSU)[1]  # threshold (binarize) the image
    

    使用thres_gray 代替gray

    gray_inv = cv2.bitwise_not(thres_gray)
    gray_test = cv2.bitwise_not(gray_inv)
    

    以下代码示例演示了解决方案:

    import cv2
    import numpy as np
    
    img1 = cv2.imread('img1.png')
    img1 = cv2.resize(img1, (100,100))
    
    img2 = cv2.imread('img2.png')
    img2 = cv2.resize(img2, (100,100))
    
    gray = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY)
    
    thres_gray = cv2.threshold(gray, 0, 255, cv2.THRESH_OTSU)[1]  # threshold (binarize) the image
    
    gray_inv = cv2.bitwise_not(thres_gray)
    gray_test = cv2.bitwise_not(gray_inv) 
    
    out2 = cv2.bitwise_or(img1, img1, mask=gray_inv)
    out3 = cv2.bitwise_or(img1, img1, mask=gray_test)
    
    cv2.imshow('out2', out2)
    cv2.imshow('out3', out3)
    cv2.waitKey()
    cv2.destroyAllWindows()
    

    out2:

    out3:

    【讨论】:

    • 我完全同意掩码应该是二进制图像并且解决方案有效。但是在这种情况下:plt.imshow(cv2.bitwise_or(img1,img1, mask=gray_inv)) 其中 gray_inv 是灰度图像的 bitwise_not 也不应该工作(输出 2)。为什么掩码在那里(即gray_inv)蚂蚁不与gray_inv的bitwise_not(即gray_test -output3)一起工作?
    • OpenCV 掩码规则类似于大多数编程语言中的布尔表达式:0 的计算结果为 false,其他值的计算结果为 true。在您的情况下,范围 [1, 255] 中的所有值都被屏蔽为“true”。 [0, 254] 范围内数字的bitwise_not 不是零,也被屏蔽为“真”。
    【解决方案2】:

    对于您所描述的效果,您不需要按位或。您想将值相乘。所以output = input1 * input2 / 255

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-10
      相关资源
      最近更新 更多