Sub topic 3
Cleaning masks with morphological operations
This chapter assumes you can threshold an image to a binary mask with cv2.threshold and can load, save and index images with cv2 and NumPy. You should also know what a grayscale image is. The goal is to turn a noisy mask into one that cv2.findContours can turn into a few clean contours.
Why masks need cleaning
A thresholded image is rarely perfect. Sensor noise leaves isolated white specks in the background. Uneven lighting punches small black holes into objects. Two shapes that sit close together can fuse into one blob. Each of these defects changes the contours you get. Specks become tiny contours, holes become child contours, and fused shapes become a single contour with the wrong area.
Morphological operations fix these defects by working on the shape of regions rather than on pixel brightness. Each operation slides a small pattern, called a structuring element (or kernel), over the mask and decides each output pixel from the neighbors the kernel covers. This chapter treats white (255) as the foreground and black (0) as the background. If your mask has the opposite polarity, invert it first, because every operation below acts on the white regions.
The structuring element
A structuring element is a small binary array that defines which neighbors count. Its size controls how strong the operation is. Its shape controls the direction of the effect.
Use cv2.getStructuringElement to build one:
import cv2
rect = cv2.getStructuringElement(cv2.MORPH_RECT, (5, 5))
ellipse = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5))
cross = cv2.getStructuringElement(cv2.MORPH_CROSS, (5, 5))
print(rect)
print(ellipse)
print(cross)| Shape | Constant | Typical use |
|---|---|---|
| Rectangle | `cv2.MORPH_RECT` | General purpose, fastest to reason about |
| Ellipse | `cv2.MORPH_ELLIPSE` | Rounded objects, avoids squaring off corners |
| Cross | `cv2.MORPH_CROSS` | Gentle effect that follows horizontal and vertical lines only |
Kernel sizes should be odd, such as 3, 5 or 7, so that the kernel has a center pixel. A larger kernel removes larger specks and fills larger holes, but it also distorts real shapes more.
Erosion and dilation
The two basic operations are opposites.
- Erosion keeps a pixel white only if every pixel under the kernel is white. White regions shrink, thin features disappear, and small specks vanish.
- Dilation makes a pixel white if any pixel under the kernel is white. White regions grow, small gaps close, and small holes fill in.
import cv2
import numpy as np
mask = np.zeros((120, 120), np.uint8)
cv2.rectangle(mask, (30, 30), (90, 90), 255, -1)
mask[10, 10] = 255 # an isolated speck
mask[60, 60] = 0 # a one-pixel hole
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3))
eroded = cv2.erode(mask, kernel, iterations=1)
dilated = cv2.dilate(mask, kernel, iterations=1)
print("white pixels original:", int(np.count_nonzero(mask)))
print("white pixels eroded: ", int(np.count_nonzero(eroded)))
print("white pixels dilated: ", int(np.count_nonzero(dilated)))The eroded mask has fewer white pixels, because the speck disappears and the square loses a one-pixel border. The dilated mask has more, because the hole fills and the square grows by a one-pixel border.
The iterations argument applies the operation repeatedly. Two iterations with a 3x3 kernel have roughly the effect of one pass with a 5x5 kernel, though not exactly for every kernel shape.
Opening and closing
Erosion and dilation on their own change the size of objects. Combining them removes defects while keeping object size roughly the same. Use cv2.morphologyEx for the combinations.
- Opening is erosion followed by dilation. It removes white specks smaller than the kernel and breaks thin bridges between objects. Objects that survive the erosion are grown back to about their original size.
- Closing is dilation followed by erosion. It fills black holes smaller than the kernel and joins nearby fragments. The outer boundary returns to about where it started.
import cv2
import numpy as np
mask = np.zeros((120, 120), np.uint8)
cv2.rectangle(mask, (30, 30), (90, 90), 255, -1)
mask[10, 10] = 255
mask[60:62, 60:62] = 0
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5))
opened = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel)
closed = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel)
clean = cv2.morphologyEx(opened, cv2.MORPH_CLOSE, kernel)
for name, m in [("mask", mask), ("opened", opened), ("closed", closed), ("clean", clean)]:
contours, _ = cv2.findContours(m, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_SIMPLE)
print(f"{name:7s} contours: {len(contours)}")The raw mask yields three contours: the square, the speck and the hole. Opening alone removes the speck. Closing alone fills the hole. Applying both leaves one contour.
The order matters. Open first to delete background noise, then close to repair the objects. If you close first, a speck that sits next to an object can merge into it, and opening can no longer remove it.
The block above is intentionally not used. The pipeline below shows the usual order instead.
Other useful operations
cv2.morphologyEx supports more operations built from the same two primitives.
| Operation | Constant | What it returns |
|---|---|---|
| Gradient | `cv2.MORPH_GRADIENT` | Dilation minus erosion, which is an outline of thickness about one kernel |
| Top hat | `cv2.MORPH_TOPHAT` | Original minus opening, which keeps small bright details |
| Black hat | `cv2.MORPH_BLACKHAT` | Closing minus original, which keeps small dark details |
Top hat and black hat are also useful on grayscale images before thresholding. Black hat with a large kernel highlights dark text on an unevenly lit page, which makes a global threshold work better.
Choosing kernel size and shape
Pick the kernel from the sizes in your image, not by guessing.
- Estimate the largest noise speck you want to delete, in pixels. The opening kernel must be larger than that speck.
- Estimate the largest hole you want to fill. The closing kernel must be larger than that hole.
- Estimate the thinnest real feature you want to keep. Both kernels must stay smaller than that feature, or it will be erased by opening or merged by closing.
- Use an ellipse kernel for round or organic objects and a rectangle for objects with axis-aligned corners.
If steps 1 and 3 conflict, because the noise is as big as the features, morphology cannot separate them. Filter by contour area afterward, or improve the threshold step instead.
You can also use non-square kernels for directional effects. A kernel of (25, 1) removes everything narrower than 25 pixels horizontally, which keeps long horizontal lines. A kernel of (1, 25) does the same for vertical lines.
Edge cases and gotchas
- Polarity. If the objects are black on white, opening removes the objects instead of the specks. Check which color is the foreground before choosing open or close, or invert with
cv2.bitwise_not. - Border behavior. OpenCV treats pixels outside the image as neutral by default, so objects touching the border are not eroded away from that side. Results near the border can still look different from the interior.
- Data type. Masks should be
uint8with values 0 and 255. A boolean array or a float array raises an error or gives wrong results. Convert withmask.astype(np.uint8) * 255. - Shape drift. Large kernels round off corners and shift thin shapes. This affects later steps such as
approxPolyDPand vertex counts, so use the smallest kernel that works. - Grayscale input. Morphology also works on grayscale images, where erosion takes the local minimum and dilation takes the local maximum. If you pass a non-thresholded image by accident, the result will not be a clean binary mask.
- In-place surprises.
morphologyExreturns a new array. Keep the original mask if you need it, for example to draw contours on the unmodified image later.
Checking your cleanup
Always look at the mask after each step. Saving intermediate images is the quickest way to find which step causes a problem.
import cv2
img = cv2.imread("shapes.png")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray, (5, 5), 0)
_, binary = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5))
opened = cv2.morphologyEx(binary, cv2.MORPH_OPEN, kernel)
clean = cv2.morphologyEx(opened, cv2.MORPH_CLOSE, kernel)
before, _ = cv2.findContours(binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
after, _ = cv2.findContours(clean, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
print("contours before cleanup:", len(before))
print("contours after cleanup: ", len(after))
cv2.imwrite("mask_raw.png", binary)
cv2.imwrite("mask_clean.png", clean)If the count after cleanup is still much larger than the number of shapes you expect, increase the opening kernel or filter by area. If it is smaller than expected, the kernels are probably too big and are merging or erasing real objects.
Exercise
A mask shows white shapes on a black background. It has many one- or two-pixel white specks in the background, and each shape has a few one-pixel black holes inside it. Which operations do you apply, in which order, and why does the order matter?
Show answer
Apply opening first, then closing. Opening (erosion then dilation) deletes the white specks while the larger shapes survive and grow back to their size. Closing (dilation then erosion) then fills the small holes inside the shapes. If you close first, a speck next to a shape can be merged into it and opening can no longer remove it. Use a kernel larger than the specks and holes (for example 5x5) but smaller than the thinnest real feature.
Exercise
You apply cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel) to a mask of black objects on a white background, and the objects get smaller or vanish. What is wrong, and how do you fix it?
Show answer
Morphology treats white as the foreground, so opening shrinks and removes the white background features, and closing or dilation grows the white area at the expense of the black objects. Invert the mask with cv2.bitwise_not(mask) (or use cv2.THRESH_BINARY_INV when thresholding) so the objects are white, then apply the operations.