How to Apply Erosion to Images with OpenCV

Related Articles

Last updated: April 4, 2023

Live now! All hands on tech!

Welcome Computer Vision Geeks! This tutorial will dive deep into attrition and how it works. Let’s start with OpenCV.

I aim to make this guide fun and easy to understand for beginners. so lets start!

Note: Here is a link to Full source code.

Looking for Extension in OpenCV?

Attrition: The Basics

Grinding is a fundamental operation in computer vision and image processing. This is a technique used to reduce unwanted noise and detail from images.

I talked about it at my place Computer Vision Power Hour Live Broadcast. Image preprocessing is essential for computer vision. Preparing your images can be as important or even more important than the model you use to analyze them.

Blurring involves shrinking or eroding the boundaries of foreground objects in the image. It helps in eliminating small white spots and connecting disjointed or broken parts of objects.

Grinding works with patterns called structural elements, which can be squares or circles. These patterns slide over the original image. When creating the new image, a pixel is set to black (0) if even one pixel in the pattern does not match the original image. However, if all the pixels in the pattern are white, the pixel of the new image will also be white.

Why use attrition?

You may be wondering, “Why should I learn about attrition?” Here’s why.

Grinding helps in:

Noise reduction: Removes light white noise from images, making them brighter and easier to analyze.

border rescue: By applying erosion followed by a subtraction operation, the boundaries of objects in an image can be extracted.

Detach objects: Erosion can disconnect objects connected by thin bridges, making them easier to separate and analyze.

Now that we’ve covered the basics, let’s dive into the code.

Getting started with OpenCV

To get started, you’ll need to install OpenCV on your computer. If you don’t have it yet, here are some great instructions for Install OpenCV.

Once you have OpenCV installed, we can begin our erosion study. Let’s start by importing the required libraries:

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

Next, let’s load an image and convert it to grayscale:

image_path = 'images/mustang.png'
image = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE)

Applying Erosion with OpenCV

Applying erosion in OpenCV is a breeze! Here’s how you can do it.

Let’s start with this picture:

How to apply erosion with OpenCV

You can Download it here

It’s a bit noisy, and we can use sanding to clean it up for computer vision stuff.

  1. Create a structure element using cv2.getStructuringElement(). You can choose from different shapes like cv2.MORPH_RECT, cv2.MORPH_ELLIPSEor cv2.MORPH_CROSS.

For this example, we will use a 3×3 rectangle.

structuring_element = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3))
  1. Start the grinding operation using cv2.erode().
eroded_image = cv2.erode(image, structuring_element, iterations=1)

God iterations parameter b incv2.erode() Specifies the number of times the burn operation should be applied. A higher number of iterations will result in a more eroded image.

  1. Now that we have our blurred image, let’s show the original and blurred images side by side for comparison:
import matplotlib.pyplot as plt

plt.figure(figsize=(12, 6))
plt.subplot(121), plt.imshow(image, cmap='gray'), plt.title('Original Image')
plt.subplot(122), plt.imshow(eroded_image, cmap='gray'), plt.title('Eroded Image')

The end result looks like this:

How to apply erosion with OpenCV

And that’s all there is to it. You have successfully applied erosion to an image using OpenCV.

Experiment with different structural elements

Different building blocks can produce different results, so it’s worth experimenting to find the best one for your specific use case. Let’s try to implement grinding using an elliptical structure element:

structuring_element_ellipse = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3))
eroded_image_ellipse = cv2.erode(image, structuring_element_ellipse, iterations=1)

plt.figure(figsize=(12, 6))
plt.subplot(121), plt.imshow(image, cmap='gray'), plt.title('Original Image')
plt.subplot(122), plt.imshow(eroded_image_ellipse, cmap='gray'), plt.title('Eroded Image with Ellipse')

This is what the result looks like:

How to apply erosion with OpenCV

Although these will not look different to the naked eye, they will be interpreted differently when passed to classifiers.

Feel free to experiment with different shapes and sizes of structural elements to see how they affect wear.


Mazel Tov! You have just learned how grinding works and how to implement it using OpenCV. Now you can confidently use this technique to preprocess images, reduce noise, and extract object boundaries in your computer vision projects. Preprocessing is everything.

Continue exploring the fascinating world of computer vision. This stuff is so much fun.

Happy coding, and see you in the next tutorial.

– Jeremy

I have a lot OpenCV demos On GitHub you can download and run. I build them on mine Computer Vision live broadcast

Questions, comments? Yell at me!


Popular Articles