Sub topic 14
Comparing shapes with matchShapes
This chapter assumes you can extract contours with cv2.findContours from a clean binary image, and that you know what area, perimeter and image moments are. It covers how cv2.matchShapes scores the similarity of two shapes, how to read that score, and where it fails.
What matchShapes does
Sometimes you do not want to name a shape. You want to know whether one contour looks like another. Examples are finding every bolt in a bin using one reference bolt, or checking that a printed logo matches a template.
cv2.matchShapes takes two contours (or two grayscale images) and returns a single float. The value is a dissimilarity score. A score of 0 means the shapes are identical as far as the measure can tell. Larger values mean the shapes differ more.
The score is built from Hu moments. These are seven numbers computed from the image moments of a shape. They are designed to stay the same when the shape is translated, scaled or rotated. So a small square and a large square rotated by 30 degrees score close to 0 against each other.
How the score is computed
The steps inside matchShapes are:
- Compute the spatial moments of each contour, then the seven Hu invariants for each. Call them h1 to h7 for shape A and shape B.
- Convert each invariant to a signed logarithmic scale:
m = sign(h) * log10(abs(h)). Hu values span many orders of magnitude, and the log scale keeps the large-magnitude terms from dominating. - Combine the seven pairs with one of three formulas, chosen by the method argument.
| Method constant | Formula over i = 1..7 | Notes |
|---|---|---|
| `cv2.CONTOURS_MATCH_I1` | sum of abs(1/mA_i - 1/mB_i) | The usual first choice. |
| `cv2.CONTOURS_MATCH_I2` | sum of abs(mA_i - mB_i) | Differences on the log scale. |
| `cv2.CONTOURS_MATCH_I3` | max of abs(mA_i - mB_i) / abs(mA_i) | Relative to shape A, so it is not symmetric. |
The fourth argument is a parameter that OpenCV currently ignores. Pass 0.0.
A first comparison
The following example builds three synthetic images. It draws a square, a rotated and scaled copy of a square, and a circle. Then it compares each to the first square. It runs as shown and needs only OpenCV and NumPy.
import cv2
import numpy as np
def largest_contour(img):
contours, _ = cv2.findContours(img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
return max(contours, key=cv2.contourArea)
square = np.zeros((300, 300), np.uint8)
cv2.rectangle(square, (100, 100), (160, 160), 255, -1)
rotated = np.zeros((300, 300), np.uint8)
box = cv2.boxPoints(((200, 150), (100, 100), 30))
cv2.fillPoly(rotated, [box.astype(np.int32)], 255)
circle = np.zeros((300, 300), np.uint8)
cv2.circle(circle, (150, 150), 40, 255, -1)
ref = largest_contour(square)
for name, img in [("rotated and scaled square", rotated), ("circle", circle)]:
score = cv2.matchShapes(ref, largest_contour(img), cv2.CONTOURS_MATCH_I1, 0.0)
print(f"{name}: {score:.4f}")The rotated and scaled square scores very close to 0. The circle scores noticeably higher, because its Hu invariants differ from those of a square even though both are compact, convex shapes. Exact values depend on rasterization, so do not rely on specific digits.
Reading the score
There is no universal threshold. The scale depends on the method, the shapes, and the image resolution. A practical workflow is:
- Pick a few images that you know are good matches and a few that are not.
- Print the scores for both groups with the method you plan to use.
- Choose a threshold that separates the groups, and leave a margin.
For many simple shapes, scores below about 0.05 to 0.1 with CONTOURS_MATCH_I1 indicate a close match. Treat this only as a starting point to tune against your own data.
Because the score is a distance, you can use it to rank. To classify an unknown contour against several templates, compute the score against each and take the minimum:
import cv2
def best_match(candidate, templates, method=cv2.CONTOURS_MATCH_I1):
"""templates: dict of label -> contour. Returns (label, score)."""
scores = {
label: cv2.matchShapes(template, candidate, method, 0.0)
for label, template in templates.items()
}
label = min(scores, key=scores.get)
return label, scores[label]Add a rejection threshold on top of this. Without one, every contour gets some label, even noise that resembles none of your templates.
What the score ignores
Hu moments are invariant to position, scale and rotation. That is useful, and it also defines what the measure cannot see.
- Rotation. A square and the same square turned 45 degrees look identical to
matchShapes. If orientation matters, for example telling an upright "I" from a lying-down "I", use another check such ascv2.minAreaRectangles. - Scale. A tiny speck with a square outline matches a large square. Filter by area first (see the chapter on filtering contours).
- Reflection. The seventh Hu invariant changes sign under mirror reflection, but the log-scale methods use its magnitude in ways that make the effect small. Do not depend on
matchShapesto separate a shape from its mirror image. - Fine detail. Moments summarize the whole shape. Small notches or a few extra pixels barely change the score. Two shapes with the same overall mass distribution can score as similar even if they look different to a person.
The measure also depends on whether you pass contours or filled masks. A contour is a list of boundary points, and OpenCV computes moments from the polygon they enclose. A hollow ring and a solid disc with the same outer boundary give the same result from the outer contour alone, since the hole is a separate contour under RETR_TREE. Use RETR_EXTERNAL for both if you want to ignore holes, and keep the choice the same for template and candidate.
Sources of error
Degenerate contours
A contour with zero area, such as a single point or a straight line, has m00 == 0. Its moments cannot be normalized, so the Hu values are not meaningful and the score can be 0, huge or nan. Always filter with cv2.contourArea before matching:
valid = [c for c in contours if cv2.contourArea(c) > 100]Pixelation on small shapes
Shapes only a few pixels wide have jagged outlines, and the jaggedness changes their Hu values. Two copies of the same small shape drawn at different rotations can score worse than the same shape at a larger size. Match at a reasonable resolution, or resample both shapes onto masks of a fixed size first.
Inconsistent preprocessing
Template and candidate must go through the same pipeline: the same blur, threshold polarity and morphology. If the template was extracted from a clean synthetic image and the candidate from a noisy photo, a nonzero baseline score is normal and your threshold must allow for it.
Method asymmetry
CONTOURS_MATCH_I3 divides by the invariants of the first shape. Swapping the arguments changes the result. Fix the argument order, with the template first, and keep it.
A matching pipeline
Putting the pieces together:
import cv2
def find_matches(binary, template_contour, threshold=0.1, min_area=100):
contours, _ = cv2.findContours(binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
results = []
for c in contours:
if cv2.contourArea(c) < min_area:
continue
score = cv2.matchShapes(template_contour, c, cv2.CONTOURS_MATCH_I1, 0.0)
if score < threshold:
results.append((score, c))
results.sort(key=lambda item: item[0])
return resultsWhen to use something else
matchShapes is a cheap global comparison. It suits cases where overall form is the signal and orientation or size is not. Prefer other tools in these cases:
- The shape must be a specific polygon, such as a triangle. Use
approxPolyDPand the vertex count. - Orientation or size matters. Compare
minAreaRectangle and area directly. - The object has texture or internal structure, not just an outline. Use template matching or feature descriptors.
- The scene has heavy occlusion. Whole-contour moments change when part of the outline is hidden.
Summary of the working model
matchShapesreturns a dissimilarity from Hu moments, where 0 is identical.- It ignores position, scale and rotation, and barely reacts to fine detail.
- Choose a threshold from your own labeled examples, not from a fixed number.
- Filter tiny contours first, preprocess template and candidate the same way, and keep the argument order fixed.
Exercise
You compare a template contour against a candidate with cv2.matchShapes and get a score of 0.003. The candidate is the same shape as the template but rotated by 90 degrees, and your application must reject rotated parts. Explain why the score is low and describe one way to add the missing check.
Show answer
Hu moments are invariant to rotation, so a rotated copy of the same shape scores near 0 regardless of the angle. To reject rotated parts, add an orientation check after the match. For example, compute cv2.minAreaRect for both contours and compare the angles, accepting the candidate only when the difference is within a tolerance. Handle the angle convention of your OpenCV version, since the range reported by minAreaRect changed between releases.
Exercise
A loop calls cv2.matchShapes(template, c, cv2.CONTOURS_MATCH_I1, 0.0) for every contour from a noisy image, and sometimes the result is nan or an absurdly large value. What is the most likely cause, and what is the fix?
Show answer
The loop includes degenerate contours with zero area, such as a single point or a line. Their m00 moment is 0, so the Hu moments are undefined. Fix it by skipping contours where cv2.contourArea(c) is below a minimum, for example 100 pixels, before calling matchShapes.