patternpythonModerate
Comparing pixels against RGB value in NumPy
Viewed 0 times
comparingnumpyvalueagainstpixelsrgb
Problem
Assume I created an image in NumPy:
And the image is RGB:
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:
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:
This code did not work:
neither this:
since the comparison was performed element-wise, and the resulting values were performed element-wise, yielding a 3-dimension (w, h, 3) boolean mask.
image = imread(...)And the image is RGB:
assert len(image.shape) == 3 and image.shape[2] == 3I 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.
Solution
Your original code can be rewritten as:
It is a little cleaner, but not more efficient, as it still has to allocate a mask of the same size as the image.
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.
Code Snippets
mask = np.all(img == (255, 127, 63), axis=-1)Context
StackExchange Code Review Q#118286, answer score: 16
Revisions (0)
No revisions yet.