Sub topic 14
Cleaning masks with erosion, dilation, opening and closing
This chapter assumes you can read an image with cv2.imread, know that a binary mask is a uint8 array holding only 0 and 255, and have already produced a mask with cv2.threshold or cv2.adaptiveThreshold. Thresholding rarely gives a clean result. You usually get isolated white specks in the background and small black holes inside the objects. Morphological operations fix both problems.
Why masks need cleanup
A threshold decides each pixel on its own. It ignores neighbors, so sensor noise, texture and small lighting changes leave errors that are only a few pixels wide. Convolution filters average values, which doesn't suit a binary image. Morphology works on shape instead. It asks whether a small pattern, the structuring element, fits inside the white region around each pixel.
In this chapter white (255) is the foreground and black (0) is the background. If your mask is the other way round, invert it first with cv2.bitwise_not, or the operations will act on the wrong region.
The structuring element
A structuring element (SE) is a small binary array that defines the neighborhood. It plays the role a kernel plays in convolution, but it is used for comparisons, not for weighted sums. Its anchor is normally the center, so use odd sizes.
cv2.getStructuringElement(shape, ksize) builds one:
| Shape constant | Footprint | Effect on edges |
|---|---|---|
| `cv2.MORPH_RECT` | Filled rectangle | Keeps square corners, favors horizontal and vertical lines |
| `cv2.MORPH_ELLIPSE` | Filled ellipse (a disk for equal sides) | Rounds corners evenly in all directions |
| `cv2.MORPH_CROSS` | Plus shape | Reaches only along rows and columns |
import cv2
for name, shape in [("rect", cv2.MORPH_RECT),
("ellipse", cv2.MORPH_ELLIPSE),
("cross", cv2.MORPH_CROSS)]:
print(name)
print(cv2.getStructuringElement(shape, (5, 5)))Printing them is worth doing once. The ellipse for 5 by 5 is not a perfect disk, and small sizes look very blocky.
Erosion and dilation
Erosion keeps a pixel white only if the structuring element, centered on it, lies entirely inside white pixels. White regions shrink, thin parts disappear, and specks smaller than the element vanish.
Dilation sets a pixel white if the element, centered on it, touches at least one white pixel. White regions grow, small gaps close, and nearby objects can merge.
The two are duals. Dilating the white foreground has the same effect as eroding the black background.
import cv2
import numpy as np
mask = np.zeros((60, 60), np.uint8)
cv2.rectangle(mask, (15, 15), (45, 45), 255, -1) # one solid square
mask[5, 5] = 255 # an isolated speck
se = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3))
eroded = cv2.erode(mask, se)
dilated = cv2.dilate(mask, se)
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 square is 31 by 31 pixels, plus one speck, so the original has 962 white pixels. Erosion removes the speck and trims one pixel from each side of the square, leaving 29 by 29, or 841. Dilation grows the square to 33 by 33 and the speck to 3 by 3, giving 1098. Run it to confirm. The point of the example is that erosion and dilation alone change the object size, not just the noise.
Opening and closing
Combining the two cancels the size change while keeping the noise-removing effect.
- Opening is erosion followed by dilation. It removes white specks and thin protrusions smaller than the element. Surviving objects return to roughly their original size.
- Closing is dilation followed by erosion. It fills black holes and narrow gaps smaller than the element, and joins nearby fragments.
Both are applied with cv2.morphologyEx. A useful memory aid: opening cleans the background, closing cleans the foreground.
import cv2
import numpy as np
rng = np.random.default_rng(0)
mask = np.zeros((120, 120), np.uint8)
cv2.circle(mask, (60, 60), 40, 255, -1)
# Add salt noise outside and pepper noise inside the disk.
noise = rng.random(mask.shape)
mask[(noise < 0.02) & (mask == 0)] = 255
mask[(noise > 0.98) & (mask == 255)] = 0
se = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5))
opened = cv2.morphologyEx(mask, cv2.MORPH_OPEN, se)
cleaned = cv2.morphologyEx(opened, cv2.MORPH_CLOSE, se)
print("white pixels noisy: ", int(np.count_nonzero(mask)))
print("white pixels opened: ", int(np.count_nonzero(opened)))
print("white pixels cleaned:", int(np.count_nonzero(cleaned)))The order matters. Opening first removes the outside specks, so closing cannot grow them into larger blobs. If you close first, a speck next to the object can bridge to it and become part of the foreground. Opening before closing is the safe default for noise in both regions.
Choosing the size and shape
The element size sets what counts as noise. Anything narrower than the element is removed by opening, and any gap narrower than the element is filled by closing. Pick a size just above the largest defect you want to remove and well below the smallest real feature you want to keep. A 3 by 3 element handles single-pixel noise. A 15 by 15 element will erase thin real structures such as text strokes or wires.
Use a rectangle when the objects are boxes, or when you want to join text characters along a line (a wide, short rectangle such as (25, 3) merges letters into words). Use an ellipse for rounded objects like cells or coins, because a rectangle slowly turns a circle into a rounded square. Use a cross for a lighter, 4-connected effect.
You can also repeat an operation with the iterations argument. Two iterations with a 3 by 3 element behave roughly like one iteration with a 5 by 5 element. This is a cheap way to scale up the effect, but for a cross or an ellipse the equivalence is only approximate.
Other morphological operations
cv2.morphologyEx supports a few more operations that build on erosion and dilation:
| Operation | Definition | Typical use |
|---|---|---|
| `cv2.MORPH_GRADIENT` | dilation minus erosion | Outlines of objects, a thick edge map of a mask |
| `cv2.MORPH_TOPHAT` | original minus opening | Bright small features on an uneven background |
| `cv2.MORPH_BLACKHAT` | closing minus original | Dark small features on a bright background |
These also work on grayscale images. In that case erosion takes the local minimum and dilation takes the local maximum under the element.
Common mistakes
- Wrong polarity. If the objects are black on a white background, opening removes the objects' thin parts and closing fills the background. Invert the mask, or choose the thresholding flag
cv2.THRESH_BINARY_INV, so the foreground is white. - Oversized element. A large element deletes real detail and rounds corners. Increase the size in small steps and inspect the result.
- Even element sizes. The anchor cannot sit on a center pixel, which shifts the result by half a pixel. Use odd sizes.
- Using the wrong dtype. Morphology on a mask that holds 0 and 1 works, but displaying it shows an almost black image. Multiply by 255 to view it.
- Cleaning before thresholding well. Morphology cannot rescue a bad threshold. If whole regions are missing, fix the threshold (for example with Otsu or an adaptive method) before you fix the mask.
- Expecting exact size preservation. Opening and closing are idempotent, so repeating them changes nothing, but they do change shape. Opening removes sharp convex corners, and closing removes sharp concave ones.
A reusable cleanup function
Wrapping the cleanup in a function keeps the parameters in one place, which helps when you tune them later in a pipeline.
import cv2
import numpy as np
def clean_mask(mask, open_size=3, close_size=7):
"""Remove small white specks, then fill small black holes."""
if mask.dtype != np.uint8:
raise ValueError("mask must be uint8 with values 0 or 255")
se_open = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (open_size, open_size))
se_close = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (close_size, close_size))
opened = cv2.morphologyEx(mask, cv2.MORPH_OPEN, se_open)
return cv2.morphologyEx(opened, cv2.MORPH_CLOSE, se_close)
mask = np.zeros((100, 100), np.uint8)
cv2.rectangle(mask, (20, 20), (80, 80), 255, -1)
mask[50, 50] = 0 # one-pixel hole
mask[5, 5] = 255 # one-pixel speck
result = clean_mask(mask)
print("hole filled:", result[50, 50] == 255)
print("speck gone: ", result[5, 5] == 0)Using a small element for opening and a larger one for closing is common, because the specks are often smaller than the holes you want to bridge. Adjust each independently.
Exercise
A thresholded mask of white coins on a black table has many one-pixel white specks on the table and a few two-pixel black holes inside the coins. You apply MORPH_CLOSE first with a 5 by 5 ellipse, then MORPH_OPEN with the same element. Some specks next to coins have turned into bumps on the coin edges. What is the cause, and how do you fix it?
Show answer
Closing dilates first, so a speck close to a coin is joined to it and the following erosion cannot separate them again, which leaves a bump. Reverse the order: apply MORPH_OPEN first to delete the isolated specks, then MORPH_CLOSE to fill the holes inside the coins.
Exercise
After thresholding with cv2.THRESH_BINARY, your objects are dark on a bright background, so the mask is white background and black objects. You call cv2.morphologyEx(mask, cv2.MORPH_OPEN, se) and the objects get larger and merge. Why, and what is the simplest fix?
Show answer
Morphology treats white as foreground, so opening acts on the white background, and the black objects appear to grow as the background loses thin parts and gaps. Use cv2.THRESH_BINARY_INV when thresholding, or apply cv2.bitwise_not to the mask, so the objects are white before cleaning.