KMeans方法(待續…)
通過kmeans方法將圖像通過像素點大小值的不同進行聚類
比如下圖的喬巴
通過kmeans聚類得到
import numpy as np
import PIL.Image as image #PIL即python image library
from sklearn.cluster import KMeans
def loadData(filePath):
f = open(filePath,'rb')
data = []
img = image.open(f) #打開圖像
m,n = img.size #獲取圖像尺寸
for i in range(m):
for j in range(n):
x,y,z = img.getpixel((i,j)) #得到圖像像素(rgb值)如果是png圖像,要再加一個h參數
data.append([x/256.0,y/256.0,z/256.0])
f.close()
return np.mat(data),m,n
imgData,row,col = loadData('C:/Users/Lenovo/Desktop/2.jpg')
label = KMeans(n_clusters=3).fit_predict(imgData) #聚類,獲得每個像素的類別(有3類)
label = label.reshape([row,col])
pic_new = image.new("L", (row, col))
# 將圖像縮小爲0-1之間的數
for i in range(row):
for j in range(col):
pic_new.putpixel((i,j), int(256/(label[i][j]+1)))
pic_new.save("C:/Users/Lenovo/Desktop/result-bull-4.jpg", "JPEG") #保存