'How to get the count of total number of pixels under each unique color in an image using python?
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.
Solution 1:[1]
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)
colorswill be a 2-dimensional array whose rows give unique pixel values.countswill 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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
