原图片:

代码:
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)
结果图片:
K值得不同,结果图片是不同的,可以试着修改K值,看一下结果图片的不同之初。