2

I have a segmented output image of size (513,513,3) and the unique values it carries is [0 200 255]. I want to get the total number of pixels under each unique color. Like get total number of pixels that are 0(black), total number of pixels that are 200(green), and total number of pixels that are 255(white).

I tried something like this:

for i in range(img.shape[-1]):
  mask = img[0, :, i].sum() 

But i feel that its wrong way of get the pixel counts under each unique color. I am new with images, please help in solving this.

sinG20
  • 143
  • 2
  • 15
  • 1
    Does this answer your question? [fastest way to find the rgb pixel color count of image](https://stackoverflow.com/questions/59669715/fastest-way-to-find-the-rgb-pixel-color-count-of-image) – bb1 Sep 06 '21 at 05:28

1 Answers1

6

Assuming that the image is represented by a numpy array img of the shape (m, n, 3) you can try the following:

import numpy as np

colors, counts = np.unique(img.reshape(-1, 3), axis=0, return_counts=True)
  • colors will be a 2-dimensional array whose rows give unique pixel values.
  • counts will be a 1-dimensional array that gives the number of occurrences of the corresponding pixel value.

For the image attached to your question is gives:

colors = [[  0   0   0]
          [  0 200   0]
          [255 255 255]]

counts = [144741,  10375, 108053]

Thus, there are three colors: [0, 0, 0] (black), [0, 200, 0] (green), and [255 255 255] (white) with the corresponding pixel counts 144741, 10375, and 108053.

Edit. I have realized that this had been already answered several times e.g. here, here or here. I will vote to close as a duplicate.

bb1
  • 7,174
  • 2
  • 8
  • 23