Sub topic 13
Convex Hulls and Convexity Defects
This chapter assumes you can already run cv2.findContours, read a contour as an (N, 1, 2) array of points, and compute contour area with cv2.contourArea. It uses the Python API of OpenCV 4.
A contour tells you where a shape's boundary is. The convex hull and its defects tell you how that boundary bends. They help you describe concave shapes such as a hand with spread fingers, a star, or a bite taken out of a disk.
What a convex hull is
The convex hull of a set of points is the smallest convex polygon that contains all of them. A common picture is a rubber band stretched around the shape. The band touches only the outermost points and skips over any dents.
A shape is convex if a straight line between any two of its points stays inside the shape. Circles, rectangles and triangles are convex. A letter "C" or a star is not.
Computing the hull
cv2.convexHull has two output forms, selected by returnPoints.
returnPoints=True(the default) returns the hull as an array of coordinates. Use this for drawing or measuring the hull.returnPoints=Falsereturns the indices of the hull points within the original contour. You need this form forcv2.convexityDefects.
import cv2
img = cv2.imread("shapes.png")
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, hierarchy = cv2.findContours(binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
c = max(contours, key=cv2.contourArea)
hull = cv2.convexHull(c) # coordinates, shape (M, 1, 2)
out = img.copy()
cv2.drawContours(out, [hull], -1, (255, 0, 0), 2)
cv2.drawContours(out, [c], -1, (0, 255, 0), 1)
cv2.imwrite("hull.png", out)
print("contour points:", len(c), "hull points:", len(hull))Pass the hull to drawContours inside a list, because that function expects a list of contours. The hull has the same (M, 1, 2) layout as a contour, so every contour function accepts it, including cv2.contourArea and cv2.arcLength.
The hull of a convex shape is nearly the shape itself. The hull of a concave shape has fewer points than its contour, because it skips the dents.
Convexity defects
A convexity defect is a dent between the contour and its hull. Take any two neighboring hull points. The contour between them may bulge inward. The deepest point of that inward stretch is the defect's "far point".
cv2.convexityDefects(contour, hull_indices) returns one row per defect. Each row has four integers:
| Field | Meaning |
|---|---|
| start | Index into the contour of the hull point where the defect begins |
| end | Index into the contour of the hull point where the defect ends |
| far | Index into the contour of the deepest point of the dent |
| depth | Distance from the far point to the hull edge, as a fixed-point value |
The first three values are indices, not coordinates. Use them to look up points in the contour. The depth is stored as an integer with 8 fractional bits, so divide it by 256 to get pixels.
c = max(contours, key=cv2.contourArea)
hull_idx = cv2.convexHull(c, returnPoints=False)
defects = cv2.convexityDefects(c, hull_idx)
if defects is not None:
for start, end, far, depth in defects[:, 0]:
print("deepest point:", tuple(c[far][0]), "depth:", depth / 256.0)
hull_area = cv2.contourArea(cv2.convexHull(c))
solidity = cv2.contourArea(c) / hull_area if hull_area > 0 else 0
print("solidity:", solidity)defects has shape (K, 1, 4), so defects[:, 0] gives a (K, 4) array that unpacks cleanly in the loop. When the shape has no defects, for example a rectangle or a circle, the function returns None. Always check for None before indexing.
Drawing the defects
Marking the far points and the hull edges makes it easy to see what the function found.
out = img.copy()
cv2.drawContours(out, [c], -1, (0, 255, 0), 2)
if defects is not None:
for start, end, far, depth in defects[:, 0]:
s = tuple(c[start][0])
e = tuple(c[end][0])
f = tuple(c[far][0])
cv2.line(out, s, e, (255, 0, 0), 1)
cv2.circle(out, f, 4, (0, 0, 255), -1)
cv2.imwrite("defects.png", out)Each blue line is a hull edge. Each red dot is the deepest point of the dent behind that edge.
Filtering defects by depth
Real masks have small ripples along the boundary. These produce many shallow defects that carry no meaning. Filter by depth to keep only the significant ones.
MIN_DEPTH = 10.0 # pixels; tune for your image scale
significant = []
if defects is not None:
for start, end, far, depth in defects[:, 0]:
if depth / 256.0 >= MIN_DEPTH:
significant.append(tuple(c[far][0]))
print("significant defects:", len(significant))A fixed pixel threshold depends on image size. A more portable option is to compare depth with the size of the shape, for example depth / 256.0 > 0.05 * max(w, h) using the bounding box from cv2.boundingRect.
A classic use is counting spread fingers in a hand mask. Each gap between two fingers produces one deep defect, so the finger count is roughly the number of significant defects plus one. This estimate breaks down when fingers touch or when only one finger is raised, since no defect appears in that case.
Solidity
Solidity is the contour area divided by the hull area. It is a single number between 0 and 1.
- Near 1.0: the shape is almost convex, such as a rectangle, circle or triangle.
- Clearly below 1.0: the shape has dents or arms, such as a star, a "C" or a hand.
Solidity is unchanged by translation, scaling and rotation, which makes it a useful filter. For example, you can separate round coins from irregular debris, or find a shape with an arm sticking out.
| Shape | Typical solidity |
|---|---|
| Filled circle or rectangle | About 1.0 |
| Five-pointed star | About 0.5 to 0.6 |
| Open hand, fingers spread | About 0.6 to 0.8 |
| Letter "C" | Below 0.7, depending on the opening |
These values are rough guides, not thresholds to copy. Measure solidity on your own masks before choosing a cutoff.
Testing convexity
cv2.isContourConvex(contour) returns True when a contour is convex. It works best on simplified polygons from approxPolyDP. On a raw contour with many pixel-level points, a single stray pixel can make it return False. Comparing solidity with a threshold such as 0.95 is often more tolerant.
Edge cases and gotchas
- Passing the wrong hull form.
convexityDefectsneeds indices. If you pass the coordinate form fromconvexHull(c), OpenCV raises an error. CallconvexHull(c, returnPoints=False)for this purpose. - Self-intersecting contours.
convexityDefectsrequires monotonically ordered hull indices. Contours fromfindContoursnormally satisfy this. A contour you build by hand or fromapproxPolyDPon a messy shape may not, and the function then fails or returns odd values. - Hull of a tiny contour. A contour with only one or two points has a degenerate hull with zero area. Guard the division when computing solidity, as the code above does.
- Unfilled holes. The hull comes from the outer contour. If you use
RETR_TREE, inner contours (holes) have their own hulls, which are rarely what you want. Compute hulls from outer contours. - Choice of approximation.
CHAIN_APPROX_SIMPLEkeeps the corner points, so hulls and defects are still accurate. HeavyapproxPolyDPsimplification can erase small defects. - Depth units. Forgetting the division by 256 makes every defect look very deep. A depth value of 2560 is 10 pixels.
Putting it together
The function below summarizes a contour with hull-based measurements.
def describe_concavity(contour, min_depth=10.0):
hull_pts = cv2.convexHull(contour)
hull_area = cv2.contourArea(hull_pts)
solidity = cv2.contourArea(contour) / hull_area if hull_area > 0 else 0.0
count = 0
if len(contour) >= 4:
hull_idx = cv2.convexHull(contour, returnPoints=False)
defects = cv2.convexityDefects(contour, hull_idx)
if defects is not None:
count = int(sum(1 for d in defects[:, 0] if d[3] / 256.0 >= min_depth))
return {"solidity": solidity, "deep_defects": count}
for contour in contours:
if cv2.contourArea(contour) < 100:
continue
print(describe_concavity(contour))A circle gives solidity near 1 and zero deep defects. A star gives lower solidity and one deep defect per notch between the points.
Exercise
A contour has a convexity defect row (start, end, far, depth) = (12, 40, 25, 3840). What is the depth in pixels, and what do the numbers 12, 40 and 25 refer to?
Show answer
The depth is 3840 / 256 = 15 pixels. The numbers 12, 40 and 25 are indices into the contour's point array: the hull point where the dent starts, the hull point where it ends, and the deepest point of the dent. Look up coordinates with c[25][0] and similar.
Exercise
You compute solidity for a mask and get 0.98, but the hull has far fewer points than the contour. Is that a contradiction?
Show answer
No. Solidity compares areas, not point counts. A contour can have many points along nearly straight or slightly rippled edges, and the hull skips them. A solidity of 0.98 means the shape fills almost all of its hull, so any dents are tiny.
Exercise
Why does cv2.convexityDefects(c, cv2.convexHull(c)) fail, and how do you fix it?
Show answer
convexHull returns point coordinates by default, but convexityDefects needs the indices of the hull points in the contour. Call cv2.convexHull(c, returnPoints=False) and pass that result instead.