Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Occurrence of list in ndarray [duplicate]

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,
}
like image 232
zaki Avatar asked Dec 23 '25 00:12

zaki


2 Answers

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})
like image 188
Nakor Avatar answered Dec 24 '25 12:12

Nakor


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}

like image 41
Masoud Avatar answered Dec 24 '25 13:12

Masoud



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!