C/C++教程

第七节 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)

 

这篇关于第七节 Scipy-kmeans聚类色彩提取的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!