简体   繁体   中英

count frequency in nested numpy array

I want to count the same pixel frequency of a image. the src ndarray:

[
 [1, 2, 3],
 [1, 2, 3],
 [5, 6, 7]
]

The result i want is:

[
 [1, 2, 3, 2],
 [5, 6, 7, 1]
]

But the numpy.unique or numpy.bincount can't work.

Would this work.

from collections import Counter
import numpy as np
In [17]: freq = Counter(np.array(lst).flatten())
In [18]: freq
Out[18]: Counter({1: 2, 2: 2, 3: 2, 5: 1, 6: 1, 7: 1})

Are you dealing with RGB values in the [0..255] range? In this case you may try this.

You start from:

import numpy as np
a = np.array([[1,2,3],[1,2,3],[5,6,7]])

Create a bijection between ([0..255],[0..255],[0..255]) and [0..16777215]:

a_ = a[:,0]*256**2 + a[:,1]*256 + a[:,0]

Apply bincount:

b_ = np.bincount(a_)

Apply the reciprocal bijection:

h = []
for i,e in enumerate(b_):
    if e:
      b = i%256
      g = (i//256)%256
      r = i/65536
      h.append([r,g,b,e])

What you want will be in h

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM