使用 cv2.bitwise 时颜色错误
Wrong colors when using cv2.bitwise
我在使用 cv2.bitwise 时遇到了问题,如最后所见,我得到了粉红色的图像,而我期望的是绿色。
但是我不明白为什么。
import cv2
import numpy as np
img = cv2.imread("image.png")[...,::-1]
shape = img.shape # 512,512,3
label = cv2.imread("mask.png", cv2.COLOR_BGR2GRAY)
shape = label.shape # 512,512
black_background = np.zeros(shape=shape, dtype=np.uint8)
shape = black_background.shape # 512,512
result = cv2.bitwise_not(img,black_background,mask=label)
cv2.imwrite("masked.png",result)
感谢您以后的帮助!
这是因为您没有对 img
输入的每一位进行反相处理,所以颜色与预期不符。您可以通过在之前输入一次 img
来解决这个问题,以便第二次操作 returns 它达到预期的颜色,如下所示:
img2 = img.copy()
cv2.bitwise_not(img, img2)
result = cv2.bitwise_not(img2, black_background, mask=label)
cv2.imwrite("masked.png",result)
编辑:
或者,您可以将 img
添加到匹配形状的黑色图像中,这样颜色就不会被弄乱,就像这样:
black = np.zeros(shape=img.shape, dtype=np.uint8)
result = cv2.add(img, black, black_background, mask=label)
cv2.imwrite("masked2.png", result)
我在使用 cv2.bitwise 时遇到了问题,如最后所见,我得到了粉红色的图像,而我期望的是绿色。 但是我不明白为什么。
import cv2
import numpy as np
img = cv2.imread("image.png")[...,::-1]
shape = img.shape # 512,512,3
label = cv2.imread("mask.png", cv2.COLOR_BGR2GRAY)
shape = label.shape # 512,512
black_background = np.zeros(shape=shape, dtype=np.uint8)
shape = black_background.shape # 512,512
result = cv2.bitwise_not(img,black_background,mask=label)
cv2.imwrite("masked.png",result)
感谢您以后的帮助!
这是因为您没有对 img
输入的每一位进行反相处理,所以颜色与预期不符。您可以通过在之前输入一次 img
来解决这个问题,以便第二次操作 returns 它达到预期的颜色,如下所示:
img2 = img.copy()
cv2.bitwise_not(img, img2)
result = cv2.bitwise_not(img2, black_background, mask=label)
cv2.imwrite("masked.png",result)
编辑:
或者,您可以将 img
添加到匹配形状的黑色图像中,这样颜色就不会被弄乱,就像这样:
black = np.zeros(shape=img.shape, dtype=np.uint8)
result = cv2.add(img, black, black_background, mask=label)
cv2.imwrite("masked2.png", result)