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 !
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With