Instagram
youtube
Facebook
Twitter

Image Erosion

OpenCV erosion is an image processing technique that is used to reduce noise and unwanted elements from an image. It works by eroding away all the pixels that are not of required by adding a matrix(kernel) over the image and replacing the pixel values within the area of the kernel with the minimum pixel value in the kernel. This process can be repeated several times to achieve the desired effect. It can be used to sharpen an image, remove noise, and extract specific features from an image.

what is cv2.erode function?

cv2.erode is a function of the OpenCV library. It is used to erode an image by applying a kernel to the image. The function erodes away the boundaries of foreground objects and leaves only the background. It is useful for removing small noises, detaching two connected objects etc. In this tutorial, we’ll learn about OpenCV erosion with some practical work.

Let's understand the concept with some practical work.

Example:

Input

Code:

import cv2
import numpy as np
img = cv2.imread('demo.png')  
kernel = np.ones((8,8), np.uint8)  
image = cv2.erode(img, kernel, iterations=1)  
cv2.imshow('result', image)
cv2.waitKey(0)  
cv2.destroyAllWindows()

In this code, first we imported the required libraries, OpenCV and NumPy. Then, we used cv2.imread() to read the image. Then, we define a structuring element(kernal) for the erosion operation. This is a small matrix of a specific size, we used a 8x8 matrix. After this, we used the  cv2.erode function, which takes three arguments: the input image, the structuring element, and the number of iterations. At last, we used the cv2.imshow to display the final result.

Result: