1. 程式人生 > >【機器學習七】利用K-means壓縮圖片

【機器學習七】利用K-means壓縮圖片

在學習機器的過程中,發現了K-means的一種應用,遂那這個例子,練練手,增加對K-means的理解。 

# -- encoding:utf-8 --
"""
Create by yexm on 2018/11/24
"""

# coding:utf-8
import matplotlib.pyplot as plt
import numpy as np
from sklearn.cluster import KMeans
from sklearn.utils import shuffle
from sklearn import  metrics

def im_resize(imgData,pixel=64):
    w,h,rgb = imData.shape
    img = 0
    if rgb == 3 or rgb == 1:
        img = np.array(imData,dtype=np.float32)/255
    else:
        img = imData
    img0 = img.reshape(-1, rgb)
    x_train = shuffle(img0, random_state=28)#打亂資料
    algo = KMeans(n_clusters=pixel)
    algo.fit(x_train[:2000,:])
    x_class = algo.predict(img0)
    center = algo.cluster_centers_#各個簇中心座標
    n=0
    img1 = np.zeros([w, h, rgb])
    for i in range(w):
        for j in range(h):
            index = x_class[n]
            data = center[index]#用簇中心的值代表該簇內其他點的值
            img1[i,j]= data
            n+=1
    km_y_hat2 = algo.labels_
    print(metrics.silhouette_score(img0, x_class))#打印出輪廓係數(即聚類衡量的一種指標)
    return img1

if __name__ == "__main__":
    imData = plt.imread('143731404.jpg')#讀取當前目錄下的圖片
    imDataNew = im_resize(imData, pixel=64)#pixel值的是簇的資料即我們長說K-means中的K
    plt.imshow(imDataNew)
    plt.show()