6
\$\begingroup\$

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.

\$\endgroup\$
  • \$\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 '16 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\$ – Luis Masuelli Jan 29 '16 at 17:05
11
\$\begingroup\$

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.

\$\endgroup\$
  • \$\begingroup\$ So there's no way to reduce the memory usage? \$\endgroup\$ – Luis Masuelli Jan 29 '16 at 21:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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