Count the number of specific values in the numpy Count the number of specific rgb values in the image.

Asked 2 years ago, Updated 2 years ago, 49 views

The numpy shape is

It comes in this form, but I want to count each of these values when it's [255 255 255] It's different from the list, so I don't have a clue. The shape is (3024, 3024, 3) type

python numpy

2022-09-20 16:03

1 Answers

https://stackoverflow.com/questions/59669715/fastest-way-to-find-the-rgb-pixel-color-count-of-image

If you look at the answers on this link, there is a good answer.

Reshape the numpy array with (-1, 3) and count the number with unique.

I've changed it to counting pairs, not triple, so look at this is an example.

>>> import numpy as np

>>> arr = np.array([[[1,1],[2,2],[1,1]],
            [[2,3],[1,1],[4,4]]])
>>> arr
array([[[1, 1],
        [2, 2],
        [1, 1]],

       [[2, 3],
        [1, 1],
        [4, 4]]])
>>> arr.shape
(2, 3, 2)
>>> arr1 = arr.reshape((-1, 2))
>>> arr1
array([[1, 1],
       [2, 2],
       [1, 1],
       [2, 3],
       [1, 1],
       [4, 4]])
>>> np.unique(arr1)
array([1, 2, 3, 4])
>>> np.unique(arr1, axis=0, return_counts=True)
(array([[1, 1],
       [2, 2],
       [2, 3],
       [4, 4]]), array([3, 1, 1, 1], dtype=int64))

>>> values, counts = np.unique(arr1, axis=0, return_counts=1)
>>> values
array([[1, 1],
       [2, 2],
       [2, 3],
       [4, 4]])
>>> counts
array([3, 1, 1, 1], dtype=int64)
>>> for value, count in zip(*np.unique(arr1, axis=0, return_counts=1)):
    print(f"{value} {count})"


[11] These 3
[22] This one
[23] This one
[44] This one
>>> 


2022-09-20 16:03

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.