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

匆匆过客 提交于 2019-12-11 17:16:44

问题


I want to create a mask of a RGB image based on a pixel value but the following code segment throws error

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

I can provide the image if it is at all required.

Here is the code segment

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

I wonder what is the problem in the code?


回答1:


Iterating over pixels with for loops is seriously slow - try to get in the habit of vectorising your processing with 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))

So, starting with this image:

You will get this mask:




回答2:


There is a hint in above error itself. You can use numpy.all() to check if an image pixel is white or not.

New code:

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


来源:https://stackoverflow.com/questions/56785080/issues-related-to-creating-mask-of-an-rgb-image-in-opencv-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!