nim.py
nim.py

Reputation: 477

What is the most pythonic way of generating a boolean mask of an RGB image based on the colour of the pixels?

I have an image with a missing part that I know has been coloured in green (first image). What is the most pythonic way of generating another "boolean" image that shows white for the missing parts and black for the non-missing parts (second image)?

Image with missing part coloured in green Image that shows the missing part (mask) in white, and the rest in black

Is it possible to do it without a for-loop, but just with array slicing?

My image is a numpy array of shape [height, width, 3]. I would like the following code to assign a two-dimensional array of booleans showing whether the value of each pixel is green ([0, 255, 0]) or not.

mask = image[:, :] == [0, 255, 0]

However, it returns an array of the same shape as the image ([height, width, 3]), showing if red, green, or blue values of the pixels are 0, 255, or 0, respectively. Could I perhaps use any() or all() method here somehow?

Upvotes: 5

Views: 2330

Answers (2)

nathancy
nathancy

Reputation: 46680

The idea is to create a blank mask using np.zeros then color pixels white where the input image pixels are green with np.where. The resulting mask should be of type ndarray.

import cv2
import numpy as np

# Load image, create blank black mask, and color mask pixels 
# white where input image pixels are green
image = cv2.imread('1.png')
mask = np.zeros(image.shape, dtype=np.uint8)
mask[np.where((image == [0,255,0]).all(axis=2))] = [255,255,255]

cv2.imshow('mask', mask)
cv2.waitKey()

enter image description here

Upvotes: 1

cadolphs
cadolphs

Reputation: 9657

You have the right idea here. The thing to use would be numpy's alltrue:

mask = np.alltrue(image == [0, 255, 0], axis=2)

Upvotes: 5

Related Questions