Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Find RGB pixels with same r,g and b value

I’ve a basic image:

enter image description here

Is there a way to quickly get the list of pixels (a mask) that have the same r, g and b pixel value?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

In the example this corresponds to the gray square in the center of the image because each pixel in the gray square has the value (100, 100, 100)

The resulting mask should be something like this:

enter image description here

I have no clue how to do this (fast),
I’ve isolated the r,g,b channels but I have no ideas

This is my code so far:

import numpy as np
from matplotlib import pyplot as plt

#Make the test image
img = np.full((512,512,3), dtype = np.uint8, fill_value = (255,0,255))
img[200:300, 200:300] = (100,100,100)

#get r,g,b
red = img[...,0]
green = img[...,1]
blue = img[...,2]

plt.imshow(img)
plt.show()

>Solution :

Absolutely!

All you need to do is check that the data in column 0, 1, and 2 are equal. Since numpy arrays have an ambiguous truth value, you won’t be able to chain the == operators like you can do with vanilla-python data types, so you’re going to have to compare two colors at a time, and then elementwise-and them:

equal_mask = (red == green) & (green == blue)

Using np.logical_and instead, you could do:

rg = np.logical_and(red, green)
equal_mask = np.logical_and(rg, blue)

or, in one line:

equal_mask = np.logical_and(np.logical_and(red, green), blue)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading