备注
Go to the end 下载完整的示例代码。或者通过浏览器中的MysterLite或Binder运行此示例
硬币图像上的结构化Ward分层集群演示#
用Ward层次聚类计算2D图像的分割。聚类在空间上受到约束,以便使每个分割区域成为一片。
# Authors: The scikit-learn developers
# SPDX-License-Identifier: BSD-3-Clause
生成数据#
from skimage.data import coins
orig_coins = coins()
将其大小调整为原始大小的20%以加快处理速度在缩小缩放之前应用高斯过滤器进行平滑可以减少混叠伪影。
import numpy as np
from scipy.ndimage import gaussian_filter
from skimage.transform import rescale
smoothened_coins = gaussian_filter(orig_coins, sigma=2)
rescaled_coins = rescale(
smoothened_coins,
0.2,
mode="reflect",
anti_aliasing=False,
)
X = np.reshape(rescaled_coins, (-1, 1))
定义数据结构#
像素与它们的邻居相连。
from sklearn.feature_extraction.image import grid_to_graph
connectivity = grid_to_graph(*rescaled_coins.shape)
计算聚类#
import time as time
from sklearn.cluster import AgglomerativeClustering
print("Compute structured hierarchical clustering...")
st = time.time()
n_clusters = 27 # number of regions
ward = AgglomerativeClustering(
n_clusters=n_clusters, linkage="ward", connectivity=connectivity
)
ward.fit(X)
label = np.reshape(ward.labels_, rescaled_coins.shape)
print(f"Elapsed time: {time.time() - st:.3f}s")
print(f"Number of pixels: {label.size}")
print(f"Number of clusters: {np.unique(label).size}")
Compute structured hierarchical clustering...
Elapsed time: 0.110s
Number of pixels: 4697
Number of clusters: 27
将结果绘制在图像上#
聚集聚类能够分割每个硬币,但是,我们不得不使用 n_cluster
比硬币的数量要大,因为分割在背景中找到了很大的。
import matplotlib.pyplot as plt
plt.figure(figsize=(5, 5))
plt.imshow(rescaled_coins, cmap=plt.cm.gray)
for l in range(n_clusters):
plt.contour(
label == l,
colors=[
plt.cm.nipy_spectral(l / float(n_clusters)),
],
)
plt.axis("off")
plt.show()

Total running time of the script: (0分0.295秒)
相关实例
Gallery generated by Sphinx-Gallery <https://sphinx-gallery.github.io>
_