Clustering K-Means 图像压缩
-
本案例使用K-Means聚类算法对图像进行压缩,我们将图像由彩色图变为灰度图。对于彩色图而言,每一个像素点的取值范围都在0-255之间,接下来我们对它进行压缩。原来的范围为0-255,也即是256种可能性,现在我们通过聚类将这256种可能性压缩一半,变成128种可能性。
-
图像压缩前:
-
图像压缩前大小:
-
图像压缩后:
-
图像压缩后大小:
-
代码实现:
from skimage import io
from sklearn.cluster import KMeans
import numpy as np
image = io.imread('test.jpg')
# io.imshow(image)
# io.show()
rows = image.shape[0]
cols = image.shape[1]
image = image.reshape(image.shape[0] * image.shape[1], 4)
KMeans = KMeans(n_clusters=128, n_init=10, max_iter=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('test.npy', clusters)
io.imsave('out.jpg', labels)
image = io.imread('test.jpg')
io.imshow(image)
io.show()
完整代码已上传至Github,各位下载时麻烦给个follow和star,感谢!
链接:ClusteringK-Means 图像压缩