Morphological Operations in SciPy (original) (raw)

Last Updated : 23 Jul, 2025

Morphological operations are a set of image processing techniques used to process geometrical structures in binary or grayscale images. They are primarily used for tasks such as noise removal, image enhancement, object segmentation and shape analysis. SciPy is a Python library used for scientific and technical computing includes a submodule called scipy.ndimage that provides a suite of tools for performing morphological operations.

Morphological operations

Morphological operations apply a structuring element to an input image and produce an output image of the same size. The basic idea is to probe the image with a small shape or template the structuring element and transform the image based on how the shape fits or misses the features in the input.

morphological-copy

Common Morphological Operations

SciPy for Morphological Functions

1. Erosion

from scipy import ndimage import numpy as np

eroded = ndimage.binary_erosion(input_image, structure=struct_element)

`

2. Dilation

from scipy import ndimage import numpy as np dilated = ndimage.binary_dilation(input_image, structure=struct_element)

`

3. Opening

from scipy import ndimage import numpy as np opened = ndimage.binary_opening(input_image, structure=struct_element)

`

4. Closing

from scipy import ndimage import numpy as np closed = ndimage.binary_closing(input_image, structure=struct_element)

`

5. Morphological Gradient

from scipy import ndimage import numpy as np gradient = ndimage.morphological_gradient(input_image, size=3)

`

6. Top Hat Transform

**1. White Top Hat: Difference between the input image and its opening.

Python `

from scipy import ndimage import numpy as np white_tophat = input_image - ndimage.grey_opening(input_image, structure=struct)

`

**2. Black Top Hat: Difference between the closing of the input image and the image itself.

Python `

from scipy import ndimage import numpy as np black_tophat = ndimage.grey_closing(input_image, structure=struct) - input_image

`