Sub topic 3
Cleaning Masks with Morphological Operations
Assume you know basic Python, NumPy array indexing, and how to load and save OpenCV images. This chapter also assumes that you can create a grayscale or binary mask. A binary mask is an image whose pixels usually contain only 0 for background and 255 for foreground. Contour detection works best when this mask has solid objects and few unwanted marks.
Morphological operations change foreground regions by examining each pixel's neighborhood. The neighborhood is defined by a kernel, also called a structuring element. A kernel is a small matrix, such as a 5 × 5 rectangle or ellipse.
Erosion and dilation
Erosion removes foreground pixels around object boundaries. It makes white regions smaller and can remove thin connections or isolated specks. Dilation adds foreground pixels around boundaries. It makes regions larger and can fill small gaps.
The kernel shape affects the result. A rectangular kernel expands equally in horizontal and vertical directions. An elliptical kernel usually produces smoother boundaries.
| Operation | Main effect | Common use |
|---|---|---|
| Erosion | Shrinks foreground regions | Remove small noise |
| Dilation | Expands foreground regions | Join nearby regions |
| Opening | Erosion followed by dilation | Remove small bright objects |
| Closing | Dilation followed by erosion | Fill small holes and gaps |
Opening and closing are often more useful than applying erosion or dilation alone. Opening removes details smaller than the kernel while approximately preserving larger shapes. Closing fills narrow breaks while preserving the overall object size.
A mask-cleaning workflow
The following example thresholds dark shapes on a light background, then applies opening and closing before finding contours.
import cv2
img = cv2.imread("shapes.png")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray, (5, 5), 0)
_, mask = cv2.threshold(
blur, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU
)
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5))
opened = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel, iterations=1)
clean = cv2.morphologyEx(opened, cv2.MORPH_CLOSE, kernel, iterations=1)
contours, hierarchy = cv2.findContours(
clean, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE
)
print("contours found:", len(contours))
cv2.imwrite("clean_mask.png", clean)iterations controls how many times OpenCV repeats an operation. Increasing it strengthens the effect, but it can also remove meaningful details or merge separate objects. Kernel size and iteration count should match the scale of the defects you want to fix.
Choosing the operation
Use opening when small foreground dots create false contours. Use closing when object boundaries contain small breaks or holes. If objects are touching, erosion may separate them, but excessive erosion can destroy thin objects. If a gap is larger than the kernel, closing may not fill it.
Morphology is sensitive to polarity. With the common OpenCV convention, operations treat white pixels as foreground. If your objects are black, invert the mask before cleaning. Inspect the saved mask, not just the original image, when debugging.
A useful debugging sequence is:
- Save the thresholded mask.
- Save the result after opening.
- Save the result after closing.
- Compare contour counts and areas at each stage.
- Reduce the kernel size if object details disappear.
> callout warning > Morphological cleanup cannot recover information that thresholding removed. If two objects merge into one large region, closing may make the merge worse. Adjust thresholding or use a smaller kernel before changing the contour code.
Exercise
A binary mask contains isolated white specks and small black holes inside otherwise solid objects. Which operations should you try first?
Show answer
Try opening to remove the isolated white specks, followed by closing to fill the small black holes. Inspect the intermediate masks and reduce the kernel size if real object details are lost.