0

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.

Levi
  • 175
  • 1
  • 2
  • 13
  • possible duplicate of http://stackoverflow.com/questions/30879446/efficiently-count-the-number-of-occurrences-of-unique-subarrays-in-numpy – Divakar Nov 11 '15 at 06:30
  • it's great. but i also want to count the same pixel – Levi Nov 11 '15 at 06:33
  • Linked a more relevant question that deals with counts. Did you check out the latest linked question? – Divakar Nov 11 '15 at 06:34
  • Yeah. I check the lastest question, and it work perfectly. Thanks Divakar – Levi Nov 11 '15 at 06:38
  • oh. I just get the result like (72370, 8), (72371, 20), (72372, 6). Image pixel seem to nested with 3 level.@Divakar – Levi Nov 11 '15 at 07:03

2 Answers2

0

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})
Ricky Wilson
  • 3,187
  • 4
  • 24
  • 29
  • Doesn't look like that's the desired output. Each row in the matrix is considered a unique "value", and you want to count how many times you see each "value". – rayryeng Nov 11 '15 at 07:00
0

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

Thomas Baruchel
  • 7,236
  • 2
  • 27
  • 46
  • Really thanks. Infact what I want is converting this code to python: index = (unsigned char) gray->imageData[i * gray->widthStep + j]; – Levi Nov 11 '15 at 07:46
  • gray is a grayscale image. and i is height, j is width – Levi Nov 11 '15 at 07:48