Sub topic 9
Filtering out noise by contour measurements
This chapter assumes you can run cv2.findContours on a binary image and read its return values. It also assumes you know what area, perimeter and bounding box mean for a contour. Everything here uses OpenCV 4 and the Python API.
Why contours need filtering
Thresholding never produces a perfect mask. Sensor noise, JPEG artifacts, dust and texture leave small white specks, and each speck becomes its own contour. The picture frame or a shadow can also become one huge contour that swallows everything.
You cannot always fix these problems earlier, with blur or morphology. Filtering by measurement is the last line of defense. It keeps the contours that match what you expect to see and discards the rest.
The rule is simple. Compute a number for each contour, compare it to a limit, and keep or drop the contour. The skill is choosing numbers that separate the real objects from the junk.
The measurements
The table lists the measurements that work well as filters. Each one is a single number computed from the contour.
| Measurement | How to compute it | Good for rejecting | Caveat |
|---|---|---|---|
| Area | `cv2.contourArea(c)` | Specks, frame-sized blobs | Depends on image resolution |
| Perimeter | `cv2.arcLength(c, True)` | Ragged, noisy outlines | Grows with edge roughness |
| Aspect ratio | `w / h` of `cv2.boundingRect(c)` | Thin lines, bars | Upright box only; rotated shapes change it |
| Extent | `area / (w * h)` | Diagonal or sparse shapes | Rotation lowers it |
| Solidity | `area / hull_area` | Ragged or concave blobs | Needs a convex hull |
| Circularity | `4 * pi * area / perimeter**2` | Anything that is not round | Equals 1.0 only for a perfect circle |
Area is the first filter to apply because it is the cheapest and removes the most junk. The others refine what is left.
A complete, runnable example
The script below builds its own test image, so you need no input file. It draws a rectangle, a circle and a thin bar, then scatters 40 small specks over the image.
import cv2
import numpy as np
# Build a test image: white background, three dark shapes, random specks.
img = np.full((300, 400, 3), 255, np.uint8)
cv2.rectangle(img, (30, 30), (130, 110), (0, 0, 0), -1)
cv2.circle(img, (250, 80), 45, (0, 0, 0), -1)
cv2.rectangle(img, (200, 200), (380, 215), (0, 0, 0), -1)
rng = np.random.default_rng(0)
for _ in range(40):
x, y = int(rng.integers(0, 400)), int(rng.integers(0, 300))
cv2.circle(img, (x, y), 1, (0, 0, 0), -1)
# Inverted Otsu threshold: dark shapes become white.
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)
contours, _ = cv2.findContours(binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
print("before filtering:", len(contours))
kept = [c for c in contours if cv2.contourArea(c) >= 50]
print("after area filter:", len(kept))
out = img.copy()
cv2.drawContours(out, kept, -1, (0, 255, 0), 2)
cv2.imwrite("filtered.png", out)The first count includes every speck that is not merged into a shape. The second count should be much smaller, because a speck covers only a few pixels. Specks that landed inside a shape are absorbed into it and never appear as contours at all.
Choosing the area limits
A fixed number such as 50 works for one image size and fails for another. A speck that is 4 pixels in a small photo is still 4 pixels after a 4x upscale in width and height, but 64 pixels after you scale the image. Real objects scale along with the image, so a fixed limit becomes wrong when the resolution changes.
Express limits as a fraction of the image area instead.
h_img, w_img = binary.shape[:2]
image_area = h_img * w_img
min_area = 0.0005 * image_area # 0.05% of the image
max_area = 0.90 * image_area # reject a frame-sized contour
candidates = [c for c in contours if min_area <= cv2.contourArea(c) <= max_area]
print("candidates:", len(candidates))The upper limit matters as much as the lower one. If the threshold has the wrong polarity, the whole background becomes white. findContours then returns one contour that follows the image border, and its area is close to the image area. The maximum catches that mistake.
Contour area is not the same as the number of white pixels inside. cv2.contourArea computes the area enclosed by the outline, so holes inside a shape are not subtracted. If you need the true pixel count, draw the contour filled on a blank mask and call cv2.countNonZero on it.
Rejecting contours that touch the border
Objects cut off by the image edge are often incomplete, and their measurements are misleading. A circle with a quarter missing has a different circularity and bounding box. Drop these contours when you need whole objects.
def touches_border(c, width, height):
x, y, w, h = cv2.boundingRect(c)
return x <= 0 or y <= 0 or x + w >= width or y + h >= height
whole = [c for c in candidates if not touches_border(c, w_img, h_img)]The bounding rectangle covers the pixels the contour occupies. A contour at the left edge has x == 0, and one at the right edge reaches x + w == width. That is why the comparisons use <= and >=.
Filtering by shape measurements
After area and border tests, use shape numbers to remove things that are the right size but the wrong kind. The next script combines all the measurements in one function.
import math
def measurements(c):
area = cv2.contourArea(c)
peri = cv2.arcLength(c, True)
x, y, w, h = cv2.boundingRect(c)
hull_area = cv2.contourArea(cv2.convexHull(c))
return {
"area": area,
"aspect": w / h,
"extent": area / (w * h),
"solidity": area / hull_area if hull_area > 0 else 0.0,
"circularity": 4 * math.pi * area / (peri * peri) if peri > 0 else 0.0,
}
for c in whole:
m = measurements(c)
print({k: round(v, 2) for k, v in m.items()})
compact = [c for c in whole if 0.2 <= measurements(c)["aspect"] <= 5.0]
print("after aspect filter:", len(compact))On the test image, the rectangle has an aspect near 1.25, the circle near 1.0 and the thin bar near 12. The bar passes the area test easily, because it is large, so only the aspect test removes it. This is why one measurement is rarely enough.
Common starting ranges, to be tuned on your own data:
- A round object has circularity above 0.8. A square scores about 0.785, so use a lower cutoff if squares should pass.
- A solid, convex object has solidity above 0.9. A star or a hand scores much lower.
- A filled rectangle has extent near 1.0, while a filled circle has extent near 0.785.
Always guard divisions. A degenerate contour, such as a single point or a one-pixel line, has zero area or zero perimeter, and an unguarded division raises ZeroDivisionError in Python (or returns nan or inf in NumPy). The same applies to centroids: m["m00"] is zero for such contours, so check it before dividing.
Filtering with the hierarchy
Noise often sits inside real objects. A hole in a washer is a legitimate contour, but a speck inside a shape is not. With cv2.RETR_TREE you can use the parent index to treat these cases differently.
contours, hierarchy = cv2.findContours(binary, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
keep_idx = []
for i, c in enumerate(contours):
parent = hierarchy[0][i][3]
if parent == -1 and cv2.contourArea(c) >= 50:
keep_idx.append(i)
print("outer contours kept:", len(keep_idx))hierarchy can be None when no contours exist, so check it before indexing in production code. RETR_EXTERNAL gives the same result for this task with less work, since it never returns nested contours.
Sorting instead of thresholding
Sometimes you know how many objects to expect but not their size. Sort by area and take the top few. This avoids a fixed limit entirely.
largest = sorted(contours, key=cv2.contourArea, reverse=True)[:3]
print([cv2.contourArea(c) for c in largest])This approach fails when the true count varies, because it always returns exactly three contours even if only two real objects exist. Use it when the count is fixed. Otherwise use limits.
Common mistakes
- Filtering before checking polarity. If the mask is inverted, the filter keeps the background. Look at the binary image first.
- Hard-coded pixel limits. They break when the camera or resolution changes. Use fractions of the image area.
- Using only the minimum area. A frame-sized contour passes a minimum test. Add a maximum.
- Judging rotated shapes by the upright box. Aspect and extent change when a shape rotates. Use
cv2.minAreaRectif orientation varies. - Removing specks by raising the threshold. This also erodes real objects. Clean the mask with morphological opening, then filter what remains.
- Assuming
contoursis a list. In OpenCV 4 it is a tuple. Build a new list with a comprehension rather than calling.remove(), which does not exist on tuples.
Exercise
A contour has area 4000 and perimeter 200. Compute its circularity using 4piarea/perimeter**2, and say whether it passes a "round object" filter that requires circularity above 0.8.
Show answer
Circularity = 4 3.1416 4000 / 200**2 = 50265 / 40000 = about 1.26. That is above 1, which a real contour should not reach, because 1.0 is the maximum for a perfect circle. A value over 1 usually means the area and perimeter come from different sources, for example an area measured from a filled mask and a perimeter from a smoothed contour. It numerically passes the 0.8 filter, but you should check how the two numbers were computed before trusting it.
Exercise
Your filter keeps contours with area at least 100. After switching to a camera with twice the width and twice the height, tiny specks start passing the filter. Why, and how do you fix it?
Show answer
Doubling both dimensions multiplies every area by 4. A speck of 30 pixels becomes about 120 pixels, which now exceeds the fixed limit of 100. Define the limit as a fraction of the image area, for example min_area = 0.0005 width height, so it scales with the resolution.