在硬幣影像上進行結構化 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.162s
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()
plot coin ward segmentation

腳本的總執行時間: (0 分鐘 0.334 秒)

相關範例

階層分群:結構化 vs. 非結構化 Ward

階層分群:結構化 vs. 非結構化 Ward

比較玩具資料集上的不同階層連結方法

比較玩具資料集上的不同階層連結方法

具有不同度量的凝聚分群

具有不同度量的凝聚分群

具有和不具有結構的凝聚分群

具有和不具有結構的凝聚分群

由 Sphinx-Gallery 產生的圖庫