What is erosion on an image using OpenCV in Python?
The basic concept of erosion is similar to that of soil erosion, except that it erodes the borders of foreground objects (always try to keep the foreground white).
The working of erosion is as follows:
- The picture is slid through the kernel (as in 2D convolution).
- A pixel in the original picture (either a 1 or a 0) will only be regarded as a
1if all of the pixels underneath the kernel are1, else it will be degraded (made to zero). - As a result, depending on the size of the kernel, any pixels along the border are eliminated. Hence, the foreground object’s thickness or size shrinks, or the image’s white region shrinks.
Some of the uses of erosion are noise removal, disconnecting connected objects in an image, removal of spurious bright spots, etc.
OpenCV is an open-source library that has a large number of computer vision algorithms.
To install the Python interface for OpenCV, we can use pip.
pip install opencv-python
The erode() function
The erode() function of OpenCV is used to apply the erosion operation on the given image with the specified kernel.
Syntax
cv2.erode(src, kernel, iterations)
Parameters
src: The image to apply the dilation on.kernel: The kernel to use.iterations: The number of iterations of erosion to be performed.
Refer to the following coding example to understand more.
Example
import cv2, numpy as npimg = cv2.imread("/test.png")kernel = np.ones((7, 7), np.uint8)eroded_img = cv2.erode(img, kernel, iterations=1)cv2.imwrite("output/Test-image.png", img)cv2.imwrite("output/eroded-image.png", eroded_img)
Explanation
- Line 1: The
cv2andnumpypackages are imported. - Line 3: The
test.pngis loaded into memory. - Line 5: The kernel is defined.
- Line 7: The image is eroded using the
erode()function. - Line 9: The test image is saved to disk.
- Line 11: The eroded image is saved to disk.
Free Resources
Copyright ©2026 Educative, Inc. All rights reserved