注意
跳转到末尾 以下载完整示例代码,或通过 JupyterLite 或 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.161s
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()

脚本总运行时间: (0 分钟 0.345 秒)
相关示例