Sub topic 9
Filtering Out Noise by Contour Measurements
Assume you know basic Python, NumPy indexing, and how to load and save images with OpenCV. A contour is a curve around a connected foreground region in a binary image. Threshold noise often creates many tiny contours. Measuring each contour lets you keep meaningful objects and reject unwanted regions.
Measure each contour
OpenCV represents a contour as an array of boundary points. These measurements are useful:
| Measurement | Meaning | Common use |
|---|---|---|
| Area | Number of pixels inside the contour | Remove tiny noise |
| Perimeter | Length of the contour boundary | Compare boundary complexity |
| Centroid | Center of the contour | Locate an object |
| Bounding rectangle | Upright rectangle around the contour | Check object size and position |
The contour area is measured in square pixels. The perimeter is measured in pixels. Neither measurement is automatically a real-world unit unless the image has been calibrated.
Image moments provide the centroid. The moments m00, m10, and m01 are calculated from the contour:
cx = m10 / m00cy = m01 / m00
A degenerate contour can have m00 == 0, so check before dividing.
Filter by area and other measurements
This example keeps contours with enough area and prints their measurements:
import cv2
img = cv2.imread("shapes.png")
if img is None:
raise FileNotFoundError("Could not read shapes.png")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray, (5, 5), 0)
# Dark objects on a light background become white foreground regions.
_, binary = cv2.threshold(
blur, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU
)
contours, _ = cv2.findContours(
binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE
)
minimum_area = 100
kept = []
for contour in contours:
area = cv2.contourArea(contour)
if area < minimum_area:
continue
perimeter = cv2.arcLength(contour, True)
moments = cv2.moments(contour)
if moments["m00"] == 0:
continue
cx = moments["m10"] / moments["m00"]
cy = moments["m01"] / moments["m00"]
x, y, width, height = cv2.boundingRect(contour)
kept.append(contour)
print(
f"area={area:.0f}, perimeter={perimeter:.1f}, "
f"centroid=({cx:.1f}, {cy:.1f}), "
f"box=({x}, {y}, {width}, {height})"
)
result = img.copy()
cv2.drawContours(result, kept, -1, (0, 255, 0), 2)
cv2.imwrite("filtered_contours.png", result)minimum_area is a starting value, not a universal constant. Choose it from the expected object size and image resolution. You can also filter by width, height, perimeter, or aspect ratio.
For example, a very wide and short region might be a shadow or a broken border:
aspect_ratio = width / float(height)
if 0.25 <= aspect_ratio <= 4.0:
kept.append(contour)Apply multiple tests only when each test represents a real property of the objects. Excessive filtering can remove valid small or rotated objects.
Debug filtering decisions
Draw rejected contours in red and accepted contours in green. This reveals whether the threshold is wrong or the measurement rule is too strict. If all contours are tiny, inspect the binary image first. A wrong foreground polarity, fragmented object, or noisy threshold must be fixed before tuning the area limit.
Exercise
Why should a program test moments["m00"] before calculating a centroid?
Show answer
The centroid divides m10 and m01 by m00. If m00 is zero, the division is invalid and the contour cannot provide a usable area-based centroid.