Sub topic 15
Common pitfalls and debugging checklist
This chapter assumes you can load and save images with cv2, index NumPy arrays, and have already used cv2.threshold, cv2.findContours, cv2.contourArea and cv2.approxPolyDP. It collects the failures that show up most often in contour pipelines and gives a repeatable way to find the cause.
Most contour bugs come from the stage before findContours. The function only traces the boundaries of white regions in a binary image. If the mask is wrong, every later measurement is wrong too.
A debugging mindset: inspect each stage
A contour pipeline has stages: grayscale, blur, threshold or edges, morphology, contours, filtering, measurement. Save or display the output of every stage. The first stage that looks wrong is your culprit.
A small helper makes this routine. It writes the mask and an overlay of the contours so you can look at them.
import cv2
def debug_dump(img, binary, contours, prefix="debug"):
cv2.imwrite(f"{prefix}_mask.png", binary)
overlay = img.copy()
cv2.drawContours(overlay, contours, -1, (0, 255, 0), 2)
cv2.imwrite(f"{prefix}_overlay.png", overlay)
print("mask shape:", binary.shape, "dtype:", binary.dtype)
print("white pixels:", cv2.countNonZero(binary), "of", binary.size)
print("contours:", len(contours))The "white pixels" line is a quick polarity test, described next.
Pitfall 1: wrong polarity
findContours treats non-zero pixels as the object and zero pixels as background. If your objects are dark on a light page and you use THRESH_BINARY, the objects become black and the page becomes white. You then get one huge contour around the whole image border, or contours of the gaps between objects.
Symptoms:
- One contour with an area close to
width * height. - Most pixels in the mask are white when you expected a small fraction.
- Drawn contours trace the image edge.
Fix: use THRESH_BINARY_INV for dark objects on a light background, as in the first example of this tutorial, or invert the mask with cv2.bitwise_not.
import cv2
gray = cv2.imread("shapes.png", cv2.IMREAD_GRAYSCALE)
blur = cv2.GaussianBlur(gray, (5, 5), 0)
_, binary = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
white_fraction = cv2.countNonZero(binary) / binary.size
if white_fraction > 0.5:
binary = cv2.bitwise_not(binary)
print("mask was mostly white, inverted it")The 0.5 rule is a heuristic. It fails when the objects genuinely cover most of the image, so treat it as a hint, not a guarantee.
Pitfall 2: noisy masks
Without blurring, sensor noise and JPEG artifacts create isolated white pixels and ragged edges. Each speck becomes a contour, and ragged edges inflate the perimeter and the vertex count after approximation.
There are three tools, and each solves a different problem:
| Problem | Tool |
|---|---|
| Speckle noise before thresholding | `GaussianBlur` or `medianBlur` |
| Isolated white specks in the mask | Morphological opening (`MORPH_OPEN`) |
| Small holes inside objects | Morphological closing (`MORPH_CLOSE`) |
| Specks that remain after cleanup | Filter by `contourArea` |
import cv2
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5))
clean = cv2.morphologyEx(binary, cv2.MORPH_OPEN, kernel)
clean = cv2.morphologyEx(clean, cv2.MORPH_CLOSE, kernel)Keep the kernel smaller than the features you want to keep. An opening with a kernel wider than a thin object erases that object. A closing with a large kernel merges neighboring shapes into one contour.
Pitfall 3: findContours modifies or consumes its input
In OpenCV 3.x, findContours modified the input image. In OpenCV 4 it does not. Many older tutorials copy the mask defensively with binary.copy(). That is harmless, but you no longer need it.
A related error is passing the wrong kind of image. findContours expects a single-channel 8-bit image. Passing a three-channel BGR image raises an error. Passing a grayscale image that was not thresholded does not raise an error: every non-zero pixel counts as foreground, so nearly the whole image becomes one blob.
Pitfall 4: OpenCV version differences in the return value
The return signature changed between versions:
| Version | Return value |
|---|---|
| OpenCV 3.x | `image, contours, hierarchy` |
| OpenCV 2.4 and 4.x | `contours, hierarchy` |
If you copy 3.x code onto OpenCV 4, you get an error such as "too many values to unpack" or, worse, you unpack the wrong items. Check your version with cv2.__version__. A version-proof unpacking takes the last two items:
import cv2
result = cv2.findContours(binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
contours, hierarchy = result[-2:]
print("OpenCV", cv2.__version__, "contours:", len(contours))Two more version-related details. In OpenCV 4, contours is a tuple of arrays, not a list, so you cannot call contours.sort(...). Use sorted(contours, key=cv2.contourArea, reverse=True). Also, when no contours are found, hierarchy is None, so code that indexes hierarchy[0] fails on an empty mask.
Pitfall 5: the wrong retrieval mode
The retrieval mode decides which contours you get.
RETR_EXTERNALreturns only outermost contours. Holes and nested shapes are dropped. Use it when you only want outlines.RETR_LISTreturns everything with no parent-child information.RETR_TREEreturns everything and records the full nesting.
A common surprise: with RETR_TREE or RETR_LIST on a filled shape, you get a single contour. On a ring or a shape with a hole, you get two: the outer boundary and the hole boundary. If you count objects and get twice the expected number, you are probably counting holes as objects. Filter on hierarchy[0][i][3] == -1 to keep only top-level contours.
import cv2
contours, hierarchy = cv2.findContours(binary, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
if hierarchy is None:
print("no contours found")
else:
top_level = [c for i, c in enumerate(contours) if hierarchy[0][i][3] == -1]
print("objects:", len(top_level), "total contours:", len(contours))Remember also that the hierarchy has a leading dimension of size 1, so a row is hierarchy[0][i], not hierarchy[i].
Pitfall 6: coordinates and shapes of contour arrays
Each contour has shape (N, 1, 2), with points stored as (x, y). That means column first, row second. NumPy images index as img[y, x]. Mixing these up gives transposed results.
To get a plain (N, 2) array, use c.reshape(-1, 2) or c[:, 0, :].
drawContours and many shape functions require the int32 or float32 type. If you build a contour by hand from a Python list, create it with np.array(points, dtype=np.int32).reshape(-1, 1, 2).
Pitfall 7: division by zero in moments
The centroid formula divides by m["m00"], which is the area. Tiny contours, such as a single point or a perfectly thin line, have m00 == 0. The code int(m["m10"] / m["m00"]) then raises ZeroDivisionError.
import cv2
def centroid(contour):
m = cv2.moments(contour)
if m["m00"] == 0:
x, y = contour[0][0]
return int(x), int(y)
return int(m["m10"] / m["m00"]), int(m["m01"] / m["m00"])Filtering by a minimum area before computing moments avoids most of these cases. The fallback above covers the rest.
Pitfall 8: approximation and classification thresholds
approxPolyDP uses an epsilon, the maximum distance between the original contour and the approximation. The spine example uses 0.04 * perimeter. Small epsilon values keep noise vertices, so a square can become a polygon with 6 or 8 vertices. Large values collapse real corners, so a rectangle can become a triangle.
Other classification traps:
- A rotated square still has 4 vertices, but the upright
boundingRectgives a width-to-height ratio that is not near 1. UseminAreaRectfor the aspect ratio when rotation is possible. - Circularity works poorly on small contours, because pixel quantization dominates the perimeter. Apply the test only above a minimum area.
- A half-visible shape touching the image border is cut off, so its vertex count is wrong. Consider discarding contours that touch the border.
- Perspective and blur change vertex counts. Treat the vertex-count rule as a heuristic for clean, frontal shapes.
Pitfall 9: drawing problems
drawContoursdraws on the image you pass in. Draw onimg.copy()if you need the original afterward.- Drawing a color on a grayscale image shows as gray. Convert with
cv2.cvtColor(gray, cv2.COLOR_GRAY2BGR)first. - A thickness of
-1fills the contour. If your shapes appear as solid blobs, check this argument. - The contour index
-1draws all contours. Passing a single contour object instead of a list is a common mistake: usecv2.drawContours(out, [c], -1, color, 2).
Pitfall 10: unstable thresholds across images
A fixed threshold value such as 127 works on one lighting condition and fails on another. Otsu's method picks a global threshold per image, which helps when the histogram is bimodal. When illumination is uneven, for example a shadow across a page, a global threshold cannot work. Use cv2.adaptiveThreshold instead, or flatten the background first.
Debugging checklist
- Print
binary.shape,binary.dtypeand the white-pixel fraction. It should be 2-D,uint8, and mostly black for typical scenes. - Save the mask and look at it. Are the objects white?
- Print
cv2.__version__and confirm the unpacking offindContours. - Print the number of contours. Compare to the number you expect.
- Print the sorted areas. A clear gap between noise and real objects tells you where to set the minimum area.
- Check
hierarchy is Nonebefore indexing. - Draw contours on a copy and look at them.
- For classification, print the vertex count and the epsilon for each contour, not only the final label.
- Test on a synthetic image where you know the answer, as in the exercise below.
Exercise
Your script finds exactly one contour whose area equals about 99 percent of the image area, though the image shows several dark shapes on white paper. You used THRESH_BINARY. What is the most likely cause, and give two ways to fix it?
Show answer
The polarity is wrong. THRESHBINARY makes the bright paper white, so findContours traces the paper as one large object. Fix it by using THRESHBINARYINV (with Otsu if desired), or by applying cv2.bitwisenot to the binary mask before calling findContours.
Exercise
You count objects with RETR_TREE and get 6 for an image containing 3 rings. Explain why, and write the condition that counts only the rings.
Show answer
Each ring has an outer boundary and an inner hole boundary, so RETRTREE returns two contours per ring. Count only top-level contours, where the parent index is -1: sum(1 for i in range(len(contours)) if hierarchy[0][i][3] == -1). Using RETREXTERNAL also gives 3.
Exercise
Why does this code crash on some contours, and how do you fix it? cx = int(m["m10"] / m["m00"])
Show answer
For degenerate contours such as a single point or a zero-width line, m00 (the area) is 0, so the division raises ZeroDivisionError. Check m["m00"] == 0 first and fall back to a contour point, or skip contours below a minimum area.