.. DO NOT EDIT. .. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. .. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: .. "auto_examples/cluster/plot_coin_ward_segmentation.py" .. LINE NUMBERS ARE GIVEN BELOW. .. only:: html .. note:: :class: sphx-glr-download-link-note :ref:`Go to the end ` to download the full example code. or to run this example in your browser via Binder .. rst-class:: sphx-glr-example-title .. _sphx_glr_auto_examples_cluster_plot_coin_ward_segmentation.py: ====================================================================== A demo of structured Ward hierarchical clustering on an image of coins ====================================================================== Compute the segmentation of a 2D image with Ward hierarchical clustering. The clustering is spatially constrained in order for each segmented region to be in one piece. .. GENERATED FROM PYTHON SOURCE LINES 11-15 .. code-block:: Python # Authors: The scikit-learn developers # SPDX-License-Identifier: BSD-3-Clause .. GENERATED FROM PYTHON SOURCE LINES 16-18 Generate data ------------- .. GENERATED FROM PYTHON SOURCE LINES 18-23 .. code-block:: Python from skimage.data import coins orig_coins = coins() .. GENERATED FROM PYTHON SOURCE LINES 24-27 Resize it to 20% of the original size to speed up the processing Applying a Gaussian filter for smoothing prior to down-scaling reduces aliasing artifacts. .. GENERATED FROM PYTHON SOURCE LINES 27-42 .. code-block:: Python 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)) .. GENERATED FROM PYTHON SOURCE LINES 43-47 Define structure of the data ---------------------------- Pixels are connected to their neighbors. .. GENERATED FROM PYTHON SOURCE LINES 47-52 .. code-block:: Python from sklearn.feature_extraction.image import grid_to_graph connectivity = grid_to_graph(*rescaled_coins.shape) .. GENERATED FROM PYTHON SOURCE LINES 53-55 Compute clustering ------------------ .. GENERATED FROM PYTHON SOURCE LINES 55-72 .. code-block:: Python 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}") .. rst-class:: sphx-glr-script-out .. code-block:: none Compute structured hierarchical clustering... Elapsed time: 0.126s Number of pixels: 4697 Number of clusters: 27 .. GENERATED FROM PYTHON SOURCE LINES 73-79 Plot the results on an image ---------------------------- Agglomerative clustering is able to segment each coin however, we have had to use a ``n_cluster`` larger than the number of coins because the segmentation is finding a large in the background. .. GENERATED FROM PYTHON SOURCE LINES 79-93 .. code-block:: Python 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() .. image-sg:: /auto_examples/cluster/images/sphx_glr_plot_coin_ward_segmentation_001.png :alt: plot coin ward segmentation :srcset: /auto_examples/cluster/images/sphx_glr_plot_coin_ward_segmentation_001.png :class: sphx-glr-single-img .. rst-class:: sphx-glr-timing **Total running time of the script:** (0 minutes 0.333 seconds) .. _sphx_glr_download_auto_examples_cluster_plot_coin_ward_segmentation.py: .. only:: html .. container:: sphx-glr-footer sphx-glr-footer-example .. container:: binder-badge .. image:: images/binder_badge_logo.svg :target: https://mybinder.org/v2/gh/scikit-learn/scikit-learn/main?urlpath=lab/tree/notebooks/auto_examples/cluster/plot_coin_ward_segmentation.ipynb :alt: Launch binder :width: 150 px .. container:: sphx-glr-download sphx-glr-download-jupyter :download:`Download Jupyter notebook: plot_coin_ward_segmentation.ipynb ` .. container:: sphx-glr-download sphx-glr-download-python :download:`Download Python source code: plot_coin_ward_segmentation.py ` .. container:: sphx-glr-download sphx-glr-download-zip :download:`Download zipped: plot_coin_ward_segmentation.zip ` .. include:: plot_coin_ward_segmentation.recommendations .. only:: html .. rst-class:: sphx-glr-signature `Gallery generated by Sphinx-Gallery `_