Morphological Transformations apply on image shape. It will apply in binary images.
There are various types of morphological transformation:
Erosion
In erosion basically we will remove the boundary of foreground objects. A kernel (a matrix of odd size (3,5,7) is convened with the image. 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).
Thickness of the foreground object decreases or white region decreases in the image. It is useful for removing small white noises.
erosion = cv.erode(img,kernel,iterations = 1)
Dilation
This is unlike erosion. It increases the white region in the image or size of foreground objects. Normally, in cases like noise removal, erosion is followed by dilation. Because, erosion removes white noises, but it also shrinks our object. So we dilate it. Since noise is gone, they won’t come back, but our object area increases. It is also useful in joining broken parts of an object.
dilation = cv.dilate(img,kernel,iterations = 1)
Opening
Opening is useful in removing noise. We use cv.morphologyEx() function for opening.
opening = cv.morphologyEx(img, cv.MORPH_OPEN, kernel)
Closing
Closing is opposite of Opening. It is useful in closing the small gap inside the foreground objects, or small black points on the object.
closing = cv.morphologyEx(img, cv.MORPH_CLOSE, kernel)
Gradient
Gradient is the difference between dilation and erosion of an image.
gradient = cv.morphologyEx(img, cv.MORPH_GRADIENT, kernel)
Tophat
It is the difference between input image and Opening of the image.
tophat = cv.morphologyEx(img, cv.MORPH_TOPHAT, kernel)
Blackhat
It is the difference between the closing of the input image and input image.
blackhat = cv.morphologyEx(img, cv.MORPH_BLACKHAT, kernel)
Example of Morphological Transformation
import cv2 as cv
import numpy as np
from matplotlib import pyplot as plt
img = cv.imread('img.png',0)
kernel = np.ones((5,5),np.uint8)
erosion = cv.erode(img,kernel,iterations = 1)
dilation = cv.dilate(img,kernel,iterations = 1)
opening = cv.morphologyEx(img, cv.MORPH_OPEN, kernel)
closing = cv.morphologyEx(img, cv.MORPH_CLOSE, kernel)
gradient = cv.morphologyEx(img, cv.MORPH_GRADIENT, kernel)
tophat = cv.morphologyEx(img, cv.MORPH_TOPHAT, kernel)
blackhat = cv.morphologyEx(img, cv.MORPH_BLACKHAT, kernel)
titles = ['img', 'erosion', 'dilation', 'opening', 'closing', 'gradient', 'tophat', 'blackhat']
images = [img, erosion, dilation, opening, closing, gradient, tophat, blackhat]
for i in range(6):
plt.subplot(2, 3, i+1), plt.imshow(images[i], 'gray')
plt.title(titles[i])
plt.xticks([]),plt.yticks([])
plt.show()