K-means聚類和矢量量化算法

K-means 是常見的聚類算法,主要思想是在集合中找到 K 箇中心,以中心爲基礎把集合分爲 k 個部分。html

矢量量化算法能夠看做基於 K-means 算法找出的 K 箇中心點,把中心點周圍的點的值用中心的值取代。python

實現

用 Python 提供的庫很容易能夠將一副圖像進行矢量量化。算法

#!/usr/bin/env python
from pylab import imread, imshow, figure, show, subplot
from numpy import reshape, uint8, flipud
from scipy.cluster.vq import kmeans,vq
from scipy import misc
import Image

quantization_layer = 16
img = imread('jet.jpg')
print img.shape
pixel = img

# performing the clustering
centroids,_ = kmeans(pixel, quantization_layer) # six colors will be found

# quantization
qnt,_ = vq(pixel,centroids)

centers_idx = qnt
clustered = centroids[centers_idx]

# display images
figure(1)
subplot(211)
imshow(img)
subplot(212)
imshow(clustered)
show()

參考

http://docs.scipy.org/doc/scipy/reference/generated/scipy.cluster.vq.kmeans.htmlui

http://blog.sina.com.cn/s/blog_49b5f5080101bfwa.html.net

http://blog.csdn.net/superdont/article/details/46399041code

相關文章
相關標籤/搜索