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

Anand Kumpatla

Sr Data Scientist @ Doubleslash Software Solutions Pvt Ltd
linkedin profile url

ProjectPro is a unique platform and helps many people in the industry to solve real-life problems with a step-by-step walkthrough of projects. A platform with some fantastic resources to gain... Read More

Relevant Projects

End-to-End Snowflake Healthcare Analytics Project on AWS-2
In this AWS Snowflake project, you will build an end to end retraining pipeline by checking Data and Model Drift and learn how to redeploy the model if needed

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

A/B Testing Approach for Comparing Performance of ML Models
The objective of this project is to compare the performance of BERT and DistilBERT models for building an efficient Question and Answering system. Using A/B testing approach, we explore the effectiveness and efficiency of both models and determine which one is better suited for Q&A tasks.

Stock Price Prediction Project using LSTM and RNN
Learn how to predict stock prices using RNN and LSTM models. Understand deep learning concepts and apply them to real-world financial data for accurate forecasting.

Deploy Transformer BART Model for Text summarization on GCP
Learn to Deploy a Machine Learning Model for the Abstractive Text Summarization on Google Cloud Platform (GCP)

Census Income Data Set Project-Predict Adult Census Income
Use the Adult Income dataset to predict whether income exceeds 50K yr based oncensus data.

Build a Hybrid Recommender System in Python using LightFM
In this Recommender System project, you will build a hybrid recommender system in Python using LightFM .

Multi-Class Text Classification with Deep Learning using BERT
In this deep learning project, you will implement one of the most popular state of the art Transformer models, BERT for Multi-Class Text Classification

Build CNN Image Classification Models for Real Time Prediction
Image Classification Project to build a CNN model in Python that can classify images into social security cards, driving licenses, and other key identity information.

Loan Eligibility Prediction Project using Machine learning on GCP
Loan Eligibility Prediction Project - Use SQL and Python to build a predictive model on GCP to determine whether an application requesting loan is eligible or not.