Dilation and Erosion are two primary image operations in mathematical Morphology. Dilation is applied to binary images. The main effect of the dilation on a binary image is to continuously increase the boundaries of regions of foreground pixels (for example, white pixels, typically). Thus areas of foreground pixels expand in size while holes within those regions become smaller.
Python cv2 dilate
The cv2.dilate() is an OpenCV function in Python that applies a morphological filter to images. The cv2.dilate() method takes two inputs, of which one is our input image; the second is called the structuring element or kernel, which decides the nature of the operation. Image dilation Increases the object area.
See the following syntax of cv2.dilate() method.
cv2.dilate(src, kernel[, anchor[, iterations[, borderType[, borderValue]]]])
The dilate() function takes the following parameters.
- image: It is a required parameter and an original image on which we need to perform dilation.
- kernel: 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.
- borderType: It depicts what kind of border to be added. Flags like cv2 define it.BORDER_CONSTANT, cv2.BORDER_REFLECT, etc.
- iterations: It is an optional parameter that takes several iterations.
- borderValue: It is border value in case of a constant border.
The dilation increases the white region in the image or the size of the foreground object increases.
# app.py import numpy as np import cv2 img = cv2.imread('data.png', 1) cv2.imshow('Original', img) kernel = np.ones((5, 5), 'uint8') dilate_img = cv2.dilate(img, kernel, iterations=1) cv2.imshow('Dilated Image', dilate_img) cv2.waitKey(0) cv2.destroyAllWindows()
In this example, first, we have imported cv2 and numpy modules.
Then we are reading an image using the imread() method.
In the next step, we have defined a kernel for dilation. We used the np.ones() function to determine the kernel matrix. The kernel is a set of coordinates, also known as a structuring element.
Then we used the cv2.dilate() function and passed the three arguments: image, kernel, and iterations. We take iterations = 1 for this example.
In the final steps, we have displayed a dilated image.
Image dilation is helpful because if you have performed Erosion, then Erosion already removed the white noises, but it also contracts our object. So we dilate it. They won’t come back since the noise is gone, but our object area increases. Dilation helps join broken parts of an object.