天天看點

機器學習-學習記錄:KMeans聚類算法實作圖像分割

原圖檔:

機器學習-學習記錄:KMeans聚類算法實作圖像分割

代碼:

import numpy as np
import matplotlib.pyplot as plt
from skimage import io as io
from sklearn.cluster import KMeans
import pandas as pd

img = io.imread('D:\\1.jpg')
plt.imshow(img)
plt.show()

# 檢視資料結果和次元
print(type(img))
print(img.shape)

# 次元存儲
img_width = img.shape[1]
img_height = img.shape[0]

# 資料次元轉換
img_data = img.reshape(-1,3)
print(img_data.shape)

# 模型建立與訓練
model = KMeans(n_clusters=2,random_state=0)
model.fit(img_data)

# 結果預測
label = model.predict(img_data)
print(label)
print(pd.value_counts(label))

# 結果資料次元轉換
label = label.reshape([img_height,img_width])
print(label)
print(label.shape)

# 後續灰階處理
label = 1/(label+1)
print(label)

# 結果可視化
plt.imshow(label)
plt.show()

# 圖像存儲到本地
io.imsave('result_kmeans.png',label)
           

結果圖檔:

機器學習-學習記錄:KMeans聚類算法實作圖像分割

K值得不同,結果圖檔是不同的,可以試着修改K值,看一下結果圖檔的不同之初。