整体思路
目录
读取图像并转化为数据类型
构造Kmeans聚类器进行聚类
获取聚类中心点
主颜色可视化
k-means聚类分析
k-means导图
完整代码与结果
import os.path
from flask import Flask,render_template
from PIL import Image
import matplotlib.pyplot as plt
import numpy as np
from scipy.cluster.vq import vq, kmeans, whiten
def colorz(filename,n=3):
img=Image.open(filename)
img=img.rotate(-90)
img.thumbnail((200,200))
w,h=img.size
print(w,h)
print('w*h=',w*h)
plt.axis('off')
plt.imshow(img)
plt.show()
points=[]
for count,color in img.getcolors(w*h):
points.append(color)
return points
def kmeansColor(img,n):
points=colorz(img,3)
fe = np.array
codebook, distortion = kmeans()
centers = np.array(codebook,dtype=float)
return centers
points=colorz('1.jpg',3)
print(points[0:10])
fe = np.array(points,dtype=float) #聚类需要是Float或者Double
print(fe[0:10])
book =np.array((fe[100],fe[1],fe[8],fe[8])) #聚类中心,初始值
print(type(book))
print("book: \n",book)
#codebook, distortion = kmeans(fe,book)
codebook, distortion = kmeans(fe,7) #7是聚类中心个数
# 可以写kmeans(wf,2), 2表示两个质心,同时启用iter参数
print("codebook:", codebook) #聚类中心
centers=np.array(codebook,dtype=int) #变为色彩,还得转为整数
print(centers)
print("distortion: ", distortion)
fe=np.array(points)
plt.scatter(fe[:,0], fe[:,2], c='b')
plt.scatter(codebook[:, 0], codebook[:,2], c='r') #聚类中心
plt.show()