You threshold a frame, call cv2.findContours, print the count, and then cv2.drawContours stops with error: (-215:Assertion failed) npoints > 0 in function 'cv::drawContours'. The count printed, so contours exist — yet drawing refuses them. In almost every case the variable you passed is not the contour list at all, but the hierarchy array that rides along in the same return tuple. This walk-through pinpoints the line, explains what each OpenCV major returns from findContours, and gives a version-safe unpacking you can keep in one helper. You finish with the corrected call, a table of return signatures by version, a one-print shape check that separates contours from hierarchy, and a synthetic-frame test that keeps the pipeline honest. The examples run on a plain Python install with numpy and cv2; the frame can come from any camera.
Why does cv2.drawContours raise npoints > 0?
Your variable named contours holds the hierarchy array, not the contour list, because OpenCV 4 returns (contours, hierarchy) from findContours and your _, contours = unpacking swaps the two. Change it to contours, _ = cv2.findContours(...) and the assertion goes away with the swap.
The failing line is the unpacking, not the drawing call. Written _, contours, the underscore receives the real contour list and contours receives the hierarchy ndarray. That array is full of genuine integers — contour indices — so print(contours) shows numbers and the run looks productive. cv2.drawContours then walks the first axis of that ndarray as if it were the list of contours, pulls out a row that is not a point array, and the guard inside the drawing code stops the call. The path in the error text, modules/imgproc/src/drawing.cpp, is the tell: detection succeeded, and the drawing arguments were wrong.
image = cv2.imread('part.jpg') # uint8, 3 channels
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # uint8, 1 channel
edged = cv2.Canny(gray, 30, 200) # uint8, 1 channel, values 0 or 255
_, contours = cv2.findContours(edged, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE) # swapped
cv2.drawContours(image, contours, -1, (0, 255, 0), 3) # raises npoints > 0
contours, _ = cv2.findContours(edged, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE) # correct
cv2.drawContours(image, contours, -1, (0, 255, 0), 3) # green outlines drawn
The Canny pair 30, 200 is an example input; the fix does not touch it. The -1 draws every contour in the list, (0, 255, 0) is BGR green and 3 is the line thickness in pixels — all three behave once the variable really holds the list.
What does cv2.findContours return in each OpenCV version?
OpenCV 2.4 returned (contours, hierarchy), OpenCV 3.x returned (image, contours, hierarchy) with the modified source image first, and OpenCV 4.x went back to (contours, hierarchy) — the middle series is why copied code disagrees with itself.
In the 3.x series the call also returned the image it modified, so a two-name unpack fails before any drawing: Python raises ValueError: not enough values to unpack at the assignment itself. That sibling failure is covered in findContours not enough values to unpack: fix the return tuple. Version 4 dropped the extra element again, which is why your two-name line runs at all — and then swaps the two objects.
| OpenCV series |
cv2.findContours returns |
What _, contours = does |
Symptom |
|---|---|---|---|
| 2.4.x | (contours, hierarchy) |
puts hierarchy into contours
|
npoints > 0 in drawContours
|
| 3.x | (image, contours, hierarchy) |
two names, three values |
ValueError at the unpack |
| 4.x | (contours, hierarchy) |
puts hierarchy into contours
|
npoints > 0 in drawContours
|
To see which series you are on, print cv2.__version__ — a string such as 4.1.1. The same build string stands in the first line of the cv2.error, so the crash itself names the major. When two references disagree, help(cv2.findContours) prints the signature your installed build actually uses; that output settles the argument.
How do you unpack findContours so it works in OpenCV 3 and 4?
Index the result from the end instead of unpacking positionally: res = cv2.findContours(...) then contours = res[-2] and hierarchy = res[-1] give the right objects in both 3.x and 4.x, because contours is always second from last.
mask = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)[1] # uint8, 1 channel
res = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
contours = res[-2] # list of ndarrays, each shaped (n, 1, 2), dtype int32
hierarchy = res[-1] # ndarray shaped (1, number_of_contours, 4)
A 3.x tuple is (image, contours, hierarchy) and a 4.x tuple is (contours, hierarchy); contours sits second from the end and hierarchy last in both, so indexing from the end lands on the right objects either way. Wrap it once and the whole codebase has a single line to audit:
def find_contours(mask, mode, method):
"""Return (contours, hierarchy) on OpenCV 3.x and 4.x."""
res = cv2.findContours(mask, mode, method)
return res[-2], res[-1]
Why did len(contours) print 1 while drawContours still failed?
The hierarchy ndarray always has shape (1, N, 4) — one outer row holding four integers per contour — so len() on it is 1 no matter how many contours were found, while a real contour list has one (n, 1, 2) int32 array per contour.
The hierarchy always has exactly one outer row, and the real list has one entry per contour found. Run both candidates on a shape with a known answer and they become impossible to confuse:
import numpy as np
import cv2
canvas = np.zeros((200, 300), dtype=np.uint8) # 300 px wide, 200 px tall
cv2.rectangle(canvas, (30, 40), (269, 159), 255, -1) # filled rectangle, 240 x 120 px
contours, hierarchy = cv2.findContours(canvas, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
print(len(contours)) # 1
print(contours[0].shape) # (716, 1, 2)
print(hierarchy.shape) # (1, 1, 4)
_, wrong = cv2.findContours(canvas, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
print(len(wrong)) # 1 — the hierarchy's outer axis, not the contour count
print(wrong[0].shape) # (1, 4) — four hierarchy integers, no points
view = cv2.cvtColor(canvas, cv2.COLOR_GRAY2BGR)
cv2.drawContours(view, wrong, -1, (0, 255, 0), 3) # npoints > 0 assertion
The rectangle spans x = 30 to 269, which is 240 columns, and y = 40 to 159, which is 120 rows. Its boundary therefore holds 2 x 240 + 2 x 120 - 4 = 716 pixels — each corner is counted once — and CHAIN_APPROX_NONE returns one point per boundary pixel, so contours[0].shape is (716, 1, 2). Under CHAIN_APPROX_SIMPLE the same rectangle is (4, 1, 2), because straight runs collapse to their end points. The mis-unpacked variable fails both checks: len(wrong) is 1 whatever the image contains, and wrong[0].shape ends in 4, not 2. One print separates the candidates anywhere: a point array is (n, 1, 2), the hierarchy's first row is (N, 4).
Does the camera or the frame source matter?
No — the assertion comes from the unpacking line, so a frame from an area scan camera, a smart camera running the pipeline on-device, or a vision controller fails identically; fix the call once and every frame source draws its outlines again.
One requirement does come from the source: findContours accepts a single-channel 8-bit image, so convert a color frame with cv2.cvtColor or threshold it before the call; a BGR frame raises its own error before any of this. After that the code is indifferent to the hardware.
On a PC-hosted camera the pipeline stays as you wrote it: read the frame, make the binary mask, then unpack the result as a contour list and a hierarchy array:
- Sensor format
- 1/1.7"
- Lens mount
- C-mount
- Interface
- GigE
- Resolution
- Up to 3 MP
The same corrected call runs on a smart camera that executes the whole contour inspection on-device and switches its pass or fail outputs without a separate PC:
- Interface
- USB 2.0
- Resolution
- 6-10 MP
- Sensor format
- 1"
- Shutter
- Global
Frames saved to disk and reloaded add a separate problem: JPEG compression peppers flat backgrounds with speckle that becomes extra contours, so keep inspection frames lossless when the count matters — findContours returns the wrong number of contours: JPEG artifacts works through the mechanism.
What if the outlines are still missing after the fix?
After the unpacking is fixed, an empty list draws nothing without any error, so check len(contours) yourself: drawContours on an empty list is a silent no-op, and a count of zero almost always means the threshold or edge step, not the call signature.
Work the remaining causes in this order:
-
The list is genuinely empty. Print
len(contours)after every change. If it is 0, the mask is empty: set the threshold midway between the object and background peaks of the gray histogram — 127 as the working start on an evenly lit 8-bit frame — and move it until the mask covers the part. - You fed it Canny edges. Edges are open, one-pixel-wide lines, and following contours on them yields fragmented rings instead of one outline per part. Threshold a filled mask instead; Canny before findContours leaves open contours: threshold the mask works the same failure in detail.
-
The count is right but full of specks. Compression artifacts, dust and background texture each become a contour. Save frames losslessly and open the mask morphologically before
findContours; in subtraction-based defect maps, image subtraction false defects: reduce contour artifacts lists the controls that matter. -
You drew one contour and expected all of them.
-1as the third argument draws every contour; an integer draws only that index.
How do you test the contour pipeline before it ships?
Feed the pipeline a synthetic frame with a known answer — one filled rectangle on a zeros background must return exactly one contour with a predictable point count — and assert both, so any signature or preprocessing change fails loudly in CI instead of on the line.
def test_filled_rectangle_is_one_contour():
canvas = np.zeros((200, 300), dtype=np.uint8)
cv2.rectangle(canvas, (30, 40), (269, 159), 255, -1)
res = cv2.findContours(canvas, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
contours = res[-2]
assert len(contours) == 1
assert contours[0].shape == (716, 1, 2)
assert contours[0].dtype == np.int32
The test encodes the arithmetic from the worked example, so it fails the day an OpenCV upgrade, a renamed variable or a rewritten preprocessing step changes what the pipeline returns. Run it in CI on the same environment the line uses.
Before you trust any contour count on the floor:
- Unpack as
contours, hierarchy = ...orres[-2], res[-1]— never_, contours = .... - Print
cv2.__version__on the machine that runs production, not only on the development laptop. - Check
contours[0].shapeonce:(n, 1, 2)means points,(N, 4)means you hold the hierarchy. - Threshold to a filled mask rather than chaining Canny into
findContours. - Keep frames that feed a count lossless, and open the mask when specks appear.
- Assert the known answer — one rectangle, 716 points — on a synthetic frame in CI.
From here the contour list feeds measurement, not just display: OpenCV contour coordinates to x and y arrays for centroid distance turns each outline into centroid coordinates. More pipeline fixes sit on the systems topic page. When the code is sound and the frame source is the limit, the camera finder narrows the choice, and if one stubborn frame keeps miscounting, ask our applications team.
Questions
What is the hierarchy array actually for?
Each contour gets four integers: the index of the next and the previous contour at the same level, then its first child and its parent, with -1 wherever the relation does not exist. RETR_EXTERNAL leaves nearly all of them -1 because it keeps only outer boundaries; RETR_TREE fills the structure in, so you can walk holes and nested objects from it.
Can you pass a plain NumPy array as one contour to drawContours?
Yes. A single contour may be an ndarray of shape (n, 1, 2) or (n, 2) holding integer coordinate pairs, not only an entry straight from findContours. Keep the coordinates integer — np.round(pts).astype(np.int32) — and never empty: the guard rejects a contour with zero points, which is the same npoints > 0 assertion.
How do you draw only the largest contour?
Pass its index as the third argument instead of -1. Rank the list with max(contours, key=cv2.contourArea) to find the biggest by area, look up its position with contours.index(...), and hand that integer to drawContours; -1 stays the shorthand for drawing every contour in the list.
Does CHAIN_APPROX_SIMPLE change the return tuple too?
No. The approximation method only changes how many points each contour carries: the 240 x 120 pixel rectangle in this guide is 716 points under CHAIN_APPROX_NONE and 4 points under CHAIN_APPROX_SIMPLE, because straight runs collapse to their end points. The tuple layout, the unpacking and the assertion behave identically.
Why does the script run on one machine and fail on another?
Because the two machines run different OpenCV builds, and the majors return different tuples: two names fit a 4.x or 2.4 build but not a 3.x one, which fails earlier with a ValueError. Print cv2.__version__ inside the same environment that runs the line — a virtualenv or container on the target often differs from your development shell.

