- Introduced by
- Computer vision community
- Year
- 1980s
- Type
- Pattern matching and detection
- Family
- Object detection
What does it do?
Template matching locates a known pattern (the template) within a larger image by sliding the template across the image and computing a similarity measure at each position.
Positions with high similarity are reported as candidate locations of the template. The method is most useful for simple detection tasks where the object's appearance is well defined and varies little.
The intuition behind the method
Template matching compares a small reference image (the template) with the image region it overlaps at every possible position in a larger image. At each position a similarity score is computed. For normalized cross-correlation, higher values indicate better agreement; for sum of squared differences, the best match is the minimum. Normalized cross-correlation compares intensity patterns after normalizing local statistics, so it responds to the pattern's structure rather than to overall brightness. The resulting similarity map is searched for peaks (or minima, for distance measures) that indicate likely template positions.
History
Template matching is an early computer-vision technique built on correlation, a concept from signal processing. Its wide use in industrial machine vision dates from the 1980s. Its main drawback, the cost of exhaustive sliding-window search, motivated faster implementations. Briechle and Hanebeck (2001) showed that normalized cross-correlation can be computed quickly by representing the template as a sum of rectangular basis functions. Their approach can outperform Fourier-transform based implementations and is especially suited to searching many different templates in the same image. The method has no single attributed originator; it belongs to the general computer-vision literature. Modern learned detectors have largely superseded template matching for complex scenes, though it remains a practical baseline.
When to use it
Choose template matching when the object keeps nearly the same shape, size, and orientation across images, when a representative template can be cut from an example image, and when lighting is reasonably stable or can be normalized. It suits repeated search for one known pattern in controlled settings, such as locating a component on an assembly line or a logo in a document. Avoid it when the object rotates, changes scale or perspective, deforms, or differs in appearance across the image set. In those cases feature-based methods (such as the SIFT approach listed among related methods) or learned detectors are usually more suitable. Avoid it also when no good template exists, because the output depends directly on that choice.
Limitations and considerations
- Not invariant to rotation, scale, or perspective change: a rotated or resized object gives a low score against a template of different orientation or size.
- Normalized cross-correlation only partly compensates for lighting. It normalizes local brightness and contrast but cannot handle strong or non-uniform illumination and shadows that change the intensity pattern itself.
- Requires a representative template; a template that contains background clutter or mixes several object variants produces many false positives.
- A naive sliding-window computation costs time proportional to the number of image pixels multiplied by the number of template pixels. This is why faster algorithms are needed for large images or large templates.
Source conditions do not replace independent scientific review or validation by an analysis engine.
Strengths
- Works directly on pixel intensities, so no feature extraction or training data set is needed; the template itself serves as the model.
- Evaluates every candidate position in the search image, so detection does not depend on first finding keypoints in either image.
- Normalized cross-correlation reduces sensitivity to uniform brightness and contrast changes compared with plain correlation.
- Fast normalized cross-correlation implementations, such as the rectangular-basis approach of Briechle and Hanebeck (2001), are especially suited to searching many different templates in the same image.
- Several instances of the same template can be returned, since each local peak above the threshold is a separate candidate.
Applications
- Quality control: detecting the presence or correct position of components in manufacturing
- Document processing: locating logos, stamps, or barcodes in documents
- Video tracking: tracking an object across frames by matching the template to consecutive frames
- Satellite imagery: locating specific geographic features or landmarks
How it works
How it works
Define the template as a small image containing only the pattern to be found, and load the target image in which to search. No model parameters are estimated at this stage.
No parameters are learned from data in this method. This step covers the choices made before the search: optional preprocessing of the template and target, such as normalization or smoothing, and the similarity measure, for example normalized cross-correlation or sum of absolute differences.
Slide the template over every valid position in the target image and compute the similarity at each position. Local peaks of the resulting similarity map (or local minima, for distance-based measures) are the match candidates.
Set the threshold on labelled validation images that resemble the intended application data. Sweep the threshold and record how the number of false positives and missed detections changes, then choose the value that suits the application. A single object often produces a cluster of high scores at neighbouring positions, so apply non-maximum suppression to keep only the strongest peak within each neighbourhood. Finally, check the retained detections visually or against ground-truth annotations. For normalized cross-correlation, scores are bounded and a perfect match gives the maximum value, so thresholds should be read relative to the scores observed on validation data.
Common pitfalls
- Using a template that includes background clutter. Background pixels lower the score of true matches and can create false peaks elsewhere in the image.
- Applying the method across scale or rotation variation without accounting for those transformations, which leads to missed detections.
- Choosing the similarity threshold by hand without validation data. The threshold trades missed detections against false positives and should be tuned on labelled examples.
- Reading results near image borders, where part of the template falls outside the image. Scores there are unreliable and these positions should be masked or excluded.
Frequently asked questions
What is normalized cross-correlation and why is it better than simple correlation?
Normalized cross-correlation accounts for local intensity variations by dividing by the standard deviation of both template and image region. This makes matches robust to global intensity changes (e.g., brightness increase). Simple correlation gives higher values for bright regions regardless of pattern similarity, whereas normalized cross-correlation isolates the pattern structure.
How does template matching handle multiple instances?
Template matching produces a similarity map with multiple peaks, each representing a potential match. By thresholding the similarity map and finding local maxima, multiple instances can be detected. Non-maximum suppression can be applied to eliminate overlapping detections from nearby peaks.
Can template matching detect rotated or scaled versions of the template?
Standard template matching cannot detect rotations or scale changes. However, multi-scale or multi-orientation variants exist: compute similarity at multiple template scales and rotations, then find the best match across all variants. This approach is slower but handles some variation. For large transformations, feature-based or deep learning methods are more efficient.
Why is template matching sensitive to lighting changes?
Template matching relies on intensity patterns. If the template is created under different lighting than the target image, intensity values differ even if the object is in the same position. Normalized cross-correlation partially mitigates this by normalizing local statistics, but it cannot handle extreme lighting variation. Preprocessing (histogram equalization) or learning-based methods are more robust.
Related methods
Sources
Lewis, J. P. (2004). Fast normalized cross-correlation. Vision Interface, 120–123.
Open publication referenceBriechle, K., & Hanebeck, U. D. (2001). Template matching using fast normalized cross correlation. SPIE Proceedings, 4387, 95–102.
Open DOI reference