Python實現K-means演算法的顏色量化

jieforest發表於2012-08-01
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/,如需轉載,請註明出處,否則將追究法律責任。

相關文章