简体   繁体   中英

Finding count of unique triple in Numpy Ndarray

I have some image in ndarray form like this:

# **INPUT**
img = np.array(
[
    [
        [0, 0, 255],
        [0, 0, 255],
        [0, 0, 255],
        [0, 0, 255],
        [0, 0, 255],
        [0, 0, 255],
        [0, 0, 255],
        [0, 0, 255]
    ],
    [
        [255, 0, 0],
        [255, 0, 0],
        [255, 0, 0],
        [0, 255, 0],
        [0, 255, 0],
        [255, 0, 0],
        [255, 0, 0],
        [255, 0, 0]
    ],
    [
        [255, 0, 0],
        [0, 255, 0],
        [255, 0, 0],
        [255, 0, 0],
        [255, 0, 0],
        [255, 0, 0],
        [255, 0, 0],
        [255, 0, 0]
    ],
    [
        [255, 0, 0],
        [255, 0, 0],
        [255, 0, 0],
        [255, 0, 0],
        [255, 0, 0],
        [255, 0, 0],
        [255, 0, 0],
        [255, 0, 0]
    ],
])

I need to find count of each color in my image,ie count of 3 following tuples: [0, 0, 255],[255, 0, 0],[0, 255, 0] . In this case:

# **Desired OUTPUT**
 unique  [[  0   0 255]
 [255   0   0]
 [  0 255   0]]
 counts  [8 21 3]

this is what I have done:

print('AXIS 0 -----------------------------------')
unique0, counts0 = np.unique(img, axis=0, return_counts=True)
print('unique0 ', unique0)
print('counts0 ', counts0)

This is the output:

  AXIS 0 -----------------------------------
  unique0  [[[  0   0 255]
  [  0   0 255]
  [  0   0 255]
  [  0   0 255]
  [  0   0 255]
  [  0   0 255]
  [  0   0 255]
  [  0   0 255]]

 [[255   0   0]
  [  0 255   0]
  [255   0   0]
  [255   0   0]
  [255   0   0]
  [255   0   0]
  [255   0   0]
  [255   0   0]]

 [[255   0   0]
  [255   0   0]
  [255   0   0]
  [  0 255   0]
  [  0 255   0]
  [255   0   0]
  [255   0   0]
  [255   0   0]]

 [[255   0   0]
  [255   0   0]
  [255   0   0]
  [255   0   0]
  [255   0   0]
  [255   0   0]
  [255   0   0]
  [255   0   0]]]
counts0  [1 1 1 1]

I get similar result when trying with axis=1 (counts1 [2 1 5]).

I have also tried giving a tuple as axis input, axis=(0, 1) , which return the error TypeError: an integer is required (got type tuple) .

Any ideas what I am doing wrong?

You could do:

elements, counts = np.unique(img.reshape((-1, 3)), axis=0, return_counts=True)
print(elements, counts)

Output

[[  0   0 255]
 [  0 255   0]
 [255   0   0]] [ 8  3 21]

Start by using np.concatenate to concatenate the ndarray along the first axis, and then use np.unique as you where doing, setting return_counts=True , which will return the counts of the flattened 2D array:

unique, counts = np.unique(np.concatenate(mg), axis=0, return_counts=True)

print(unique)
[[  0   0 255]
 [  0 255   0]
 [255   0   0]]

print(counts)
# array([ 8,  3, 21], dtype=int64)

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