Dilation on an image using OpenCV in Python
Dilation of an image is the process by which the object area in the image is increased. This process is used to accentuate features in the image. It increases the white region in the image or the size of the foreground object increases.
Working of dilation:
- A kernel (a matrix of odd size (5,7,9) is convolved with the image.
- A pixel element in the original image is ‘1’ if at least one pixel under the kernel is ‘1’.
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 dilate() function
The dilate() function of OpenCV is used to apply the dilation operation on the given image with the specified kernel.
Syntax
cv2.dilate(img, kernel, iterations)
Parameters
img: The image to apply the dilation on.kernel: The kernel to use.iterations: The number of iterations of dilations 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)dilated_img = cv2.dilate(img, kernel, iterations=1)cv2.imwrite("output/Test-image.png", img)cv2.imwrite("output/dilated-image.png", dilated_img)
Explanation
- Line 1: The
opencvandnumpypackages are imported. - Line 3: The
test.pngimage is read into memory. - Line 5: The kernel is defined.
- Line 7: The image is dilated using the
cv2.dilate()method. - Line 9: The test image is saved to disk.
- Line 11: The dilated image is saved to disk.
The output image dilated-image.png shows a reduction in the object area.
Free Resources
Copyright ©2026 Educative, Inc. All rights reserved