Site icon Machine Learning Projects

How to perform Morphological Operations like Erosion, Dilation, and Gradient in Python using OpenCV – easiest explanation –2023

Machine Learning Projects

So, in today’s blog, we will see that how we can perform morphological operations like erosion, dilation, and gradient upon an image to enhance it.

Morphological transformations are some simple operations based on the image shape. It is normally performed on binary images. It needs two inputs, one is our original image, and the second one is called structuring element or kernel which decides the nature of the operation. Two basic morphological operators are Erosion and Dilation. Then its variant forms like Opening, Closing, Gradient, etc also come into play.

This is going to be a very interesting and informative blog, so without any further due, Let’s do it…

Step 1 – Importing required libraries.

import cv2
import numpy as np
import matplotlib.pyplot as plt

Step 2 – Load the image.

imgpath = "cameraman.tif"
img = cv2.imread(imgpath, 0)
Image on which we will perform morphological operations…

Step 3 – Let’s make a kernel.

k = np.ones((5, 5), np.uint8)

Step 4 – Perform the first morphological operation – Erosion.

Syntax: cv2.erode(src, kernel[, dst[, anchor[, iterations[, borderType[, borderValue]]]]])

Parameters:

srcIt is the image that is to be eroded.
kernelA structuring element used for erosion. If element = Mat(), a 3 x 3 rectangular structuring element is used. The kernel can be created using getStructuringElement.
dstIt is the output image of the same size and type as src.
anchorIt is a variable of type integer representing anchor point and its default value Point is (-1, -1) which means that the anchor is at the kernel center.
borderTypeIt depicts what kind of border to be added. It is defined by flags like cv2.BORDER_CONSTANTcv2.BORDER_REFLECT, etc.
iterationsIt is the number of times erosion is applied.
borderValueIt is border value in case of a constant border.
erosion = cv2.erode(img, k, iterations=2)

Step 5 – Perform the second morphological operation – Dilation.

Syntax: cv2.dilate(src, kernel[, anchor[, iterations[, borderType[, borderValue]]]])

Parameters:

srcIt is a required parameter and an original image on which we need to perform dilation.
kernelIt is the required parameter is the matrix with which the image is convolved.
dstIt is the output image of the same size and type as image src.
anchorIt is a variable of type integer representing the anchor point and its default value Point is (-1, -1) which means that the anchor is at the kernel center.
borderTypeIt depicts what kind of border to be added. It is defined by flags like cv2.BORDER_CONSTANTcv2.BORDER_REFLECT, etc.
iterationsIt is an optional parameter that takes several iterations.
borderValueIt is border value in case of a constant border.
dilation = cv2.dilate(img, k, iterations=2)

Step 6 – Perform the third morphological operation – Gradient.

gradient = cv2.morphologyEx(img, cv2.MORPH_GRADIENT, k)

Step 7- Finally let’s plot the results of morphological operations.

titles = ['original', 'erosion', 'dilate', 'gradient']
img = [img, erosion, dilation, gradient]

for i in range(4):
    plt.subplot(2, 2, i+1)
    plt.xticks([])
    plt.yticks([])
    plt.title(titles[i])
    plt.imshow(img[i], cmap='gray')
plt.show()
Final results…

Let’s see the whole code of morphological operations…

# morphological operations
import cv2
import numpy as np
import matplotlib.pyplot as plt

imgpath = "cameraman.tif"
img = cv2.imread(imgpath, 0)

k = np.ones((5, 5), np.uint8)

erosion = cv2.erode(img, k, iterations=2)
dilation = cv2.dilate(img, k, iterations=2)
gradient = cv2.morphologyEx(img, cv2.MORPH_GRADIENT, k)

titles = ['original', 'erosion', 'dilate', 'gradient']
img = [img, erosion, dilation, gradient]

for i in range(4):
    plt.subplot(2, 2, i+1)
    plt.xticks([])
    plt.yticks([])
    plt.title(titles[i])
    plt.imshow(img[i], cmap='gray')

plt.show()

NOTE – You can read more about the morphological operations at the official OpenCV documentation.

Do let me know if there’s any query regarding morphological operations by contacting me by email or LinkedIn.

So this is all for this blog folks, thanks for reading it and I hope you are taking something with you after reading this and till the next time ?…

Read my previous post: HOW TO USE MOUSE CLICKS TO DRAW CIRCLES IN PYTHON USING OPENCV

Check out my other machine learning projectsdeep learning projectscomputer vision projectsNLP projectsFlask projects at machinelearningprojects.net.

Exit mobile version