Dilation
Dilation involves dilating the outer surface (the foreground) of the image. As binary images only contain two pixels 0 and 255, it primarily involves expanding the foreground of the image and it is suggested to have the foreground as white. The thickness of erosion depends on the size and shape of the defined kernel. We can make use of NumPy’s ones() function to define a kernel. There are a lot of other functions like NumPy zeros, customized kernels, and others that can be used to define kernels based on the problem at hand. It is exactly opposite to the erosion operation
Code:
- Import the necessary packages as shown
- Read the image
- Binarize the image.
- As it is advised to keep the foreground in white, we are performing OpenCV’s invert operation on the binarized image to make the foreground white.
- We are defining a 3×3 kernel filled with ones
- Then we can make use of the Opencv dilate() function to dilate the boundaries of the image.
Python3
import cv2 # read the image img = cv2.imread(r "path to image" , 0 ) # binarize the image binr = cv2.threshold(img, 0 , 255 , cv.THRESH_BINARY + cv.THRESH_OTSU)[ 1 ] # define the kernel kernel = np.ones(( 3 , 3 ), np.uint8) # invert the image invert = cv2.bitwise_not(binr) # dilate the image dilation = cv2.dilate(invert, kernel, iterations = 1 ) # print the output plt.imshow(dilation, cmap = 'gray' ) |
Output:
The output should be a thicker image than the original one.
Python OpenCV – Morphological Operations
Python OpenCV Morphological operations are one of the Image processing techniques that processes image based on shape. This processing strategy is usually performed on binary images.
Morphological operations based on OpenCV are as follows:
- Erosion
- Dilation
- Opening
- Closing
- Morphological Gradient
- Top hat
- Black hat
For all the above techniques the two important requirements are the binary image and a kernel structuring element that is used to slide across the image.