【发布时间】:2018-12-17 03:46:21
【问题描述】:
我是机器学习的新手,我正在学习用于图像分离的 k-mean,但我无法理解它的代码:
from matplotlib.image import imread
image = imread(os.path.join("images","unsupervised_learning","ladybug.png"))
image.shape
X = image.reshape(-1, 3)
kmeans = KMeans(n_clusters=8, random_state=42).fit(X)
segmented_img = kmeans.cluster_centers_[kmeans.labels_]
segmented_img = segmented_img.reshape(image.shape)
segmented_imgs = []
n_colors = (10, 8, 6, 4, 2)
for n_clusters in n_colors:
kmeans = KMeans(n_clusters=n_clusters, random_state=42).fit(X)
segmented_img = kmeans.cluster_centers_[kmeans.labels_]
segmented_imgs.append(segmented_img.reshape(image.shape))
plt.figure(figsize=(10,5))
plt.subplots_adjust(wspace=0.05, hspace=0.1)
plt.subplot(231)
plt.imshow(image)
plt.title("Original image")
plt.axis('off')
for idx, n_clusters in enumerate(n_colors):
plt.subplot(232 + idx)
plt.imshow(segmented_imgs[idx])
plt.title("{} colors".format(n_clusters))
plt.axis('off')
plt.show()
特别是这段代码的含义
segmented_img = kmeans.cluster_centers_[kmeans.labels_]
【问题讨论】:
-
你知道 k-means 是如何工作的吗?
-
这不是“分离”,它被称为“颜色量化”。了解正确的术语可能会帮助您找到相关的来源。例如,这里有很多关于颜色量化算法的问题,维基百科也有一篇关于它的合理文章。
-
是的,我知道 k-mean 是如何工作的
标签: python image image-processing machine-learning k-means