.. 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 JupyterLite or 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-16 .. code-block:: Python # Author : Vincent Michel, 2010 # Alexandre Gramfort, 2011 # License: BSD 3 clause .. GENERATED FROM PYTHON SOURCE LINES 17-19 Generate data ------------- .. GENERATED FROM PYTHON SOURCE LINES 19-24 .. code-block:: Python from skimage.data import coins orig_coins = coins() .. GENERATED FROM PYTHON SOURCE LINES 25-28 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 28-43 .. 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 44-48 Define structure of the data ---------------------------- Pixels are connected to their neighbors. .. GENERATED FROM PYTHON SOURCE LINES 48-53 .. code-block:: Python from sklearn.feature_extraction.image import grid_to_graph connectivity = grid_to_graph(*rescaled_coins.shape) .. GENERATED FROM PYTHON SOURCE LINES 54-56 Compute clustering ------------------ .. GENERATED FROM PYTHON SOURCE LINES 56-73 .. 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.159s Number of pixels: 4697 Number of clusters: 27 .. GENERATED FROM PYTHON SOURCE LINES 74-80 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 80-94 .. 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.348 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/1.4.X?urlpath=lab/tree/notebooks/auto_examples/cluster/plot_coin_ward_segmentation.ipynb :alt: Launch binder :width: 150 px .. container:: lite-badge .. image:: images/jupyterlite_badge_logo.svg :target: ../../lite/lab/?path=auto_examples/cluster/plot_coin_ward_segmentation.ipynb :alt: Launch JupyterLite :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 ` .. include:: plot_coin_ward_segmentation.recommendations .. only:: html .. rst-class:: sphx-glr-signature `Gallery generated by Sphinx-Gallery `_