Search code examples
pythonopencvimage-processingmask

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


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?


Solution

  • 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:

    enter image description here

    You will get this mask:

    enter image description here