Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Efficient way to count every pixels of an image of a particular value in Python?

I have an RGB image composed of 7 different possible colors. I want to count how many of each pixel type is present in the image, in an efficient way. So not a loop on every pixels if possible, at least not manually (numpy operation is ok beacause it's way faster)

I tried loading it into a numpy array, which gives me a N*M*3 array, but I can't figure out a way to count the pixels of a particular value... Any ideas?

Thank you !

like image 465
Adrien Nivaggioli Avatar asked Oct 29 '25 17:10

Adrien Nivaggioli


1 Answers

Just partially flatten and use np.unique with return_counts = True and axis = 0

flat_image = image.reshape(-1, 3)  # makes one long line of pixels
colors, counts = np.unique(flat_image, return_counts = True, axis = 0)

Or as one line:

colors, counts = np.unique(image.reshape(-1, 3), 
                           return_counts = True, 
                           axis = 0)
like image 157
Daniel F Avatar answered Oct 31 '25 08:10

Daniel F



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!