I have an RGB image -ndarray- and I want to count the occurrence of some colors like [255,0,0] or [0,0,255] in this image.
example of image data
np.ones((3, 3, 3)) * 255
array([[[255., 255., 255.],
[255., 255., 255.],
[255., 255., 255.]],
[[255., 255., 255.],
[255., 255., 255.],
[255., 255., 255.]],
[[255., 255., 255.],
[255., 255., 255.],
[255., 255., 255.]]])
So as result I want something like this
{
'[255,255,255]' : 9,
}
One solution could be the Counter function:
from collections import Counter
import numpy as np
# Generate some data
data = np.ones((10, 20, 3)) * 255
# Convert to tuple list
data_tuple = [ tuple(x) for x in data.reshape(-1,3)]
Counter(data_tuple)
Returns:
Counter({(255.0, 255.0, 255.0): 200})
Whereas its possible to use Counter or opencv histogram function to compute frequency of every single pixel , for specific pixels, its more efficient to use this:
import numpy as np
ar = np.ones([3,3,3]) *255
ar[1,1,:] = [0, 0, 200]
pixels = dict()
pixels['[255, 255, 255]'] = np.sum(np.all(ar == [255,255, 255], axis = 2))
pixels['[0, 0, 200]'] = np.sum(np.all(ar == [0, 0, 200], axis = 2))
result : {'[255, 255, 255]': 8, '[0, 0, 200]': 1}
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