Skip to content Skip to sidebar Skip to footer

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 amb

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

enter image description here

You will get this mask:

enter image description here

Solution 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 inrange(h):
    for l inrange(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

Post a Comment for "Issues Related To Creating Mask Of An Rgb Image In Opencv Python"