Explain Dilation of an image How to dilate an image in OpenCV

This recipe explains what is the Dilation of an image and how to dilate an image with OpenCV. This method takes two inputs in which one is our input image and the second is called the structuring element

Recipe Objective: What is the Dilation of an image? How to dilate an image using OpenCV?

In this recipe, let us understand the Dilation of an image and how to dilate an image using OpenCV.

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.

Dilation is one of the two fundamental Morphological transformation techniques. 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: Dilation of an image

Dilation is a morphological transformation operator used to increase the size or thickness of the foreground object in an image. In most cases, Dilation is used to connect two broken objects of an image. To dilate an image, we define a kernel matrix which is made of ones and slide the kernel through the image. 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. Each pixel element is assigned a one if any of the pixels under the kernel neighborhood is 1. This increases the size of the white region in the image, which in turn increases the size of the foreground object in an image. Dilation is usually performed after the image is eroded using another morphological transformation operator called Erosion. This process helps in removing the white noise from the image.

We can dilate an image in OpenCV using the cv2.dilate() function, which takes the following inputs.

  • src: The image which is to be dilated
  • 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

Before we dilate the image using the cv2.dilate() function, let us first create a kernel matrix using the np.ones() function of the NumPy package.

kernel = np.ones((7,7),np.uint8)
dilated_image = cv2.dilate(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",'Dilated Image']
images = [image,masked_image, dilated_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:

Dilated Image

We can see the thickness of A being increased in the dilated 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

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.

Loan Eligibility Prediction using Gradient Boosting Classifier
This data science in python project predicts if a loan should be given to an applicant or not. We predict if the customer is eligible for loan based on several factors like credit score and past history.

Tensorflow Transfer Learning Model for Image Classification
Image Classification Project - Build an Image Classification Model on a Dataset of T-Shirt Images for Binary Classification

BigMart Sales Prediction ML Project in Python
The goal of the BigMart Sales Prediction ML project is to build and evaluate different predictive models and determine the sales of each product at a store.

Learn How to Build a Logistic Regression Model in PyTorch
In this Machine Learning Project, you will learn how to build a simple logistic regression model in PyTorch for customer churn prediction.

ML Model Deployment on AWS for Customer Churn Prediction
MLOps Project-Deploy Machine Learning Model to Production Python on AWS for Customer Churn Prediction

PyCaret Project to Build and Deploy an ML App using Streamlit
In this PyCaret Project, you will build a customer segmentation model with PyCaret and deploy the machine learning application using Streamlit.

Recommender System Machine Learning Project for Beginners-2
Recommender System Machine Learning Project for Beginners Part 2- Learn how to build a recommender system for market basket analysis using association rule mining.

Classification Projects on Machine Learning for Beginners - 1
Classification ML Project for Beginners - A Hands-On Approach to Implementing Different Types of Classification Algorithms in Machine Learning for Predictive Modelling

Build an Image Classifier for Plant Species Identification
In this machine learning project, we will use binary leaf images and extracted features, including shape, margin, and texture to accurately identify plant species using different benchmark classification techniques.