Search code examples
pythonlistimagecountk-means

Get number of pixels in clusters with same color in an image


I have a black and white image where I want to count the pixels in each white spot (cluster). I am lost and I think it's missing just something I cant't think of. The Image looks like this: enter image description here

I already counted the number of clusters with KMeans like this:

from skimage import morphology, measure
from sklearn.cluster import KMeans

rows, cols, bands = img_converted.shape

X = img_converted.reshape(rows*cols, bands)

kmeans = KMeans(n_clusters=2, n_init='auto').fit(X)

labels = kmeans.labels_.reshape(rows, cols)

for i in np.unique(labels):
    blobs = np.int_(morphology.binary_opening(labels == i))    
    color = np.around(kmeans.cluster_centers_[i])
    count = len(np.unique(measure.label(blobs))) - 1
    print('Color: {}  >>  Objects: {}'.format(color, count))

Output:

Color: [0. 0. 0.]  >>  Objects: 1
Color: [255. 255. 255.]  >>  Objects: 217

I would like to have a List with the length of each of the 217 Objects I found. Maybe someone has a solution. Thanks for your help


Solution

  • To get the number of elements in each of the cluster, you could trivially count the frequency of each element in the measure.label(blobs) as shown below:

    list_of_labels = (measure.label(blobs).flatten().tolist())
    from collections import Counter
    print (Counter(list_of_labels))
    

    Output:

    Counter({0: 4289988,
             1: 1855,
             2: 130,
             3: 124,
              ..
              ..
             215: 97,
             216: 119,
             217: 210})