之前在几次建模比赛中也用到了K-Means,但当时都是用SPSS做的,一顿操作就完了,没有了解到原理和代码方面的东西。在此记录一下用K-Means聚类法对图片进行压缩实战,方便以后复习。
# -*- coding: utf-8 -*-
#K-Means聚类用在图像压缩
#导入KMeans库
from skimage import io
from sklearn.cluster import KMeans
import numpy as np
image = io.imread('tiger.png') #读图片
io.imshow(image)
io.show() #先看看长啥样
#看看行、列有多少个像素点
rows = image.shape[0]
cols = image.shape[1]
image = image.reshape(image.shape[0]*image.shape[1],3) #行*列变成2D,3个颜色通道
kmeans = KMeans(n_clusters = 128, n_init=10, max_iter=200) #聚类256->128个簇;迭代次数200
kmeans.fit(image)
clusters = np.asarray(kmeans.cluster_centers_,dtype=np.uint8)
labels = np.asarray(kmeans.labels_,dtype=np.uint8 ) #像素点发生变化
labels = labels.reshape(rows,cols) #再返回成图像
print (clusters.shape)
np.save('codebook_test.npy',clusters)
io.imsave('compressed_test.jpg',labels) #保存新图
image = io.imread('compressed_test.jpg')
io.imshow(image)
io.show()
出现了比较丑的黑白老虎…