Python cv2 erode: How to Erode Images using OpenCV
OpenCV-Python is a Python library explicitly designed to solve computer vision problems. Morphological transformations are some simple operations based on the image shape. It is usually performed on binary images. There are two main morphological transformations.
- Image Dilate
- Image Erosion
OpenCV-Python provides the cv2 module that supports the following two functions.
- cv2.dilate()
- cv2.erode()
Python cv2 erode()
To perform erosion on images, use cv2.erode() method. The erode() is generally performed on binary images. The erode() method requires two inputs; one is an input image, and the second is called a structuring element or kernel, which decides the nature of the operation.
Syntax
cv2.erode(src, kernel[, dst[, anchor[, iterations[, borderType[, borderValue]]]]])
Parameters
- image: It is a required parameter and an original image on which we need to perform dilation.
- kernel: It is the required parameter is the matrix with which the image is convolved.
- dst: It is the output image of the same size and type as image src.
- anchor: It is a variable of type integer representing the anchor point, and its default value Point is (-1, -1), which means that the anchor is at the kernel center.
- iterations: It is an optional parameter that takes several iterations.
- borderType: It depicts what kind of border to be added. It is defined by flags like cv2.BORDER_CONSTANT, cv2.BORDER_REFLECT, etc.
- borderValue: It is border value in case of a constant border.
Return Value
It returns an eroded image.
Example
# app.py import numpy as np import cv2 img = cv2.imread('data.png', 1) cv2.imshow('Original', img) kernel = np.ones((5, 5), 'uint8') erode_img = cv2.erode(img, kernel, iterations=1) cv2.imshow('Eroded Image', erode_img) cv2.waitKey(0) cv2.destroyAllWindows()
Output
In erosion, the kernel slides through the image (as happens in the 2D convolution).
A pixel in the input image (either 1 or 0) will be considered 1 only if all the pixels under the kernel is 1; otherwise, it is eroded (made to zero).
So what happens is that all the pixels near the boundary will be discarded depending upon the size of the kernel. So the thickness or size of the foreground object decreases, or the white region decreases in the image.
It is useful for removing small white noises, detach two connected objects, etc.
Let’s see another example.
# app.py import numpy as np import cv2 img = cv2.imread('data.png', 1) cv2.imshow('Original', img) kernel = np.ones((6, 6), 'uint8') erode_img = cv2.erode(img, kernel, cv2.BORDER_REFLECT, iterations=1) cv2.imshow('Eroded Image', erode_img) cv2.waitKey(0) cv2.destroyAllWindows()
Output
That is it for the Python cv2 erode() method.