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) & (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.

  • \$\begingroup\$ 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). \$\endgroup\$
    – Jamal
    Jan 29, 2016 at 17:03
  • \$\begingroup\$ Added the language. Thanks. Anyway, the code I have doubts about, has one-liners like this. Other code is irrelevant to my problem. \$\endgroup\$ Jan 29, 2016 at 17:05

1 Answer 1


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.

  • 1
    \$\begingroup\$ So there's no way to reduce the memory usage? \$\endgroup\$ Jan 29, 2016 at 21:24
  • \$\begingroup\$ you can always mix the vectorization of numpy with the branching of python to get different space-time tradeoffs, for example create one numpy row (third dimension) at a time and reduce them in python. \$\endgroup\$
    – Akababa
    Oct 16, 2019 at 4:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.