Sub topic 15
Common Pitfalls and Debugging Checklist
This chapter assumes you know basic Python, NumPy indexing, image loading with OpenCV, and grayscale pixel values. It focuses on diagnosing contour results that are missing, excessive, or geometrically wrong.
Start with the binary mask
Most contour failures begin before cv2.findContours. Inspect the image passed to it, not only the final drawing.
A contour usually traces white foreground regions on a black background. If your objects are dark on a light background, use an inverted threshold. If the polarity is wrong, OpenCV may detect the background as one large contour.
import cv2
image = cv2.imread("objects.png")
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blurred = cv2.GaussianBlur(gray, (5, 5), 0)
_, mask = cv2.threshold(
blurred, 0, 255,
cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU
)
contours, _ = cv2.findContours(
mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE
)
print("mask values:", set(mask.ravel()))
print("contours:", len(contours))
cv2.imwrite("debug-mask.png", mask)A valid binary mask normally contains only values 0 and 255. Print its minimum, maximum, and number of nonzero pixels when debugging. A mask that is entirely black or entirely white cannot produce useful object contours.
Diagnose the processing pipeline
Use this order when results are wrong:
Wrong polarity
Use cv2.THRESH_BINARY_INV when the objects are darker than their background. With adaptive thresholding, inspect whether lighting changes cause parts of one object to split. A global threshold can fail under uneven illumination, while an adaptive threshold can create extra texture contours.
Noisy or broken masks
Small specks create many tiny contours. Opening, which erodes and then dilates, removes small foreground noise. Closing, which dilates and then erodes, fills small gaps. The kernel size controls how aggressively nearby pixels are changed.
Do not apply large kernels automatically. They can merge separate objects, remove narrow parts, or change measured area and perimeter.
Check API choices and measurements
The retrieval mode must match the question. Use RETR_EXTERNAL for only outer objects. Use RETR_TREE when holes and nested contours matter. A hole may appear as a child contour, so counting every returned contour can overcount objects.
The approximation method also affects memory and detail. CHAIN_APPROX_NONE stores nearly every boundary pixel. CHAIN_APPROX_SIMPLE compresses straight runs and is usually sufficient for measurements and drawing.
OpenCV 4 returns contours and hierarchy like this:
contours, hierarchy = cv2.findContours(
mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE
)Some older OpenCV versions returned three values:
_, contours, hierarchy = cv2.findContours(
mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE
)If code fails during unpacking, check cv2.__version__ rather than changing later processing.
| Symptom | Likely cause | Check |
|---|---|---|
| One huge contour | Wrong polarity or connected background | Inspect the mask |
| Many tiny contours | Sensor noise or texture | Filter by area and try opening |
| Missing object parts | Threshold too strict or erosion too strong | Compare grayscale and mask |
| Wrong shape labels | Approximation tolerance is unsuitable | Tune epsilon as a fraction of perimeter |
| Incorrect hole count | Retrieval mode ignores hierarchy | Use `RETR_TREE` and inspect parents |
Checklist before trusting results
- Draw contours on a copy of the original image.
- Print contour count and nonzero mask pixels.
- Filter by area before calculating centroids.
- Check
m["m00"]before dividing to avoid zero-area errors. - Treat circularity and vertex counts as heuristics, not proof.
- Compare measurements after changing threshold or kernel size.
- Use
cv2.minEnclosingCircleor a rotated rectangle when axis-aligned boxes are misleading.
Exercise
Your mask is entirely white and RETR_EXTERNAL returns one contour around the image border. What should you inspect first?
Show answer
Inspect threshold polarity and the binary mask. The background is probably white foreground, so invert the threshold or correct the segmentation before finding contours.