from sklearn.datasets import load_sample_image
from sklearn.cluster import KMeans
import matplotlib.pyplot as plt
import numpy as np
china=load_sample_image("china.jpg")
plt.imshow(china)
plt.show()
![](https://img2018.cnblogs.com/blog/1482909/201811/1482909-20181101114052309-1056711233.png)
image=china[::3,::3]#降低分辨率
X=image.reshape(-1,3)
print(china.shape,image.shape,X.shape)
![](https://img2018.cnblogs.com/blog/1482909/201811/1482909-20181101114212951-1797194449.png)
n_colors=64#(256,256,256)
model=KMeans(n_colors)
labels=model.fit_predict(X)
colors=model.cluster_centers_
plt.imshow(image);
plt.show()
plt.imshow(image.astype(np.uint8))
plt.show()
![](https://img2018.cnblogs.com/blog/1482909/201811/1482909-20181101114412799-1786167121.png)
#查看原始图片与新图片所占用内存的大小
import sys
print(sys.getsizeof(china))
print(sys.getsizeof(images)
![](https://img2018.cnblogs.com/blog/1482909/201811/1482909-20181105000230519-1744233280.png)
#将原始图片与新图片保存文件,观察文件大小
import matplotlib.image as img
img.imsave("C:\\china.jpg",china)
img.imsave("C:\\china_zip.jpg",images)
![](https://img2018.cnblogs.com/blog/1482909/201811/1482909-20181105000256303-1047561936.png)