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.
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).
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.
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().
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.
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):
Run the complete code and this is the result.