K-means算法应用:图片压缩

from sklearn.datasets import load_sample_image
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
import numpy as np
flower=load_sample_image('flower.jpg')#原始图片
plt.imshow(flower)
plt.show()

image=flower[::3,::3]#降低原始图片的分辨率
plt.imshow(image)
plt.show()

#利用Kmeans对图片进行压缩
x=image.reshape(-1,3)#改变数组的形状
n_colors=64
model=KMeans(n_colors)
labels=model.fit_predict(x)
colors=model.cluster_centers_
new_image=colors[labels]
new_image=new_image.reshape(image.shape)
plt.imshow(new_image.astype(np.uint8))
plt.show()

  

 

#原始图片与新图片所占用内存的大小
import sys
print(sys.getsizeof(flower))
print(sys.getsizeof(new_image))
#原始图片与新图片保存成文件
import matplotlib.image as img
img.imsave("F:\\flower.jpg",flower)
img.imsave("F:\\flower_zip.jpg",image)

 

 

 

 

posted on 2018-11-15 14:42  zz,ZZ  阅读(130)  评论(0编辑  收藏  举报

导航