cv2.erode() function in OpenCV – Python

In this tutorial, we are going to learn cv2.erode() function.This is basically an operation in Morphological Transformation. The function is actually packed in the OpenCV package in Python. So let’s learn how we can imply it in Python and see its Output.

We are going to do this using OpenCV and NumPy packages if you have already installed open CV and NumPy then you can ignore otherwise you have to install open CV and NumPy.

How to install OpenCV and NumPy?

To install OpenCV You have to download the OpenCV program and run it on your computer and install it as a normal installation.

To install NumPy you have to run the following comment in your command prompt or terminal (for Linux or Mac users) then it will be installed.

pip install numpy

cv2.erode() function in Python – OpenCV

Erosion is one of the most important operations in Morphological Transformation. Erosion is basically omitting or thining the boundaries of the bright area of the image. We apply Erosion only to the binary image(The image which consists only two colors black and white. The colors of Binary image is represented by 0 and 1 But sometimes it is also represented as 0 and 255). To make Erosion happen we use cv2.erode() function.

Code for Erosion in Python:

So, At first, we are importing cv2 and numpy in Python (Make sure, You’ve installed the OpenCV before writing the code).

import cv2
import numpy as np

Then using the NumPy module we are reading the image using imread() function. In the arguments of the function, we are giving the location of the Binary image, if the image is in the same folder then we only give the name of the image as the argument of the imread() function.

Then we take the kernel matrix size (6,6). A kernel(a matrix of odd size(3,5,7) is convolved with the image.

morph_img = cv2.imread('image.png',0)
morph_kernel = np.ones((6,6),np.uint8)

Now we are performing Erosion. So we take a variable and use cv2.erode() function on this variable.

erosion = cv2.erode(morph_img,kernel,iterations = 1)
cv2.imshow('EROSION', erosion)

And finally to show the Output of our program we use np.imshow() function.

The output of Erosion:

cv2.erode() function in OpenCV - Python

Uses of Erosion:

  • It helps to remove small bright holes in the Binary image.
  • It is used to disconnect two slightly connected images.

Leave a Reply