OpenCV: Morphological Operations

OpenCV Morphological Operations

Morphological Magic with OpenCV

Step into the captivating realm of morphological operations in OpenCV! In this guide, we unravel the art of transforming images through dilation, erosion, opening, and closing. These operations, inspired by mathematical morphology, are fundamental tools for enhancing or diminishing structures within images. Whether you’re refining object boundaries, eliminating noise, or accentuating features, understanding morphological operations is key to mastering the nuances of image processing. Join us on this Python journey as we delve into the magic of shape-shifting images with OpenCV.

What’s Covered:

  • What are Morphological Operations?
  • Basic Python Example of Morphological Operations.

What are Morphological Operations?

In OpenCV, morphological operations are a set of image processing techniques that focus on the shape and structure of objects in an image. These operations are typically performed on binary or grayscale images and are based on the concepts of dilation, erosion, opening, and closing.

Here are the basic morphological operations in OpenCV:


Dilation is a morphological operation that expands the boundaries of foreground objects in an image. It works by convolving a kernel or structuring element with the input image and replacing each pixel with the maximum value within the neighborhood defined by the kernel. Dilation helps in filling gaps, joining broken parts, and thickening the contours of objects.


Erosion is the opposite of dilation. It erodes away the boundaries of foreground objects, making them smaller. Erosion is achieved by convolving a kernel or structuring element with the input image and replacing each pixel with the minimum value within the neighborhood defined by the kernel. Erosion is useful for removing noise, detaching connected objects, and thinning the contours.


Opening is a morphological operation that combines erosion followed by dilation. It helps in removing noise, fine details, and small objects while preserving the overall shape of larger objects. Opening is performed by applying erosion first and then dilation on the resulting image.


Closing is the reverse of opening and combines dilation followed by erosion. It is useful for closing small holes, connecting broken parts, and smoothing the object contours. Closing is performed by applying dilation first and then erosion on the input image.

In OpenCV, these morphological operations can be performed using functions like cv2.dilate(), cv2.erode(), cv2.morphologyEx(), and so on. These functions allow you to specify the kernel or structuring element, control the size and shape of the neighborhood, and adjust the iterations to achieve the desired effect.

Note that morphological operations are typically applied to binary or grayscale images where the objects of interest are represented by different intensity values or color regions.

Basic Python Example of Morphological Operations

Let’s go through a basic Python example using erosion and dilation, two fundamental morphological operations. In this example, we’ll use a simple binary image with white objects on a black background.

import cv2
import numpy as np
from matplotlib import pyplot as plt

# Create a binary image with a white square in the center
image = np.zeros((300, 300), dtype=np.uint8)
cv2.rectangle(image, (50, 50), (250, 250), 255, -1)

# Define a kernel for morphological operations
kernel = np.ones((5, 5), np.uint8)

# Erosion: It erodes away the boundaries of the foreground object.
erosion = cv2.erode(image, kernel, iterations=1)

# Dilation: It increases the object area and is useful in closing small holes.
dilation = cv2.dilate(image, kernel, iterations=1)

# Plot the original, eroded, and dilated images
plt.subplot(131), plt.imshow(image, cmap='gray'), plt.title('Original')
plt.subplot(132), plt.imshow(erosion, cmap='gray'), plt.title('Erosion')
plt.subplot(133), plt.imshow(dilation, cmap='gray'), plt.title('Dilation')
In this example:
  • We create a binary image with a white square in the center using NumPy and OpenCV.
  • Then we define a 5×5 kernel using np.ones for the morphological operations.
  • We perform erosion on the original image using cv2.erode.
  • Then we perform dilation on the original image using cv2.dilate.
  • We use Matplotlib to display the original, eroded, and dilated images side by side.

You can run this code in Visual Studio, you will however need Matplotlib installed to observe the effects of erosion and dilation on the binary image. Adjust the size of the kernel and the number of iterations to observe different effects on the image.

If you have not used Matplotlib before, you can read our matplotlib basics guide here: Matplotlib Basics


Congratulations on mastering the morphological dance of pixels in OpenCV! You’ve now harnessed the power to sculpt and refine images, emphasizing details and smoothing imperfections. Morphological operations, with their ability to enhance or suppress features, are invaluable in the world of computer vision. As you integrate these techniques into your projects, remember that each dilation and erosion is a brushstroke, shaping your images with precision. Continue to experiment, innovate, and let the magic of morphological operations unfold in your visual creations.

In the next installment of this OpenCV for Beginners guide we will be learning Face Detection

That’s All Folks!

You can find all of our OpenCV guides here: OpenCV for Beginners

Luke Barber

Hello, fellow tech enthusiasts! I'm Luke, a passionate learner and explorer in the vast realms of technology. Welcome to my digital space where I share the insights and adventures gained from my journey into the fascinating worlds of Arduino, Python, Linux, Ethical Hacking, and beyond. Armed with qualifications including CompTIA A+, Sec+, Cisco CCNA, Unix/Linux and Bash Shell Scripting, JavaScript Application Programming, Python Programming and Ethical Hacking, I thrive in the ever-evolving landscape of coding, computers, and networks. As a tech enthusiast, I'm on a mission to simplify the complexities of technology through my blogs, offering a glimpse into the marvels of Arduino, Python, Linux, and Ethical Hacking techniques. Whether you're a fellow coder or a curious mind, I invite you to join me on this journey of continuous learning and discovery.

Leave a Reply

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

Verified by MonsterInsights