Template Matching

Template matching finds where a small image patch, the template , appears inside a larger image . For every offset , a score compares with the patch of whose top-left corner is at . The best match is the offset with the highest similarity or the lowest distance. In the formulas below, the sums run over all template pixels . The template mean is , and is the mean of the image patch under the template.

The lecture compares four scores. Correlation (method 0) is the cross-correlation of the image with the template:

Zero-mean correlation (method 1) subtracts the template mean first, . The sum of squared differences (SSD, or L2, method 2) is a distance, and it expands into three terms:

The first term is a constant. The second is times the correlation map. The third is the squared image filtered with a box of ones the size of the template. SSD can therefore be computed with two filtering operations and a sum. Normalized cross-correlation (NCC, method 3) subtracts both means and divides by both norms:

NCC lies in . It equals exactly when the patch is for some contrast factor and brightness offset . The lecture ranks the methods by speed and quality. The zero-mean filter is fastest but a poor matcher. SSD is next fastest and is sensitive to overall intensity. NCC is slowest, and it is invariant to local average intensity and contrast.

Project 1 aligns the three color channels of a Prokudin-Gorskii glass-plate scan with this machinery. It searches every displacement in a window such as and shifts one channel with np.roll. It scores the overlap with the L2 norm or with NCC. Border pixels are left out of the score. Large scans use a coarse-to-fine image pyramid.

Intuition

A template is a stencil, and matching slides it across the image and checks the fit at each position. The first idea is to score the fit with a dot product. Correlation computes the inner product between the template and each image patch. The inner product grows with the brightness of the patch, so a plain white wall can outscore a perfect copy of the template. Each later method removes one way the score can be fooled. Zero-mean correlation stops rewarding brightness. SSD measures the pixel differences, so it rewards only a near-copy. NCC treats the mean-removed template and patch as vectors and and measures the angle between them. Raising the patch’s contrast stretches its vector without turning it, so the angle and the score stay the same.

\usepackage{tikz}
\usepackage{amsmath}
\begin{document}
\definecolor{tem}{HTML}{2F80ED}
\definecolor{pat}{HTML}{D9483B}
\definecolor{mid}{HTML}{8A8A8A}
\begin{tikzpicture}[scale=1.6,>=latex,font=\small]
\fill[mid] (0,0) circle (1pt) node[below left] {$\mathbf{0}$};
\draw[->,very thick,tem] (0,0) -- (3,0.6) node[right] {$\tilde{\mathbf{g}}$ (template, mean removed)};
\draw[->,very thick,pat] (0,0) -- (1.2,1.1) node[above left] {$\tilde{\mathbf{f}}_{m,n}$};
\draw[->,thick,pat,dashed] (1.2,1.1) -- (2.4,2.2) node[right] {$a\,\tilde{\mathbf{f}}_{m,n}$, $a > 0$ (more contrast)};
\draw[mid] (0.7,0.14) arc (11.3:42.5:0.714);
\node[mid] at (0.95,0.42) {$\theta$};
\node[mid,align=left,right] at (1.6,-0.35) {$\text{NCC} = \cos\theta$ is the same for $\tilde{\mathbf{f}}_{m,n}$ and $a\,\tilde{\mathbf{f}}_{m,n}$};
\end{tikzpicture}
\end{document}

Properties

(Zero-Mean Correlation) Subtracting the template mean also cancels the patch mean, but the score still grows with patch contrast.

The weights sum to . Hence , and adding a constant to the patch does not change the score. A bright wall no longer wins. A patch with the same pattern at twice the contrast still scores twice as high. High-contrast regions with a roughly similar layout of dark and light therefore beat the true match. The lecture’s eye search shows this failure, with false detections well away from the eyes. A fixed detection threshold is also hard to choose, because the score has no fixed scale.

(Reading the SSD Expansion) Minimizing SSD is the same as maximizing correlation only where the local energy is constant.

The third term changes from patch to patch. A bright patch has a large , which raises its SSD, so SSD prefers patches whose energy matches the template’s. This is how SSD avoids the white-wall failure of plain correlation. Adding a constant to a patch of pixels changes its SSD by , so SSD is sensitive to overall intensity. In code, the expansion turns an SSD map into one correlation and one box filter of . Both are linear filters, so both can use the FFT for large templates.

(NCC Invariance) NCC is unchanged when the patch is replaced by with , and it changes sign when .

Subtracting the patch mean removes , and dividing by the patch norm removes . In vector form, , the Pearson correlation of the pixel values. The invariance cuts both ways. A faint smudge with the right shape scores as high as a crisp copy. NCC is undefined on a flat patch, where the denominator is , so implementations add a small constant to the denominator or skip such patches.

(Speed Ranking) The extra cost of each method is the local statistics it needs at every offset.

Zero-mean correlation is one filtering pass with the fixed kernel . SSD adds a box filter of to the correlation. NCC needs the mean and the norm of every patch, which costs box filters of and , and then a division at every offset. All three are linear in the number of template pixels per offset. The ranking reflects the constant factors.

(Coarse-to-Fine Search) A pyramid search estimates the shift on a small image, doubles it, and refines it by a pixel or two at each finer level.

An error of half a pixel at one level becomes one pixel at the next finer level. A search of or pixels around the doubled estimate is therefore enough. Each level must be blurred before it is subsampled, or aliasing creates false structure that misleads the coarse search. Too many levels leave a coarsest image with too few pixels to match, so the first estimate can lock onto the wrong shift.

(Borders) np.roll wraps pixels around the edges, so the score must ignore a margin.

After a roll by pixels, the first columns hold pixels from the opposite side of the image. Glass-plate scans also have black and white borders that differ from channel to channel. Both effects add large errors that have nothing to do with alignment. The fix is to score only an interior crop, for example the image with removed from each side.

Examples

(Easy) Four Scores on One Row

A 1D template is searched in the row

indexed to . The offset is the index of the window’s first pixel. The windows at , and are , and .

(Medium) Why Project 1 Needs a Pyramid

A full-resolution glass-plate channel is about pixels, and the true shift between channels can reach pixels in each direction. Scoring one offset costs about one operation per pixel.

(Hard) When NCC Fails Across Color Channels

Project 1 names the portrait of the Emir of Bukhara as a scan whose channels do not share brightness values. Suppose a robe is bright through the blue filter and dark through the red filter. At the correct alignment, a 1D slice across the robe reads in blue and in red.

See Also