Python实现K-means算法的颜色量化

The aim of color clustering is to produce a small set of representative colors that capture the color properties of an image. Using the small set of color found by the clustering, a quantization process can be applied to the image to find a new version of the image that has been "simplified," both in colors and shapes.

In this post we will see how to use the K-Means algorithm to perform. color clustering and how to apply the quantization. Let's see the code:

CODE:

01.from pylab import imread,imshow,figure,show,subplot
02.from numpy import reshape,uint8,flipud
03.from scipy.cluster.vq import kmeans,vq
04.
05.img = imread('clearsky.jpg')
06.
07.# reshaping the pixels matrix
08.pixel = reshape(img,(img.shape[0]*img.shape[1],3))
09.
10.# performing the clustering
11.centroids,_ = kmeans(pixel,6) # six colors will be found
12.# quantization
13.qnt,_ = vq(pixel,centroids)
14.
15.# reshaping the result of the quantization
16.centers_idx = reshape(qnt,(img.shape[0],img.shape[1]))
17.clustered = centroids[centers_idx]
18.
19.figure(1)
20.subplot(211)
21.imshow(flipud(img))
22.subplot(212)
23.imshow(flipud(clustered))
24.show()

来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/301743/viewspace-739423/,如需转载,请注明出处,否则将追究法律责任。

转载于:http://blog.itpub.net/301743/viewspace-739423/

你可能感兴趣的:(python,数据结构与算法,人工智能)