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

Gautam Vermani

Data Consultant at Confidential
linkedin profile url

Having worked in the field of Data Science, I wanted to explore how I can implement projects in other domains, So I thought of connecting with ProjectPro. A project that helped me absorb this topic... Read More

Relevant Projects

NLP Project to Build a Resume Parser in Python using Spacy
Use the popular Spacy NLP python library for OCR and text classification to build a Resume Parser in Python.

Linear Regression Model Project in Python for Beginners Part 1
Machine Learning Linear Regression Project in Python to build a simple linear regression model and master the fundamentals of regression for beginners.

Deploy Transformer-BART Model on Paperspace Cloud
In this MLOps Project you will learn how to deploy a Tranaformer BART Model for Abstractive Text Summarization on Paperspace Private Cloud

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 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.

Model Deployment on GCP using Streamlit for Resume Parsing
Perform model deployment on GCP for resume parsing model using Streamlit App.

Detectron2 Object Detection and Segmentation Example Python
Object Detection using Detectron2 - Build a Dectectron2 model to detect the zones and inhibitions in antibiogram images.

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 Text Classification Model with Attention Mechanism NLP
In this NLP Project, you will learn to build a multi class text classification model with attention mechanism.

Time Series Analysis with Facebook Prophet Python and Cesium
Time Series Analysis Project - Use the Facebook Prophet and Cesium Open Source Library for Time Series Forecasting in Python