当我使用 bitwise_not (OpenCV-Python) 反转它时,图像遮罩不起作用

Image mask not working when I invert it using bitwise_not (OpenCV-Python)

我正在尝试使用按位运算。在下面的代码中,我使用了 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))

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

您需要对蒙版进行“二值化”。

为了让您的代码正常工作,掩码应该是二进制图像。
在 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: