![](/img/trans.png)
[英]Python : count the number of different values for a given attribute in a list of objects
[英]Count the number of objects of different colors in an image in Python
這是一張我要從中計算每種顏色的對象數的 圖表 。 什么是不使用opencv的簡單方法?
[編輯2]:我嘗試過的方法如下:(1)有色物體計數
from PIL import Image
im = Image.open('./colored-polka-dots.png').getcolors()
im.sort(key=lambda k: (k[0]), reverse=True)
print('Top 5 colors: {}'.format((im[:5])))
# View non-background colors
color_values = []
for color in im[1:5]:
color_values.append(color[1])
arr = np.asarray(color[1]).reshape(1,1,4).astype(np.uint8)
plt.imshow(arr)
plt.show() # get top 4 frequent colors as green,blue,pink,ornage
# Create a dict of color names and their corressponding rgba values
color_dict = {}
for color_name,color_val in zip(['green','blue','pink','orange'],color_values):
color_dict[color_name] = color_val
# Make use of ndimage.measurement.labels from scipy
# to get the number of distinct connected features that satisfy a given threshold
for color_name,color_val in color_dict.items():
b = ((img[:,:,0] ==color_val[0]) * (img[:,:,1] ==color_val[1]) * (img[:,:,2] ==color_val[2]))*1
labeled_array, num_features = scipy.ndimage.measurements.label(b.astype('Int8'))
print('Color:{} Count:{}'.format(color_name,num_features))
>輸出:
orange: 288
green: 288
pink: 288
blue: 288
盡管這達到了目的,但我想知道是否有更有效,更優雅的方法來解決此問題。
這是一個基於scikit-image
的簡單解決方案:
代碼 :
import numpy as np
from skimage import io, morphology, measure
from sklearn.cluster import KMeans
img = io.imread('https://i.stack.imgur.com/du0XZ.png')
rows, cols, bands = img.shape
X = img.reshape(rows*cols, bands)
kmeans = KMeans(n_clusters=5, random_state=0).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: [ 254. 253. 253. 255.] >> Objects: 1
Color: [ 255. 144. 36. 255.] >> Objects: 288
Color: [ 39. 215. 239. 255.] >> Objects: 288
Color: [ 255. 38. 135. 255.] >> Objects: 288
Color: [ 192. 231. 80. 255.] >> Objects: 288
備注 :
聚類中心的RGB坐標已四舍五入around
僅用於可視化目的。
我還通過binary_opening
執行了打開操作,以擺脫孤立的像素。
必須將標簽產生的label
數量減去1
,以僅考慮那些帶有考慮顏色標簽的連接區域。
輸出的第一行顯然對應於白色背景。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.