Morphological operations are image processing techniques applied on binary images to remove noise, enhance shapes, and extract useful structures. The most common operations are erosion, dilation, opening, and closing.
Erosion reduces the boundaries of white regions, making objects thinner. Useful for removing small white noise.
import cv2
import numpy as np
img = cv2.imread("sample.jpg", cv2.IMREAD_GRAYSCALE)
_, thresh = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY)
kernel = np.ones((5,5), np.uint8)
erosion = cv2.erode(thresh, kernel, iterations=1)
cv2.imshow("Erosion", erosion)
cv2.waitKey(0)
cv2.destroyAllWindows()
Dilation expands white regions, making objects thicker. Useful for filling small black holes inside objects.
dilation = cv2.dilate(thresh, kernel, iterations=1)
cv2.imshow("Dilation", dilation)
cv2.waitKey(0)
cv2.destroyAllWindows()
Opening is erosion followed by dilation. It helps remove small noise while keeping the main object intact.
opening = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, kernel)
cv2.imshow("Opening", opening)
cv2.waitKey(0)
cv2.destroyAllWindows()
Closing is dilation followed by erosion. It is useful for closing small black holes inside white objects.
closing = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel)
cv2.imshow("Closing", closing)
cv2.waitKey(0)
cv2.destroyAllWindows()
✅ In this lesson, you learned about erosion, dilation, opening, and closing operations in OpenCV.
These techniques are widely used for noise removal, shape analysis, and image preprocessing.
👉 With this, we complete Module 2: Image Transformations & Filtering. Next, we’ll test your knowledge with Quiz 2 🎯
