from PIL import Image
from sklearn.cluster import KMeans
import numpy as np

q = Image.open('10049.jpg')
# q.show()
m, n = q.size
q1 = np.array(q)
#这里有坑，注意q.size和q1.shape的值不一样，横竖跌倒

q1 = q1.reshape((m*n, 3))

k = 8
y = KMeans(n_clusters = k).fit_predict(q1)

centroids = np.zeros((k, 3))
#计算类心值，之后填充图像
for cent in range(k):
    centroids[cent] = q1[np.where(y == cent)].mean(axis = 0)
    
ynew = y.reshape((n, m))
pic_new = Image.new("RGB", (m, n))
for i in range(m):
    for j in range(n):
        pic_new.putpixel((i, j), tuple([int(x) for x in centroids[ynew[j][i]]]))
pic_new.show()