What is the Morphological gradient of an image in OpenCV

This recipe explains what is the Morphological gradient of an image in OpenCV

Recipe Objective: What is the Morphological gradient of an image in OpenCV?

In this recipe, let us understand what the Morphological gradient of an image is.

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.

The morphological gradient is one of the Morphological transformation techniques derived from the two fundamental Morphological operators, Erosion and Dilation. 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,mask = 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: Extracting Morphological gradient of an image

Before we understand what morphological gradient is, let us first understand what is Dilation and Erosion. Dilation is a morphological transformation operator used to increase the size or thickness of the foreground object in an image. In contrast, Erosion is an operation where the boundaries of the foreground object are eroded to the desired extent.

A morphological gradient is nothing but the difference between Erosion and Dilation of an image. This gives the outline of the foreground object.

To extract the morphological gradient of an image, we define a kernel matrix made of ones using the np.ones() function of the Numpy package.  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

kernel = np.ones((7,7),np.uint8)

The cv2.morphologyEx() function can extract the foreground object's morphological gradient, which takes the following inputs.

  • src: The input image
  • op: The type of morphological transformation operation
  • kernel: The kernel matrix

The morphological transformation operator to be passed in place of the op parameter is cv2.MORPH_GRADIENT

gradient = cv2.morphologyEx(mask, cv2.MORPH_GRADIENT, kernel)

Step 4: Displaying the output

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

titles = ['Original Image',"Binary Image",'Morphological gradient']
images = [image,masked_image,gradient]
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:

Morphological Gradient

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

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

Time Series Classification Project for Elevator Failure Prediction
In this Time Series Project, you will predict the failure of elevators using IoT sensor data as a time series classification machine learning problem.

OpenCV Project for Beginners to Learn Computer Vision Basics
In this OpenCV project, you will learn computer vision basics and the fundamentals of OpenCV library using Python.

Build Real Estate Price Prediction Model with NLP and FastAPI
In this Real Estate Price Prediction Project, you will learn to build a real estate price prediction machine learning model and deploy it on Heroku using FastAPI Framework.

Demand prediction of driver availability using multistep time series analysis
In this supervised learning machine learning project, you will predict the availability of a driver in a specific area by using multi step time series analysis.

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

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.

Azure Text Analytics for Medical Search Engine Deployment
Microsoft Azure Project - Use Azure text analytics cognitive service to deploy a machine learning model into Azure Databricks

Mastering A/B Testing: A Practical Guide for Production
In this A/B Testing for Machine Learning Project, you will gain hands-on experience in conducting A/B tests, analyzing statistical significance, and understanding the challenges of building a solution for A/B testing in a production environment.

Hands-On Approach to Regression Discontinuity Design Python
In this machine learning project, you will learn to implement Regression Discontinuity Design Example in Python to determine the effect of age on Mortality Rate in Python.