Morphological operations help us change shapes in images or data. They make objects smaller or bigger to find patterns or clean noise.
0
0
Morphological operations (erosion, dilation) in SciPy
Introduction
To remove small dots or noise from a black and white image.
To fill small holes inside objects in an image.
To separate objects that are close together in a photo.
To highlight or grow certain features in a shape or image.
Syntax
SciPy
from scipy.ndimage import binary_erosion, binary_dilation # Erosion result = binary_erosion(input_array, structure=structuring_element) # Dilation result = binary_dilation(input_array, structure=structuring_element)
input_array is the image or data as a 2D array of True/False or 1/0.
structuring_element defines the shape used to erode or dilate, like a small square or circle.
Examples
This erodes a 3x3 block of True values, shrinking the shape by removing edge pixels.
SciPy
from scipy.ndimage import binary_erosion import numpy as np image = np.array([[1,1,1],[1,1,1],[1,1,1]], dtype=bool) eroded = binary_erosion(image)
This dilates a single True pixel, growing it to neighbors.
SciPy
from scipy.ndimage import binary_dilation import numpy as np image = np.array([[0,0,0],[0,1,0],[0,0,0]], dtype=bool) dilated = binary_dilation(image)
Sample Program
This code shows how erosion shrinks the square by removing edge pixels, and dilation grows it by adding pixels around the edges.
SciPy
from scipy.ndimage import binary_erosion, binary_dilation import numpy as np # Create a simple 5x5 image with a square in the center image = np.array([ [0,0,0,0,0], [0,1,1,1,0], [0,1,1,1,0], [0,1,1,1,0], [0,0,0,0,0] ], dtype=bool) # Define a 3x3 square structuring element structure = np.ones((3,3), dtype=bool) # Apply erosion eroded_image = binary_erosion(image, structure=structure) # Apply dilation dilated_image = binary_dilation(image, structure=structure) print("Original image:\n", image.astype(int)) print("\nEroded image:\n", eroded_image.astype(int)) print("\nDilated image:\n", dilated_image.astype(int))
OutputSuccess
Important Notes
Erosion removes pixels on object edges, making shapes smaller.
Dilation adds pixels to object edges, making shapes bigger.
Choosing the right structuring element shape and size affects results a lot.
Summary
Morphological operations change shapes in images by shrinking or growing them.
Erosion removes edge pixels; dilation adds edge pixels.
These operations help clean images and find patterns.