这是一个figure,我想从中计算每种颜色的对象数。不使用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))>
Output:
^{pr2}$
虽然这达到了目的,但我想知道是否有更有效和优雅的方法来解决这个问题。在