Applying Morphological Transformations in OpenCV

In this tutorial, we are going to learn and understand: Applying Morphological Transformations in OpenCV.

Introduction

Morphological transformations are image processing techniques used to enhance or clean up images. In this tutorial, we’ll learn how to apply erosion, dilation, opening, and closing using OpenCV in Python.

Why Use Morphological Transformations?

They are commonly used in:

  • Noise removal
  • Object detection and segmentation
  • Edge and contour enhancement
  • Bridging gaps in object boundaries

Step 1: Importing Required Libraries

We first need to import OpenCV and NumPy.

import cv2
import numpy as np

Step 2: Loading the Image

We will read a grayscale image using OpenCV:

image = cv2.imread('image.jpeg', 0) # Load image in grayscale mode

Step 3: Defining the Kernel

A kernel is a small matrix used to apply transformations:

kernel = np.ones((5,5), np.uint8)

Step 4: Applying Morphological Transformations

1. Erosion

Erosion removes pixels on object boundaries, making objects smaller. This is useful for removing small noise.

erosion = cv2.erode(image, kernel, iterations=1)

2. Dilation

Dilation adds pixels to object boundaries, making objects larger. This helps in bridging small gaps.

dilation = cv2.dilate(image, kernel, iterations=1)

3. Opening (Erosion to Dilation)

Opening helps remove noise by first eroding and then dilating the image.

opening = cv2.morphologyEx(image, cv2.MORPH_OPEN, kernel)

4. Closing (Dilation to Erosion)

Closing is the opposite of opening; it helps close small holes in objects.

closing = cv2.morphologyEx(image, cv2.MORPH_CLOSE, kernel)

Step 5: Displaying the Results

To visualize the transformations, we use OpenCV’s imshow() function:

cv2.imshow('Erosion', erosion)
cv2.imshow('Dilation', dilation)
cv2.imshow('Opening', opening)
cv2.imshow('Closing', closing)
cv2.waitKey(0)
cv2.destroyAllWindows()

Output

Source:

Erosion:

Dilation:

Opening:

Closing:

Conclusion

In this tutorial, we learned Applying Morphological Transformations in OpenCV.

  • Erosion: Shrinks objects, removes noise
  • Dilation: Expands objects, fills gaps
  • Opening: Removes small noise
  • Closing: Fills small holes in objects

Leave a Comment

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

Scroll to Top