K-Means的图像分割实例

import numpy as np
import matplotlib.pyplot as plt
import sklearn
from sklearn.linear_model import LinearRegression
from sklearn.linear_model import LogisticRegression
import pandas as pd
from sklearn.metrics import accuracy_score
from sklearn.metrics import mean_squared_error,r2_score
from sklearn.cluster import KMeans
from sklearn.neighbors import KNeighborsClassifier
from skimage import  io as io

#kmeans的聚类
img = io.imread('./OIP-C.jpg')
#维度存储
img_width = img.shape[1]#存储宽度
img_height = img.shape[0]#存储高度
#数据维度转换3维转2维
img_data = img.reshape(-1,3)
print(img_data.shape)

#模型的建立与训练
KM = KMeans(n_clusters=4,random_state=0)
KM.fit(img_data)
#聚类结果预测
label = KM.predict(img_data)
print(label)
print(pd.value_counts(label))

#结果的保存需要把转变的维度再转变回原来的维度
label1 = label.reshape([img_height,img_width])
print(label1)
#后续的灰度处理
label1 = 1/(label1+1)
print(label1)

#结果可视化
plt.imshow(label1)
plt.show()
io.imsave("./jieguo.jpg",label1)

结果:

K-Means的图像分割实例_第1张图片

K-Means的图像分割实例_第2张图片

 

 

你可能感兴趣的:(python,聚类,python,机器学习)