Morphological transformations on images and working of erosion

This recipe explains what are morphological transformations on images and the working of erosion. Morphological transformations are operations that are performed based on the shape of the image.

Recipe Objective: What are morphological transformations on images? Explain how erosion works.

In this recipe, let us understand Morphological transformations on images and how erosion works in detail.

Explore Fascinating Image Processing Project Ideas With Source Code

Step 1: Import the libraries and read the image.

Let us first import the necessary libraries and read the image. The image that we are using here is the one shown below.

Input Image

import numpy as np
import cv2
from matplotlib import pyplot as plt
image = cv2.imread('letter_A.jpg',0)

Step 2: Converting Grayscale image to binary image.

Morphological transformations generally work only on binary images. Hence, let us convert our input image into a binary image. It is also recommended to keep the foreground in white, and the background is black. This can be achieved by using the cv2.threshold() function.

retVal,masked_image = cv2.threshold(image,155,255,cv2.THRESH_BINARY_INV)

The cv2.THRESH_BINARY_INV performs inverse binary thresholding which maintains the foreground in white and the background in black

Step 3: Erosion of an image using Morphological transformation

In simple terms, Morphological transformations are nothing but operations that are performed based on the shape of the image. They are usually performed on binary images. These operations require two inputs. One is the binary image over which the transformations are to be performed. The other is the kernel ( A kernel is nothing but a small matrix used for sharpening, blurring, embossing, edge detection, and much more. It is also sometimes called a convolution matrix, a mask, or a filter ) which decides the type of the operation.

Erosion is one of the two fundamental morphological operators. As the name suggests, erosion is an operation where the boundaries of the foreground object are eroded to the desired extent.

But how does it erode the boundaries? As the kernel passes through the image, any given pixel in the original image would be considered one if and only if its kernel neighbors are 1. Otherwise, the pixel value is considered as 0. That is, the pixel is eroded. This is the reason for converting any given image into a binary image. This operation is extensively used in noise cancellation, detaching two connected objects, and so on.

This can be implemented in OpenCV using the cv2.erode() function, which takes the following inputs.

  • src: The image which is to be eroded
  • kernel: The kernel matrix
  • iterations : (Optional) The number of iterations that specify how many times the operation will be performed. The default value is 1

Unlike other transformation functions in OpenCV, we have to define our kernel matrix for cv2.erode(). Let us create a 5 x 5 matrix of ones that can be used as a kernel matrix using the NumPy package

kernel = np.ones((7,7),np.uint8)
eroded_image = cv2.erode(masked_image,kernel,iterations = 3)

Step 4: Displaying the output

Let us display the output using matplotlib subplots for a better comparison of results.

titles = ['Original Image',"Binary Image",'Eroded Image']
images = [image,masked_image, eroded_image]
plt.figure(figsize=(13,5))
for i in range(3):
    plt.subplot(1,3,i+1)
    plt.imshow(images[i],'gray')
    plt.title(titles[i])
    plt.xticks([])
    plt.yticks([])
plt.tight_layout()
plt.show()

Output:

Output

We can see the thickness of A being reduced in the Eroded image.


Download Materials


What Users are saying..

profile image

Abhinav Agarwal

Graduate Student at Northwestern University
linkedin profile url

I come from Northwestern University, which is ranked 9th in the US. Although the high-quality academics at school taught me all the basics I needed, obtaining practical experience was a challenge.... Read More

Relevant Projects

House Price Prediction Project using Machine Learning in Python
Use the Zillow Zestimate Dataset to build a machine learning model for house price prediction.

Build a Wealth Management Agentic AI Chatbot with MS Fabric
In this Agentic AI project , you will learn to build an intelligent financial assistant that autonomously analyzes your financial data, assesses risks, and designs personalized investment strategies, making wealth management more efficient and personalized to your needs

Build a Churn Prediction Model using Ensemble Learning
Learn how to build ensemble machine learning models like Random Forest, Adaboost, and Gradient Boosting for Customer Churn Prediction using Python

Learn to Build an End-to-End Machine Learning Pipeline - Part 3
This machine learning project integrates model monitoring, CI/CD practices and Amazon Sagemaker pipelines into the logistics-oriented machine learning pipeline to streamline workflow orchestration for scalable and reliable deployment of ML models in logistics.

End-to-End Snowflake Healthcare Analytics Project on AWS-1
In this Snowflake Healthcare Analytics Project, you will leverage Snowflake on AWS to predict patient length of stay (LOS) in hospitals. The prediction of LOS can help in efficient resource allocation, lower the risk of staff/visitor infections, and improve overall hospital functioning.

Loan Eligibility Prediction in Python using H2O.ai
In this loan prediction project you will build predictive models in Python using H2O.ai to predict if an applicant is able to repay the loan or not.

MLOps AWS Project on Topic Modeling using Gunicorn Flask
In this project we will see the end-to-end machine learning development process to design, build and manage reproducible, testable, and evolvable machine learning models by using AWS

PyTorch Project to Build a LSTM Text Classification Model
In this PyTorch Project you will learn how to build an LSTM Text Classification model for Classifying the Reviews of an App .

Loan Default Prediction Project using Explainable AI ML Models
Loan Default Prediction Project that employs sophisticated machine learning models, such as XGBoost and Random Forest and delves deep into the realm of Explainable AI, ensuring every prediction is transparent and understandable.

Build Regression (Linear,Ridge,Lasso) Models in NumPy Python
In this machine learning regression project, you will learn to build NumPy Regression Models (Linear Regression, Ridge Regression, Lasso Regression) from Scratch.

OSZAR »