与在 opencv 中创建 RGB 图像掩码相关的问题 python

Issues related to creating mask of an RGB image in opencv python

我想根据像素值创建 RGB 图像的遮罩,但以下代码段会引发错误

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

如果需要,我可以提供图片。

这里是代码段

image = cv2.imread("abcd.png")
for k in range(image.shape[0]):
    for l in range(image.shape[1]):
        if(image[k][l]==[255,255,255]):
            mask[k][l]=255
        else:
            mask[k][l]=0

请问代码有什么问题?

上面的错误本身就有提示。您可以使用 numpy.all() 检查图像像素是否为白色。

新代码:

import cv2
import numpy as np

image = cv2.imread("image.png")
h, w = image.shape[:2]
mask = np.zeros((h, w))

for k in range(h):
    for l in range(w):
        if np.all(image[k][l]==255): # true if (image[k][l][0]==255 and image[k][l][1]==255 and image[k][l][1]==255)
           mask[k][l]=255

使用 for 循环迭代像素非常慢 - 尝试养成使用 Numpy 向量化处理的习惯。

import numpy as np
import cv2

# Load image
image = cv2.imread("start.png")

# Mask of white pixels - elements are True where image is White
Wmask =(im[:, :, 0:3] == [255,255,255]).all(2) 

# Save as PNG
cv2.imwrite('result.png', (Wmask*255).astype(np.uint8))

因此,从这张图片开始:

你会得到这个面具: