python - 与在OpenCV Python中创建RGB图像的 mask 有关的问题

标签 python opencv image-processing mask

我想基于像素值创建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


我想知道代码中的问题是什么?

最佳答案

使用for循环遍历像素非常慢-尝试养成使用Numpy对 vector 进行矢量化处理的习惯。

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))

因此,从此图像开始:

enter image description here

您将获得此面具:

enter image description here

关于python - 与在OpenCV Python中创建RGB图像的 mask 有关的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56785080/

相关文章:

python - 获得一个数字的所有除数的最佳方法是什么?

c++ - 使用c++将Mat转换为opencv中的内存

macos - 带有OpenCV Mac的CMake(小牛)

python - 在 Python 中将 3 个单独的 numpy 数组组合为 RGB 图像

c# - 用c#替换图像中的颜色

python - 使用 ProcessPoolExecutor 进行并行处理

python - numpy的转置方法无法将一维行ndarray转换为一列

python - 使用 init_model 中的模型对 Pylons 应用程序进行 Nose 测试?

python - OpenCV 3.0缺少诸如drawMatches和drawMatchesKNN的方法

python - cv2.findContours 找不到轮廓