from sklearn.datasets import load_sample_imagefrom sklearn.cluster import KMeansimport matplotlib.pyplot as pltimport numpy as npchina = load_sample_image("china.jpg")#读取图片plt.imshow(china)plt.show()print(china.shape)#观察图片存放数据特点image = china[::3, ::3] #降低分辨率X = image .reshape(-1,3)plt.imshow(image)plt.show()print(image.shape,X.shape)n_colors =64 #(256,256,256)model = KMeans(n_colors) #k均值聚类算法,将图片中所有的颜色值做聚类labels = model.fit_predict(X) #每个点的颜色分类,0-63colors = model.cluster_centers_ #64个聚类中心,颜色值new_image=colors[labels] #用聚类中心的颜色代替原来的颜色值new_image=new_image.reshape(image.shape) #形成新的照片plt.imshow(new_image.astype(np.uint8))plt.show()import matplotlib.image as imgimg.imsave('F:\\china.jpg',china)img.imsave('F:\\china_zip.jpg',image)