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

NLP Project for Multi Class Text Classification using BERT Model
In this NLP Project, you will learn how to build a multi-class text classification model using using the pre-trained BERT model.

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

Personalized Medicine: Redefining Cancer Treatment
In this Personalized Medicine Machine Learning Project you will learn to classify genetic mutations on the basis of medical literature into 9 classes.

Deep Learning Project for Beginners with Source Code Part 1
Learn to implement deep neural networks in Python .

Build Customer Propensity to Purchase Model in Python
In this machine learning project, you will learn to build a machine learning model to estimate customer propensity to purchase.

Build an AI Chatbot from Scratch using Keras Sequential Model
In this NLP Project, you will learn how to build an AI Chatbot from Scratch using Keras Sequential Model.

Build a Music Recommendation Algorithm using KKBox's Dataset
Music Recommendation Project using Machine Learning - Use the KKBox dataset to predict the chances of a user listening to a song again after their very first noticeable listening event.

Digit Recognition using CNN for MNIST Dataset in Python
In this deep learning project, you will build a convolutional neural network using MNIST dataset for handwritten digit recognition.

Locality Sensitive Hashing Python Code for Look-Alike Modelling
In this deep learning project, you will find similar images (lookalikes) using deep learning and locality sensitive hashing to find customers who are most likely to click on an ad.

Forecasting Business KPI's with Tensorflow and Python
In this machine learning project, you will use the video clip of an IPL match played between CSK and RCB to forecast key performance indicators like the number of appearances of a brand logo, the frames, and the shortest and longest area percentage in the video.