def find_dominant_colors(image):
"""Cluster the colors of the image in CLUSTER_NUMBER of clusters. Returns
an array of dominant colors reverse sorted by cluster size.
"""
array = img_as_float(fromimage(image))
# Reshape from MxNx4 to Mx4 array
array = array.reshape(scipy.product(array.shape[:2]), array.shape[2])
# Remove transparent pixels if any (channel 4 is alpha)
if array.shape[-1] > 3:
array = array[array[:, 3] == 1]
# Finding centroids (centroids are colors)
centroids, _ = kmeans(array, CLUSTER_NUMBER)
# Allocate pixel to a centroid cluster
observations, _ = vq(array, centroids)
# Calculate the number of pixels in a cluster
histogram, _ = scipy.histogram(observations, len(centroids))
# Sort centroids by number of pixels in their cluster
sorted_centroids = sorted(zip(centroids, histogram),
key=lambda x: x[1],
reverse=True)
sorted_colors = tuple((couple[0] for couple in sorted_centroids))
return sorted_colors
评论列表
文章目录