Eroding an image using the OpenCV function erode()

In this program, we will erode an image using the OpenCV function erode(). Erosion of image means to shrink the image. If any of the pixels in a kernel is 0, then all the pixels in the kernel are set to 0. One condition before applying an erosion function on image is that the image should be a grayscale image.

Original Image


Step 1: Import cv2
Step 2: Import numpy.
Step 3: Read the image using imread().
Step 4: Define the kernel size using numpy ones.
Step 5: Pass the image and kernel to the erode function.
Step 6: Display the output.

Example Code

import cv2
import numpy as np
image = cv2.imread('testimage.jpg')
kernel = np.ones((7,7), np.uint8)
image = cv2.erode(image, kernel)
cv2.imshow('Eroded Image', image)