Erosion and Dilation of images using OpenCV in Python (original) (raw)

Last Updated : 05 Aug, 2025

Morphological operations modify images based on the structure and arrangement of pixels. They apply kernel to an input image for changing its features depending on the arrangement of neighboring pixels. Morphological operations like erosion and dilation are techniques in image processing, especially for binary or grayscale images. They help in analyzing shapes, cleaning noise and refining object boundaries.

Erosion

Erosion in image processing is a morphological operation that shrinks and thins the boundaries of objects in an image by removing pixels on object edges, effectively making objects smaller and removing small white noise.

Purpose

How It Works

Dilation

Dilation is a morphological operation that expands the boundaries of objects in an image by adding pixels to object edges making objects appear larger and filling in small gaps or holes.

**Purpose:

**How It Works:

Implementation of Erosion and Dilation

Let's implement Erosion and Dilation with OpenCV in Python,

**Step 1: Import Libraries

We will import the necessary libraries,

**Step 2: Load Input Image and Define the Structuring Elements(Kernel)

The kernel defines the neighborhood for the operation. Common choices are rectangles or disks.

Used image can be downloaded from here.

Python `

img = cv2.imread('input.png', 0) plt.imshow(img, cmap='gray') plt.title("Original Image") plt.axis('off') plt.show() kernel = np.ones((5, 5), np.uint8)

`

**Output:

original-cat

Original

**Step 3: Apply Erosion

Erosion works by sliding the kernel across the image. A pixel remains white (255) only if all pixels under the kernel are white, otherwise, it becomes black (0). This reduces object boundaries and removes small white noise.

Python `

img_erosion = cv2.erode(img, kernel, iterations=1)

plt.imshow(img_erosion, cmap='gray') plt.title("After Erosion") plt.axis('off') plt.show()

`

**Output:

erosion

After Erosion

**Step 4: Apply Dilation

Dilation slides the kernel across the image and a pixel becomes white if at least one pixel under the kernel is white. This thickens white regions or objects and fills small holes.

Python `

img_dilation = cv2.dilate(img, kernel, iterations=1)

plt.imshow(img_dilation, cmap='gray') plt.title("After Dilation") plt.axis('off') plt.show()

`

**Output:

dilation

After Dilation

Applications

**Erosion

**Dilation

Erosion and dilation are fundamental morphological operations in image processing that allow us to refine, clean and manipulate shapes within images. By using simple structuring elements, these techniques help remove noise, separate or connect objects and enhance image features making them essential tools for effective pre-processing and analysis in computer vision tasks with OpenCV and Python.