How do I find the most common RGBA pixel value in a image?

Viewed 123

I have an image of a dog, which has shape (432, 575, 4). The 3rd dimension in the ndarray contains the RGBA values for each pixel. I want to find out what the most common pixel is, i.e. the mode.

For a 2d array, I can use the following line: np.unique(a, axis=0, return_counts=True)

However, I can't work out how to only compare the vectors in the 3rd dimension of a 3d array. This question is similar, but it only works for a 2d array: Finding the most common subarray within a numpy array. If I simply change the axis to '=1`, it doesn't give me the result that I need.

1 Answers

Since you don't care for the image's shape, you can use reshape to flatten your image and use the linked answer:

rgba, counts = np.unique(a.reshape(-1,4), axis=0, return_counts=True)

# the mode here
rgba[np.argmax(counts)]
Related