def find_a_dominant_color(image):
# K-mean clustering to find the k most dominant color, from:
# http://stackoverflow.com/questions/3241929/python-find-dominant-most-common-color-in-an-image
n_clusters = 5
# Get image into a workable form
im = image.copy()
im = im.resize((150, 150)) # optional, to reduce time
ar = scipy.misc.fromimage(im)
im_shape = ar.shape
ar = ar.reshape(scipy.product(im_shape[:2]), im_shape[2])
ar = np.float_(ar)
# Compute clusters
codes, dist = scipy.cluster.vq.kmeans(ar, n_clusters)
vecs, dist = scipy.cluster.vq.vq(ar, codes) # assign codes
counts, bins = scipy.histogram(vecs, len(codes)) # count occurrences
# Get the indexes of the most frequent, 2nd most frequent, 3rd, ...
sorted_idxs = np.argsort(counts)
# Get the color
peak = codes[sorted_idxs[1]] # get second most frequent color
return [int(i) for i in peak.tolist()] # list comprehension to quickly cast everything to int
评论列表
文章目录