.. DO NOT EDIT. .. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. .. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: .. "advanced/image_processing/auto_examples/plot_clean_morpho.py" .. LINE NUMBERS ARE GIVEN BELOW. .. only:: html .. note:: :class: sphx-glr-download-link-note :ref:`Go to the end <sphx_glr_download_advanced_image_processing_auto_examples_plot_clean_morpho.py>` to download the full example code. .. rst-class:: sphx-glr-example-title .. _sphx_glr_advanced_image_processing_auto_examples_plot_clean_morpho.py: Cleaning segmentation with mathematical morphology =================================================== An example showing how to clean segmentation with mathematical morphology: removing small regions and holes. .. GENERATED FROM PYTHON SOURCE LINES 9-55 .. image-sg:: /advanced/image_processing/auto_examples/images/sphx_glr_plot_clean_morpho_001.png :alt: plot clean morpho :srcset: /advanced/image_processing/auto_examples/images/sphx_glr_plot_clean_morpho_001.png :class: sphx-glr-single-img .. code-block:: Python import numpy as np import scipy as sp import matplotlib.pyplot as plt rng = np.random.default_rng(27446968) n = 10 l = 256 im = np.zeros((l, l)) points = l * rng.random((2, n**2)) im[(points[0]).astype(int), (points[1]).astype(int)] = 1 im = sp.ndimage.gaussian_filter(im, sigma=l / (4.0 * n)) mask = (im > im.mean()).astype(float) img = mask + 0.3 * rng.normal(size=mask.shape) binary_img = img > 0.5 # Remove small white regions open_img = sp.ndimage.binary_opening(binary_img) # Remove small black hole close_img = sp.ndimage.binary_closing(open_img) plt.figure(figsize=(12, 3)) l = 128 plt.subplot(141) plt.imshow(binary_img[:l, :l], cmap="gray") plt.axis("off") plt.subplot(142) plt.imshow(open_img[:l, :l], cmap="gray") plt.axis("off") plt.subplot(143) plt.imshow(close_img[:l, :l], cmap="gray") plt.axis("off") plt.subplot(144) plt.imshow(mask[:l, :l], cmap="gray") plt.contour(close_img[:l, :l], [0.5], linewidths=2, colors="r") plt.axis("off") plt.subplots_adjust(wspace=0.02, hspace=0.3, top=1, bottom=0.1, left=0, right=1) plt.show() .. rst-class:: sphx-glr-timing **Total running time of the script:** (0 minutes 0.075 seconds) .. _sphx_glr_download_advanced_image_processing_auto_examples_plot_clean_morpho.py: .. only:: html .. container:: sphx-glr-footer sphx-glr-footer-example .. container:: sphx-glr-download sphx-glr-download-jupyter :download:`Download Jupyter notebook: plot_clean_morpho.ipynb <plot_clean_morpho.ipynb>` .. container:: sphx-glr-download sphx-glr-download-python :download:`Download Python source code: plot_clean_morpho.py <plot_clean_morpho.py>` .. container:: sphx-glr-download sphx-glr-download-zip :download:`Download zipped: plot_clean_morpho.zip <plot_clean_morpho.zip>` .. only:: html .. rst-class:: sphx-glr-signature `Gallery generated by Sphinx-Gallery <https://sphinx-gallery.github.io>`_