.. note:: :class: sphx-glr-download-link-note Click :ref:`here ` to download the full example code .. rst-class:: sphx-glr-example-title .. _sphx_glr_intro_scipy_auto_examples_plot_connect_measurements.py: ============================= Demo connected components ============================= Extracting and labeling connected components in a 2D array .. code-block:: python import numpy as np from matplotlib import pyplot as plt Generate some binary data .. code-block:: python np.random.seed(0) x, y = np.indices((100, 100)) sig = np.sin(2*np.pi*x/50.) * np.sin(2*np.pi*y/50.) * (1+x*y/50.**2)**2 mask = sig > 1 plt.figure(figsize=(7, 3.5)) plt.subplot(1, 2, 1) plt.imshow(sig) plt.axis('off') plt.title('sig') plt.subplot(1, 2, 2) plt.imshow(mask, cmap=plt.cm.gray) plt.axis('off') plt.title('mask') plt.subplots_adjust(wspace=.05, left=.01, bottom=.01, right=.99, top=.9) .. image:: /intro/scipy/auto_examples/images/sphx_glr_plot_connect_measurements_001.png :class: sphx-glr-single-img Label connected components .. code-block:: python from scipy import ndimage labels, nb = ndimage.label(mask) plt.figure(figsize=(3.5, 3.5)) plt.imshow(labels) plt.title('label') plt.axis('off') plt.subplots_adjust(wspace=.05, left=.01, bottom=.01, right=.99, top=.9) .. image:: /intro/scipy/auto_examples/images/sphx_glr_plot_connect_measurements_002.png :class: sphx-glr-single-img Extract the 4th connected component, and crop the array around it .. code-block:: python sl = ndimage.find_objects(labels==4) plt.figure(figsize=(3.5, 3.5)) plt.imshow(sig[sl[0]]) plt.title('Cropped connected component') plt.axis('off') plt.subplots_adjust(wspace=.05, left=.01, bottom=.01, right=.99, top=.9) plt.show() .. image:: /intro/scipy/auto_examples/images/sphx_glr_plot_connect_measurements_003.png :class: sphx-glr-single-img **Total running time of the script:** ( 0 minutes 0.047 seconds) .. _sphx_glr_download_intro_scipy_auto_examples_plot_connect_measurements.py: .. only :: html .. container:: sphx-glr-footer :class: sphx-glr-footer-example .. container:: sphx-glr-download :download:`Download Python source code: plot_connect_measurements.py ` .. container:: sphx-glr-download :download:`Download Jupyter notebook: plot_connect_measurements.ipynb ` .. only:: html .. rst-class:: sphx-glr-signature `Gallery generated by Sphinx-Gallery `_