其他分享
首页 > 其他分享> > 第七节 Scipy-kmeans聚类色彩提取

第七节 Scipy-kmeans聚类色彩提取

作者:互联网

import numpy as np
from scipy.cluster.vq import vq, kmeans, whiten
import matplotlib.pyplot as plt

fe = np.array([[1.9,2.0],
                     [1.7,2.5],
                     [1.6,3.1],
                     [0.1,0.1],
                     [0.8,0.3],
                     [0.4,0.3],
                     [0.22,0.1],
                     [0.4, 0.3],
                     [0.4,0.5],
                     [1.8,1.9]])

book = np.array((fe[0], fe[1]))
print(type(book))
print("book: \n",book)

 注:先安装pip install scipy

2.聚类实例

codebook, distortion = kmeans(fe, book)
# 可以写kmeans(wf,2), 2表示两个质心,同时启用iter参数
print("codebook:", codebook)
print("distortion: ", distortion)

plt.scatter(fe[:,0], fe[:,1], c='g')
plt.scatter(codebook[:, 0], codebook[:, 1], c='r')
plt.show()

 3.取出图像的色彩和频次

import os
from PIL import Image
import matplotlib.pyplot as plt

os.chdir(r'C:\\Users')
print(os.getcwd())
im = np.array(Image.open(r'C:\Users\86159\Desktop\python\class7\niu.jpg'))

#用缩略图聚类
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
colorz(r'C:\Users\86159\Desktop\python\class7\niu.jpg',3)

 

标签:plt,img,kmeans,Scipy,fe,聚类,print,import,book
来源: https://blog.csdn.net/weixin_57434133/article/details/121279077