Much of the current conversation about computer vision starts with a model. For a large class of industrial stations it should start with a question: is the scene controlled? If the camera is fixed, the lighting is stable, and the part is the same part every time, a classical localiser is often faster, cheaper to validate, and easier to explain to a quality auditor than a detector. This tutorial builds one with plain OpenCV.
1. When this approach fits
Use template matching when:
- The camera and lighting are fixed, and scale varies little (or is known from calibration).
- You need a deterministic result and a number you can trace to pixels.
- You have few or no labelled images.
- The latency budget is tight, or the target hardware has no accelerator.
Avoid it when appearance varies widely (texture, colour, heavy occlusion), or when scale changes substantially. Then use a learned detector, and keep this pipeline as a cross-check.
2. The baseline: normalised cross-correlation
cv2.matchTemplate slides a template over the image and scores each position. Prefer the normalised methods, because they tolerate global brightness and contrast changes:
import cv2
import numpy as np
img = cv2.imread('frame.png', cv2.IMREAD_GRAYSCALE)
tpl = cv2.imread('template.png', cv2.IMREAD_GRAYSCALE)
res = cv2.matchTemplate(img, tpl, cv2.TM_CCOEFF_NORMED)
_, score, _, loc = cv2.minMaxLoc(res)
print(score, loc)
The score is in roughly [-1, 1]. Note that the location is the top-left corner of the template, not its centre. Add half the template size if you want the centre.
3. Make the template good
Most failures are template failures, not algorithm failures.
- Crop to a feature-rich region, not the whole part. A uniform area correlates with everything.
- Use a mask for non-rectangular parts (
cv2.matchTemplateaccepts amaskargument forTM_CCORR_NORMEDandTM_SQDIFF, and recent versions forTM_CCOEFF_NORMED; check your build and test it on a known frame). - Average several good captures to reduce sensor noise in the template.
- Blur image and template lightly, for example
cv2.GaussianBlurwith a 3x3 kernel, so that noise does not dominate the score.
4. Coarse-to-fine with an image pyramid
Full-resolution matching over a 12 MP frame is slow. Search at low resolution, then refine in a small window at full resolution:
def match_pyramid(img, tpl, levels=3, margin=8):
imgs, tpls = [img], [tpl]
for _ in range(levels):
imgs.append(cv2.pyrDown(imgs[-1]))
tpls.append(cv2.pyrDown(tpls[-1]))
res = cv2.matchTemplate(imgs[-1], tpls[-1], cv2.TM_CCOEFF_NORMED)
_, score, _, (x, y) = cv2.minMaxLoc(res)
for lvl in range(levels - 1, -1, -1):
x, y = x * 2, y * 2
th, tw = tpls[lvl].shape
x0, y0 = max(x - margin, 0), max(y - margin, 0)
x1 = min(x + tw + margin, imgs[lvl].shape[1])
y1 = min(y + th + margin, imgs[lvl].shape[0])
roi = imgs[lvl][y0:y1, x0:x1]
res = cv2.matchTemplate(roi, tpls[lvl], cv2.TM_CCOEFF_NORMED)
_, score, _, (dx, dy) = cv2.minMaxLoc(res)
x, y = x0 + dx, y0 + dy
return x, y, score
The risk is that a coarse level misses a small template. Keep the template at least about 16 px on its short side at the coarsest level, and verify on your worst-case frames.
5. Adding rotation
Normalised correlation is not rotation invariant. If the part can rotate, search over angles, ideally at the coarse level only:
def rotate(tpl, angle):
h, w = tpl.shape
M = cv2.getRotationMatrix2D((w / 2, h / 2), angle, 1.0)
c, s = abs(M[0, 0]), abs(M[0, 1])
nw, nh = int(h * s + w * c), int(w * s + h * c)
M[0, 2] += nw / 2 - w / 2
M[1, 2] += nh / 2 - h / 2
return cv2.warpAffine(tpl, M, (nw, nh), borderMode=cv2.BORDER_REPLICATE)
best = (-1, None, None)
for a in range(0, 360, 5):
r = cv2.matchTemplate(coarse_img, rotate(coarse_tpl, a), cv2.TM_CCOEFF_NORMED)
_, s, _, loc = cv2.minMaxLoc(r)
if s > best[0]:
best = (s, a, loc)
Then refine the angle in a narrow band (best angle +/- 5 degrees in 0.5 degree steps) at full resolution. Padding the rotated template with replicated border pixels is a compromise. A mask removes the padding bias more cleanly.
6. Sub-pixel refinement
The integer peak of the score map is only accurate to a pixel. Fit a parabola through the peak and its neighbours on each axis:
def subpixel(res, x, y):
def off(a, b, c):
d = a - 2 * b + c
return 0.0 if d == 0 else 0.5 * (a - c) / d
dx = off(res[y, x - 1], res[y, x], res[y, x + 1])
dy = off(res[y - 1, x], res[y, x], res[y + 1, x])
return x + dx, y + dy
Guard against peaks on the border of the result map, where neighbours do not exist.
7. An accept/reject rule you can defend
A score is not a decision. Build the rule from data:
- Collect a set of known-good frames and a set of known-bad ones (empty fixture, wrong part, part upside down, glare).
- Compute the best score for each.
- Plot the two distributions and choose a threshold with a margin on both sides. Record the margin.
- Also check the ratio between the best peak and the second-best peak outside a small exclusion zone. A high score with a close runner-up indicates an ambiguous match, such as a symmetric part.
Reject when either test fails, and send the frame to a review queue rather than silently dropping it.
8. Turning pixels into millimetres
A position in pixels is useful only with calibration. With a fixed camera looking at a plane, a homography from a calibration target maps pixel coordinates to plane coordinates. See our camera calibration tutorial for the full workflow. Quote the localisation uncertainty as the repeatability you measured: capture the same stationary part 50 times, and report the standard deviation of the position and angle.
9. Validation checklist
- Repeatability: standard deviation over repeated captures of a stationary part.
- Reproducibility: re-seat the part by hand 30 times and compare.
- Lighting drift: test at the lowest and highest light levels the station will see.
- Failure set: confirm every known-bad frame is rejected.
- Timing: measure the 99th percentile latency, not the mean.
10. Where a model still earns its place
A hybrid works well. Use the classical localiser for the precise pose, and a small classifier or anomaly model for the question of whether the part is acceptable. Each does the job it is best at, and the failure modes stay separable.
If you have a station where you suspect a model is overkill, or one where a classical approach has stopped being reliable, our OpenCV consultants can review it and tell you plainly which route is cheaper to validate and maintain.