In this Python OpenCV lesson we are going to learn about Python OpenCV Morphological Transformations, according to OpenCV Documentation Morphological transformations are some simple operations based on the image shape. It is normally performed on binary images. It needs two inputs, one is our original image, second one is called structuring element or kernel which decides the nature of operation. Two basic morphological operators are Erosion and Dilation. then its variant forms like Opening, Closing, Gradient etc also comes into play.
1: Erosion
The basic idea of erosion is just like soil erosion only, it erodes away the boundaries of foreground
object (Always try to keep foreground in white). So what does it do? The kernel slides through the
image (as in 2D convolution). A pixel in the original 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).
2: Dilation
It is just opposite of erosion. Here, a pixel element is ‘1’ if at least one pixel under the kernel is ‘1’. So it increases the white region in the image or size of foreground object increases. Normally, in cases like noise removal, erosion is followed by dilation. Because, erosion removes white noises, but it also shrinks our object.
3: Opening
Opening is just another name of erosion followed by dilation. It is useful in removing noise, as we explained above. Here we use the function, cv2.morphologyEx().
4: Closing
Closing is reverse of Opening, Dilation followed by Erosion. It is useful in closing small holes inside the foreground objects, or small black points on the object.
5: Morphological Gradient
It is the difference between dilation and erosion of an image.
Also there are two more that you can use we have Top Hat and Black Hat.
This is the complete source code for this lesson.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
import cv2 import numpy as np import matplotlib.pyplot as plt # it is 5 x 5 kernel example with full of ones img = cv2.imread('morphimg.png') img2 = cv2.imread('morphnoise.png') img3 = cv2.imread('morphclosing.png') kernel = np.ones((5,5),np.uint8) erosion = cv2.erode(img,kernel,iterations = 0) dilation = cv2.dilate(img,kernel,iterations = 1) opening = cv2.morphologyEx(img2, cv2.MORPH_OPEN, kernel) closing = cv2.morphologyEx(img3, cv2.MORPH_CLOSE, kernel) gradient = cv2.morphologyEx(img, cv2.MORPH_GRADIENT, kernel) titles = ["Original Image", "Erosion","Dilation", "Opening", "Closing", "Gradient" ] images = [img, erosion, dilation,opening, closing,gradient ] #in subplot we have number of rows, # number of coulmns, and image positoon for i in range(6): plt.subplot(3,3, i+1) plt.imshow(images[i]) plt.title(titles[i]) plt.xticks([]), plt.yticks([]) plt.show() cv2.waitKey(0) cv2.destroyAllWindows() |
Run the complete code and this is the result.