Sub topic 14
Cleaning Masks with Erosion, Dilation, Opening, and Closing
This chapter assumes you know basic Python, NumPy array indexing and data types, grayscale images, and OpenCV image I/O. It also assumes you have a binary mask: an image containing foreground pixels and background pixels, usually represented by 255 and 0.
Binary masks and structuring elements
A binary mask is useful after thresholding. White pixels represent the detected object, and black pixels represent the background. Thresholding often creates small defects:
- Isolated white pixels appear as noise.
- White objects contain small black holes.
- Nearby white regions have narrow gaps.
- Object boundaries become uneven.
Morphology is a family of operations that changes shapes in a mask. Each operation examines a neighborhood defined by a structuring element, also called a kernel. The structuring element controls the shape and size of the change.
| Operation | Main effect | Typical use |
|---|---|---|
| Erosion | Shrinks white regions | Remove small white noise |
| Dilation | Expands white regions | Fill gaps or connect nearby regions |
| Opening | Erosion followed by dilation | Remove small white objects |
| Closing | Dilation followed by erosion | Fill small black holes and gaps |
Erosion and dilation
Erosion keeps a pixel white only when the structuring element fits within the white region around that pixel. It removes boundary pixels, so foreground objects become smaller. Small white components can disappear completely.
Dilation makes a pixel white when the structuring element touches a white pixel. It adds pixels around foreground objects. Dilation can connect nearby components, but it can also merge objects that should remain separate.
A larger structuring element produces a stronger change. An elliptical element often preserves rounded object shapes better than a rectangular one.
import cv2
mask = cv2.imread("mask.png", cv2.IMREAD_GRAYSCALE)
if mask is None:
raise FileNotFoundError("mask.png could not be read")
# Make sure the input is binary.
_, mask = cv2.threshold(mask, 127, 255, cv2.THRESH_BINARY)
se = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5))
eroded = cv2.erode(mask, se, iterations=1)
dilated = cv2.dilate(mask, se, iterations=1)
cv2.imwrite("eroded.png", eroded)
cv2.imwrite("dilated.png", dilated)The iterations argument repeats the operation. Increasing it has a similar effect to using a larger structuring element, although the exact result can differ.
Opening and closing
Opening removes small white components while preserving larger shapes:
- Erode the mask.
- Dilate the eroded result.
Closing fills small black gaps inside or between white regions:
- Dilate the mask.
- Erode the dilated result.
opened = cv2.morphologyEx(mask, cv2.MORPH_OPEN, se)
closed = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, se)
cv2.imwrite("opened.png", opened)
cv2.imwrite("closed.png", closed)Choose the structuring element based on the defect size you want to remove or fill. If it is too large, opening can erase valid objects and closing can join separate objects.
A practical cleanup sequence
A common mask-cleaning sequence uses opening first and closing second:
This sequence is only a starting point. If the mask contains holes but little isolated noise, closing may be enough. If objects are touching, erosion can separate them, but excessive erosion may remove thin objects.
Exercise
A mask contains many isolated white pixels and small black holes inside large white objects. Which operations should you try first, and why?
Show answer
Try opening to remove isolated white pixels, followed by closing to fill small black holes. Choose a structuring element slightly larger than the unwanted defects but smaller than valid objects.