# Comparing pixels against RGB value in NumPy

Assume I created an image in NumPy:

image = imread(...)


And the image is RGB:

assert len(image.shape) == 3 and image.shape == 3


I want to check (i.e. get a boolean mask) which pixels are (R=255, G=127, B=63) in a cleaner and efficient way:

mask = (img[:, :, 0] == 255) & (img[:, :, 1] == 127) & (img[:, :, 2] == 63)


This code worked for me. However - please correct me if I'm wrong - this code is creating three intermediate masks and, since I'm processing images, those masks will be pretty big.

I need help with:

• Is there a way to make boolean masks occupy 1 bit per element, instead of 1 byte per element?
• Is there a way to solve the same problem without creating the three intermediate boolean masks?

This code did not work:

mask = img == (255, 127, 63)


neither this:

mask = img[:, :, :] == (255, 127, 63)


since the comparison was performed element-wise, and the resulting values were performed element-wise, yielding a 3-dimension (w, h, 3) boolean mask.

• Please add the language tag as well. I'm also not sure if this would be enough code for review (someone else may be able to determine that). Jan 29, 2016 at 17:03
• Added the language. Thanks. Anyway, the code I have doubts about, has one-liners like this. Other code is irrelevant to my problem. Jan 29, 2016 at 17:05

mask = np.all(img == (255, 127, 63), axis=-1)