Issues related to creating mask of an RGB image in

2019-08-19 05:57发布

问题:

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