Erosion of an Image Using OpenCV-Python

Hi there, today we will be talking about something interesting as well as simple : Erosion of an Image Using OpenCV module in Python. An image has many features (for example:- edge, contrast etc.). Erosion is one of the fundamental operations in morphological image processing. This operation basically erodes away the boundaries of foreground object. Erosion of an image has many benefits (for example: it can remove small bright spots of an image, it can be used for edge detection etc.). We can erode any image using a few lines of codes.

Let’s get started. 

Erosion of an Image Project

Requirements:  

Basic knowledge of python(go through Learn Python Tutorial) . We can use any ide ( for example:  https://code.visualstudio.com/download , https://jupyter.org/).

You can also go through https://studygyaan.com/python/blurring-an-image-using-opencv-python

Modules:

OpenCV : It is a python open-source library, we use it for all sorts of image and video analysis, for instance, facial recognition and detection, photo editing etc.

NumPy : NumPy (an acronym for “Numeric Python” or “Numerical Python”) is a library for the Python programming language. It is used for working with large ,multi-dimensional arrays and matrices.

Installation:

Firstly, we have to open command prompt in administrator mode.

OpenCV: To install OpenCV we have to type the below command in the terminal.

pip install opencv-python

NumPy :Similarly, to install Numpy we will type the below command in the terminal.

pip install numpy

Approach:

1. Firstly, we have to import the modules one by one.

 import cv2
 import numpy as np 

2. Secondly, we will read the image.

MyImage = cv2.imread(path)

3. Thirdly, we have to give a name of the window in which image will be displayed.

window_name = 'MyWindow'

4. Fourthly, we have to create a kernel (a matrix of odd size(3,5,7)).

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

5. Now, we will use cv2.erode( ) method for eroding the boundaries away. The basic syntax of this method is cv2.erode(src, kernel[, dst[, anchor[, iterations[, borderType[, borderValue]]]]]). The parameters are src( the image), kernel (an element used for image processing), dst (output image), anchor (integer variable to represent the anchor point at the kernel), iterations (it tells us how many times erosion is applied) etc.

Finally, we can display the image.

 image = cv2.erode(MyImage, kernel)  
 cv2.imshow(window_name, image) 

Source Code:

 import cv2
 import numpy as np
 MyImage = cv2.imread(path)  
 window_name = 'MyWindow'
 kernel = np.ones((5, 5), np.uint8)
 image = cv2.erode(MyImage, kernel)  
 cv2.imshow(window_name, image)   

Original Image:

Output:

Hope, you liked this tutorial.