Erode – Dilate

Written by

in

Erosion and dilation are foundational morphological image processing operations used to alter the shapes and boundaries of features within binary or grayscale images. Erosion shrinks foreground (white) objects by stripping away pixels along their boundaries, which helps eliminate isolated white noise. Conversely, dilation expands foreground objects by adding pixels around their borders, making features thicker and filling in small holes or gaps. How the Filters Work Underlyingly

Both operations require a structuring element (kernel)—a small matrix (like a 3×3 or 5×5 grid) that slides across the image like a window.

Erosion (cv2.erode): As the kernel passes over a pixel, the center pixel retains a value of 1 (or white) only if all pixels covered by the kernel are 1. If even a single overlapping pixel is 0 (black), the target pixel turns to 0. This effectively erases thin lines, tears down object boundaries, and removes small background specks.

Dilation (cv2.dilate): As the kernel slides, the center pixel becomes 1 if at least one pixel under the kernel is 1. This effectively grows the object boundaries, fuses broken line segments together, and collapses small interior voids. Essential Code Syntax in Python

You must first initialize a structuring element using NumPy or built-in OpenCV tools, then apply the specific transformation function.

import cv2 import numpy as np # Load a grayscale image and binarize it (Foreground should be white, background black) img = cv2.imread(‘binary_image.png’, cv2.IMREAD_GRAYSCALE) # 1. Define the Kernel (Structuring Element) # A simple 5x5 square matrix filled with ones kernel = np.ones((5, 5), np.uint8) # 2. Apply Erosion # ‘iterations’ dictates how many consecutive times the filter runs eroded_img = cv2.erode(img, kernel, iterations=1) # 3. Apply Dilation dilated_img = cv2.dilate(img, kernel, iterations=1) # Display the results cv2.imshow(‘Eroded’, eroded_img) cv2.imshow(‘Dilated’, dilated_img) cv2.waitKey(0) cv2.destroyAllWindows() Use code with caution. Advanced Structuring Elements

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *