Search code examples
pythonnumpyunique

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,i.e. 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?


Solution

  • 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)