获取图像中具有相同颜色的簇中的像素数

问题描述 投票:0回答:1

我有一张黑白图像,我想计算每个白点(簇)中的像素。我迷路了,我认为它缺少了一些我想不到的东西。图像看起来像这样: enter image description here

我已经用这样的 KMeans 计算了集群的数量:

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))

输出:

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

我想要一个列表,其中包含我找到的 217 个对象中每个对象的长度。也许有人有解决方案。 感谢您的帮助

python list image count k-means
1个回答
0
投票

要获得每个簇中的元素数量,您可以简单地计算

measure.label(blobs)
中每个元素的频率,如下所示:

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

输出:

Counter({0: 4289988,
         1: 1855,
         2: 130,
         3: 124,
          ..
          ..
         215: 97,
         216: 119,
         217: 210})
© www.soinside.com 2019 - 2024. All rights reserved.