K-MEANS聚类之图像分割Python实现
K-MEANS聚类再上上一章就详细介绍完了,接下来我们做一个小小的图像分割。
第一步:导包和导入图片
from matplotlib.image import imread
from sklearn.cluster import KMeans
import matplotlib.pyplot as plt
import numpy as np
image=imread('C:/Users/bwy/Desktop/嘿嘿哈嘿.jpg')
然后我们看一下图片的shape:
image.shape
(1280, 960, 3)三维的,由于k-means是两个参数所以我们需要reshape()
2.reshape
X=image.reshape(-1,3)
X.shape
结果:(-1代表1280*960)
(1228800, 3)
3 大招出场
segmented_imgs=[]
n_colors=(10,8,6,4,1)
for n_cluster in n_colors:
kmeans=KMeans(n_clusters=n_cluster,random_state=142).fit(X)
segmented_img=kmeans.cluster_centers_[kmeans.labels_].reshape(image.shape)
new_segmented_img=np.around(segmented_img).astype(int)
segmented_imgs.append(new_segmented_img)
4.图像显示
plt.figure(figsize=(8,6))
plt.subplot(231)
plt.imshow(image)
plt.title('Original image')
for idx,n_clusters in enumerate(n_colors):
plt.subplot(232+idx)
plt.imshow(segmented_imgs[idx])
plt.title('{}colors'.format(n_clusters))
结果如图:
不要慌,不要慌,太阳下山有月光,月亮落下有朝阳。(●ˇ∀ˇ●)
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
THE END
二维码