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[2] == 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) &amp; (img[:, :, 1] == 127) &amp; (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.
Your original code can be rewritten as:

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


It is a little cleaner, but not more efficient, as it still has to allocate a mask of the same size as the image.