Sub topic 5
Choosing a contour approximation method
Every call to cv2.findContours takes a fourth argument that controls how many points are stored for each contour. This chapter covers what the four options do and what each one changes in the numbers you measure afterward. It also covers when the choice matters.
It assumes you can already build a clean binary image and call cv2.findContours. It also assumes you know the OpenCV 4 return value is (contours, hierarchy). Each contour is a NumPy array of shape (N, 1, 2), with one (x, y) point per row.
What the argument decides
A contour is the boundary of a white region. The boundary is a closed chain of pixels. The approximation method decides whether findContours stores every pixel of that chain or only some of them.
The method only affects how the boundary is stored. It does not change which regions are found or how they are nested. Retrieval modes, covered in a later chapter, control that.
| Constant | What is stored | Typical use |
|---|---|---|
| `cv2.CHAIN_APPROX_NONE` | Every boundary pixel | Per-pixel analysis, pixel-accurate masks |
| `cv2.CHAIN_APPROX_SIMPLE` | Only the end points of straight horizontal, vertical and diagonal runs | Default for most work |
| `cv2.CHAIN_APPROX_TC89_L1` | A reduced set chosen by the Teh-Chin algorithm | Rare, when you want fewer points on curves |
| `cv2.CHAIN_APPROX_TC89_KCOS` | A reduced set chosen by the Teh-Chin algorithm, using a curvature measure | Rare |
Seeing the difference
The script below draws a filled rectangle and a filled circle on a blank image. It then counts the stored points for each method.
import cv2
import numpy as np
img = np.zeros((200, 300), np.uint8)
cv2.rectangle(img, (20, 30), (120, 130), 255, -1)
cv2.circle(img, (210, 100), 60, 255, -1)
methods = {
"NONE": cv2.CHAIN_APPROX_NONE,
"SIMPLE": cv2.CHAIN_APPROX_SIMPLE,
"TC89_L1": cv2.CHAIN_APPROX_TC89_L1,
"TC89_KCOS": cv2.CHAIN_APPROX_TC89_KCOS,
}
for name, method in methods.items():
contours, _ = cv2.findContours(img, cv2.RETR_EXTERNAL, method)
# Sort left to right so the rectangle always comes first.
contours = sorted(contours, key=lambda c: cv2.boundingRect(c)[0])
rect, circle = contours
print(f"{name:10s} rectangle points={len(rect):4d} circle points={len(circle):4d}")The rectangle shows the clearest effect. With NONE it has 400 points, one for each boundary pixel, because a 101 by 101 pixel square has 4 × 100 boundary steps. With SIMPLE it has 4 points, one per corner, because each side is a straight run. The circle has no long straight runs, so SIMPLE removes fewer points from it. It still removes many, because curves contain short horizontal, vertical and diagonal stretches. The two TC89 variants usually keep fewer points on the circle than SIMPLE does. Exact counts depend on your OpenCV build, so print them instead of relying on remembered values.
What SIMPLE changes and what it does not
SIMPLE removes points that lie on a straight horizontal, vertical or diagonal run. These points add no information about the polygon, so polygon-based measurements stay the same. The next script checks this on the same image.
import cv2
import numpy as np
img = np.zeros((200, 300), np.uint8)
cv2.rectangle(img, (20, 30), (120, 130), 255, -1)
cv2.circle(img, (210, 100), 60, 255, -1)
def measure(method):
contours, _ = cv2.findContours(img, cv2.RETR_EXTERNAL, method)
c = max(contours, key=cv2.contourArea)
m = cv2.moments(c)
return (
len(c),
round(cv2.contourArea(c), 1),
round(cv2.arcLength(c, True), 1),
round(m["m10"] / m["m00"], 1),
round(m["m01"] / m["m00"], 1),
)
for name, method in [("NONE", cv2.CHAIN_APPROX_NONE),
("SIMPLE", cv2.CHAIN_APPROX_SIMPLE),
("TC89_L1", cv2.CHAIN_APPROX_TC89_L1)]:
n, area, perimeter, cx, cy = measure(method)
print(f"{name:8s} points={n:4d} area={area} perimeter={perimeter} centroid=({cx},{cy})")NONE and SIMPLE report the same area, perimeter and centroid for this image. The functions treat the contour as a polygon, and dropping points from the middle of a straight edge does not change the polygon. The TC89_L1 row can differ slightly from the other two, because that method may skip points where the boundary turns. It is a smoothing step, not a lossless compression.
So SIMPLE is lossless for the polygon, and the TC89 methods are lossy. If you need the area or perimeter to match a pixel-exact reference, use NONE or SIMPLE.
When NONE is worth its cost
SIMPLE is the right default. It uses less memory, and every later step that loops over contour points runs faster. Choose NONE only when you need one of these:
- Index-based boundary analysis. If you compute curvature, a distance-from-centroid signature, or a chain code, the points must be evenly spaced along the boundary.
SIMPLEleaves gaps of varying length, so the same index step means different distances. - Counting boundary pixels.
len(c)withNONEis the boundary pixel count. WithSIMPLEit is only the number of stored end points. - Resampling to a fixed number of points. Resampling from the dense chain gives a more faithful result than resampling from sparse end points.
- Drawing each boundary pixel. For example, a debug view that marks every point.
The cost is real on large images. A single contour of a large object can hold tens of thousands of points, and a noisy mask can hold thousands of small contours.
Inspecting stored points
To see which points a method kept, draw them. This helps when a later step behaves unexpectedly.
import cv2
import numpy as np
img = np.zeros((200, 300), np.uint8)
cv2.rectangle(img, (20, 30), (120, 130), 255, -1)
cv2.circle(img, (210, 100), 60, 255, -1)
contours, _ = cv2.findContours(img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
vis = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
for c in contours:
for (x, y) in c[:, 0]:
cv2.circle(vis, (int(x), int(y)), 2, (0, 0, 255), -1)
cv2.imwrite("points_simple.png", vis)With SIMPLE, you will see only four red dots on the rectangle, one at each corner. Change the method to NONE and the whole edge turns red.
A gotcha with fitting functions
Some OpenCV functions need a minimum number of points. Under SIMPLE, a contour can have fewer points than a function needs.
The code below shows the failure and a guard.
import cv2
import numpy as np
img = np.zeros((200, 200), np.uint8)
cv2.rectangle(img, (40, 40), (140, 120), 255, -1)
contours, _ = cv2.findContours(img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
c = contours[0]
print("stored points:", len(c))
try:
cv2.fitEllipse(c)
except cv2.error:
print("fitEllipse failed on the sparse contour")
dense, _ = cv2.findContours(img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
(cx, cy), (major, minor), angle = cv2.fitEllipse(dense[0])
print("ellipse center:", (round(cx, 1), round(cy, 1)))Functions that read only the polygon, such as contourArea, arcLength, moments, boundingRect, minAreaRect, convexHull and approxPolyDP, work with either method. The sparse contour already holds every corner. minEnclosingCircle also works, since its result depends only on the extreme points.
Approximation versus approxPolyDP
The method argument is not the same as cv2.approxPolyDP, which a later chapter covers.
- The chain method is chosen once, when the contour is found, and has no tolerance setting.
SIMPLEnever moves the polygon.approxPolyDPdoes, and you control how far with an epsilon value.- Use
SIMPLEto store contours compactly. UseapproxPolyDPto reduce a curved or noisy contour to a few vertices so you can count corners.
If you want a vertex count to classify a shape, the chain method will not give it to you. A noisy circle stored with SIMPLE can still hold dozens of points.
Choosing a method
In practice, start with SIMPLE. Switch to NONE when a downstream function needs more points or even spacing. Use a TC89 method only if you have tested it on your own images and the small changes to area and perimeter are acceptable.
Common mistakes
- Reading
len(c)as a shape property. The value depends on the method, so it says little about a shape. Two identical squares drawn at different sizes both have 4 points underSIMPLE. - Mixing methods between runs. Contours found with different methods are not comparable point by point. Use one method throughout a pipeline.
- Using TC89 and expecting identical measurements. These methods can shift area and perimeter. Compare against
SIMPLEbefore relying on them. - Looping over
NONEcontours in a hot path. Per-point Python loops over dense contours are slow. Use NumPy operations onc[:, 0]instead.
Exercise
You find contours with cv2.CHAINAPPROXSIMPLE and call cv2.fitEllipse on a small, filled square, and it raises an error. Why does it fail, and what is the smallest change that fixes it?
Show answer
SIMPLE stores only the four corners of the square, and cv2.fitEllipse needs at least 5 points. Find the contours with cv2.CHAINAPPROXNONE, which keeps every boundary pixel, or check len(contour) >= 5 before calling the function.
Exercise
A contour found with CHAINAPPROXNONE and the same contour found with CHAINAPPROXSIMPLE have very different len() values. Will cv2.contourArea return different results for them? Explain.
Show answer
No. SIMPLE removes only points that lie on straight horizontal, vertical or diagonal runs. The polygon is unchanged, so contourArea, arcLength and the moments match. Only the TC89 methods can change these values slightly.