Sub topic 14
Comparing Shapes with `matchShapes`
Prerequisites and working model
This chapter assumes that you can load images with OpenCV, work with NumPy arrays, and create binary masks. A contour is a sequence of points that follows the boundary of a connected white region in a binary image.
cv2.matchShapes compares two contours by calculating Hu moments. Hu moments are seven numeric values that describe a shape while reducing the effects of translation, scale, and rotation. The function returns a dissimilarity score:
- A score near
0means the contours are similar. - A larger score means the contours differ more.
- The score is relative, not a percentage.
- There is no universal cutoff that identifies a match for every image collection.
The comparison depends on the contour boundary. It does not compare the original colors or textures inside the shapes.
import cv2
def largest_contour(path):
image = cv2.imread(path, cv2.IMREAD_GRAYSCALE)
if image is None:
raise FileNotFoundError(f"Could not read {path}")
blurred = cv2.GaussianBlur(image, (5, 5), 0)
_, binary = cv2.threshold(
blurred, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU
)
contours, _ = cv2.findContours(
binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE
)
if not contours:
raise ValueError(f"No contour found in {path}")
return max(contours, key=cv2.contourArea)
template = largest_contour("template.png")
candidate = largest_contour("candidate.png")
score = cv2.matchShapes(
template,
candidate,
cv2.CONTOURS_MATCH_I1,
0.0
)
print(f"dissimilarity: {score:.6f}")The first three arguments identify the contours and the comparison method. cv2.CONTOURS_MATCH_I1 selects one of OpenCV's Hu-moment comparison formulas. The final argument is reserved for the method and is normally 0.0.
What the comparison measures
The matching process follows this path:
Translation, scale, and rotation usually have little effect because Hu moments are designed to be invariant to those changes. Reflection is a special case. A mirrored shape can produce a different result, so test mirrored examples if orientation does not matter in your application.
The preprocessing still matters. If thresholding removes part of a shape, adds a hole, or joins two objects, matchShapes compares the damaged boundary. It cannot recover the intended shape.
| Situation | Likely effect |
|---|---|
| Same shape at another size | Usually a low score |
| Small boundary noise | A slightly higher score |
| Missing or added parts | A much higher score |
| Wrong contour selected | A meaningless comparison |
Choosing a threshold
To turn a score into a decision, collect scores from known examples. Compare each candidate with several valid templates and record the scores. Then choose a threshold that separates valid and invalid examples on your data.
Use contour filtering before matching when a mask contains noise. Select contours by area, position, or hierarchy rather than assuming contours[0] is the desired object. Also verify that both contours represent comparable objects. Comparing a filled outer contour with a contour around a hole answers a different question.
Exercise
Exercise
A candidate has a much higher matchShapes score than expected. Name two checks you should perform before changing the score threshold.
Show answer
Check that both contours represent the intended objects and inspect the binary masks for wrong polarity, missing regions, noise, or merged shapes.