Morphological transformation
Erosion cv.erode
The basic idea of erosion is like soil erosion, it erodes the boundaries of foreground objects (try to keep the foreground white).
Specific method : the kernel slides through the image (in 2D convolution). A pixel (whether it is 1 or 0) in the original image is considered 1 only when all the pixels under the kernel are 1, otherwise it will be eroded (become 0).
Result : According to the size of the kernel, all pixels near the boundary will be discarded. The thickness or size of the foreground object is reduced
, or only the white area in the image is reduced. It helps to remove small white noise, separate two connected objects, etc.
img = cv.imread('3.png',0)
kernel = np.ones((5,5),np.uint8)
erosion = cv.erode(img,kernel,iterations = 1)
#或者erosion = cv.morphologyEx(img, cv.MORPH_ERODE, kernel)
Expand cv.dilate()
Contrary to erosion, if at least one pixel under the kernel is "1", then the pixel element is "1". Therefore, the width of the white area in the image or the size of the foreground object will be increased.
Usually, in the case of noise elimination, it will expand after corrosion, because corrosion will eliminate white noise, but it will also shrink the object. It is also useful when connecting damaged parts of objects.
img = cv.imread('3.png',0)
kernel = np.ones((5,5),np.uint8)
erosion = cv.dilate(img,kernel,iterations = 1)
#或者 erosion = cv.morphologyEx(img, cv.MORPH_DILATE, kernel)
cv .morphologyEx() function
This function is used for morphological operations, mainly including the following operations.
————MORPH_OPEN – Opening operation
————MORPH_CLOSE – Closing operation
————MORPH_GRADIENT-Morphological gradient
————MORPH_TOPHAT-"Top hat" ("Top hat")
————MORPH_BLACKHAT-"Black hat"
————MORPH_ERODE-"Corrosion"
————MORPH_DILATE-"Expansion"
Open operation
It erodes and then expands, helping to eliminate noise.
kernel = np.ones((8,8),np.uint8)
opening = cv.morphologyEx(img, cv.MORPH_OPEN, kernel)
Closed operation
The closing operation is the opposite of the opening operation, first expansion and then erosion. It is useful when closing small holes inside the foreground object or small black spots on the object
.
kernel = np.ones((8,8),np.uint8)
closing = cv.morphologyEx(img, cv.MORPH_CLOSE, kernel)
Morphological gradient
It is the difference between expansion and corrosion, a bit like an outline.
kernel = np.ones((8,8),np.uint8)
gradient= cv.morphologyEx(img, cv.MORPH_GRADIENT, kernel)
Top hat
The difference between the input image and the image opening operation.
kernel = np.ones((8,8),np.uint8)
tophat = cv.morphologyEx(img, cv.MORPH_TOPHAT, kernel)
Black hat
The difference between the input image and the image closing operation.
kernel = np.ones((8,8),np.uint8)
blackhat = cv.morphologyEx(img, cv.MORPH_BLACKHAT, kernel)