---
title: Normalized Cross-Correlation Template Matching
url: https://www.emergentmind.com/topics/normalized-cross-correlation-template-matching
type: topic
---

# Normalized Cross-Correlation Template Matching

Normalized cross-correlation template matching is a sliding-window similarity method that compares a template with candidate signal or image regions after subtracting their local means and normalizing their energies or standard deviations. For a template $t$ and a signal window beginning at location $k$, its standard discrete form is

$$
\operatorname{NCC}(k)=
\frac{
\sum_i (x_{i+k}-\bar{x}_k)(t_i-\bar{t})
}{
\sqrt{\sum_i (x_{i+k}-\bar{x}_k)^2}
\sqrt{\sum_i (t_i-\bar{t})^2}
},
$$

where $\bar{x}_k$ is the mean of the candidate window and $\bar{t}$ is the template mean. The resulting response map is searched for maxima, which represent likely matches. NCC is mathematically a local Pearson correlation coefficient, typically bounded by $[-1,1]$, and is designed to reduce sensitivity to additive offsets and positive multiplicative intensity changes. Its principal limitations are sensitivity to geometric changes, deformation, occlusion, sampling-grid mismatch, locally nonstationary statistics, and windows or templates with zero variance.

## 1. Mathematical formulation and interpretation

Template matching defines an input dataset, a specified template, optionally a search domain, and a matching criterion. In image matching, a template is translated through every feasible position of a source image; at each position, the template-sized image patch is compared with the template. The position producing the maximum response is selected:

$$
(u^\ast,v^\ast)=\arg\max_{u,v}\operatorname{NCC}(u,v).
$$

For an image $f(x,y)$ and a template $t(x,y)$, the local source mean at position $(u,v)$ is

$$
\bar{f}_{u,v}
=
\frac{1}{N}
\sum_{(x,y)\in W_{u,v}}f(x,y),
$$

while the template mean is

$$
\bar{t}
=
\frac{1}{N}
\sum_{(x,y)\in W_T}t(x,y).
$$

The centered quantities are $f-\bar{f}_{u,v}$ and $t-\bar{t}$. Normalization by their $\ell_2$ norms converts the centered patches into unit-length vectors. NCC therefore measures normalized alignment rather than the magnitude of the raw products.

The usual interpretation is:

- $NCC\approx +1$: nearly identical centered intensity patterns;
- $NCC\approx 0$: weak linear similarity;
- $NCC\approx -1$: approximately inverted centered patterns.

A value near $-1$ indicates strong inverse correspondence rather than arbitrary dissimilarity. NCC is undefined when either compared patch has zero variance, because the denominator vanishes. Implementations must therefore handle constant templates and constant source windows specially.

NCC is equivalent to cosine similarity applied after mean subtraction:

$$
\operatorname{NCC}(a,b)
=
\frac{
(a-\bar{a}\mathbf{1})^\mathsf{T}
(b-\bar{b}\mathbf{1})
}{
\|a-\bar{a}\mathbf{1}\|_2
\|b-\bar{b}\mathbf{1}\|_2
}.
$$

This relation distinguishes NCC from ordinary cross-correlation,

$$
C(k)=\sum_i x_{i+k}t_i,
$$

which does not remove means or normalize local energy. Ordinary correlation is affected by amplitude, baseline, local energy, and template norm. NCC addresses these photometric effects but does not inherently solve geometric correspondence.

## 2. Sliding-window computation and invariance

The conventional exhaustive procedure consists of selecting a template, extracting every valid source-image window, computing local source statistics, evaluating NCC, storing the response map, and selecting maxima or threshold-qualified candidates. If the template has $r\times c$ pixels and the source image has $R\times C$ pixels, exhaustive translation evaluates

$$
(R-r+1)(C-c+1)
$$

positions. A detection system may retain every location satisfying

$$
NCC(u,v)\geq \tau,
$$

although no universal threshold is prescribed. Nearby detections may require consolidation.

For an ideal affine photometric transformation

$$
f'(x,y)=a f(x,y)+b,
$$

with $a>0$, mean subtraction removes $b$ and normalization removes $a$. NCC is consequently invariant, under suitable conditions, to global additive brightness changes and positive multiplicative contrast changes. Negative scaling reverses the centered pattern and changes the sign of the correlation.

This invariance is local only to the compared patch. It does not guarantee robustness to spatially varying illumination, nonlinear camera response, clipping, quantization, noise, or geometric misalignment. Basic NCC remains sensitive to scale and rotation because a transformed object no longer occupies corresponding template pixels. It is also limited for deformable objects, substantial occlusion, motion, and ambiguous or repetitive image content.

The computational cost of a direct NCC comparison includes multiplications, additions, a division, and a square root. For an $r\times c$ comparison, one reported operation count is:

- multiplications: $3rc+1$;
- divisions: $1$;
- additions: $3(rc-1)$;
- square-root operations: $1$.

Efficiency can be improved by reusing statistics from neighboring windows, using integral images, restricting the search domain, or using frequency-domain correlation. However, frequency-domain methods do not automatically outperform spatial-domain methods in every practical setting.

## 3. Fast and structured NCC implementations

### Integral-image and FFT computation

For a grayscale source image $f$, summed-area tables provide local window sums in constant time after preprocessing. A second integral image built from $f^2$ provides squared-intensity sums. If

$$
F_{u,v}=\sum_{x,y}f(u+x,v+y)
$$

and

$$
F^{(2)}_{u,v}
=
\sum_{x,y}f(u+x,v+y)^2,
$$

then the centered source-window energy is

$$
\sum_{x,y}(f(u+x,v+y)-\bar{f}_{u,v})^2
=
F^{(2)}_{u,v}
-
\frac{F_{u,v}^2}{WH}.
$$

The numerator can be evaluated as a convolution between the source image and a spatially reversed, zero-mean template. FFT-based NCC combines this correlation with the integral-image statistics. Its asymptotic cost is dominated by

$$
O(MN\log(MN))
$$

for an $M\times N$ source image, with additional approximately $O(MN)$ work for integral-image construction and pointwise operations.

### Segmented normalized cross-correlation

“Template Matching in Images using Segmented Normalized Cross-Correlation” introduces a piecewise-constant template approximation [2502.01286]. The template is recursively divided into axis-aligned rectangular segments until each segment satisfies a standard-deviation condition

$$
\sigma_i<\sigma_{\max}.
$$

Each segment is assigned its original mean intensity. Adjacent segments with equal assigned values are merged. The resulting approximation is represented by a list of rectangular tuples rather than a full pixel grid.

For segment $S_i$ with width $W_i$, height $H_i$, and assigned intensity $k_i$, the approximate numerator is

$$
\operatorname{num}(u,v;f,\kappa)
=
\sum_i
\left[
F_i(u,v)-W_iH_i\bar{f}_{u,v}
\right]
(k_i-\bar{\kappa}),
$$

where $F_i(u,v)$ is the source-image sum over the translated segment. Each $F_i$ is obtained from the source integral image with four table accesses. The approximate template energy is precomputed as

$$
E_\kappa
=
\sum_i W_iH_i(k_i-\bar{\kappa})^2.
$$

Thus, the per-location matching cost is proportional to the number of segments rather than the number of template pixels. The method uses coarse and fine approximations, with reported parameters

$$
\sigma_{\max,\mathrm{fast}}=0.99\sigma_t,
\qquad
\sigma_{\max,\mathrm{slow}}=0.1\sigma_t,
\qquad
K_{\max}=5000.
$$

The coarse approximation rejects positions whose approximate NCC is below $0.9$; surviving positions are evaluated with the fine approximation.

The method is effective for small or visually simple templates, where segmentation produces few rectangles. In reported examples, it was faster than FFT-based NCC while producing maximum-score differences of approximately $0.01$ for several Socket and Split city templates. For visually complex templates, segment counts and preprocessing time increase, while approximation errors can become substantial: reported approximate maximum NCC values fell to $0.75$ and $0.74$ for large Split city templates whose FFT-based maximum was $1.00$. The method does not address rotation or scale changes and inherits NCC’s zero-variance limitations [2502.01286].

### Subsampled circulant correlation

“Fast Template Matching by Subsampled Circulant Matrix” develops a probabilistic acceleration for one-dimensional cyclic matching [1509.04863]. Its stated algorithm uses raw cross-correlation rather than NCC, with

$$
c_k=\sum_{i=0}^{K-1}t_i x_{k+i}.
$$

The signal is periodically aggregated using reduction parameters $M_1$ and $M_2$. Each reduced correlation identifies a residue class of possible locations, and the Chinese Remainder Theorem combines the classes when

$$
M_1M_2>N,
\qquad
M_1\geq K,
\qquad
M_2\geq K,
$$

with $M_1$ and $M_2$ coprime. The reported complexity is

$$
O(N)
$$

additions and

$$
O(K\log K)
$$

multiplications when the reduction parameters are of order $K$.

The method is not an NCC algorithm because it has no local mean subtraction or variance normalization. An NCC adaptation would need source-window sums and squared sums in addition to the correlation numerator. Since the NCC denominator is nonlinear, it cannot generally be recovered exactly from one linear aggregation of grouped correlation values. A practical hybrid would use subsampled raw correlation for candidate generation, reconstruct a small set of candidates, and evaluate exact NCC only at those locations [1509.04863].

## 4. Extensions across representations, dimensions, and motion

NCC can be applied beyond raw grayscale pixels by changing the representation being correlated.

### Multichannel deep feature maps

“Cross-Domain Image Matching with Deep Feature Maps” introduces multi-channel normalized cross-correlation (MCNCC) for CNN feature maps [1804.05305]. For channel $c$, local means and variances are computed separately over the compared spatial support. MCNCC is the average of channelwise NCC values:

$$
\operatorname{MCNCC}(X,Y)
=
\frac{1}{N}
\sum_{c=1}^{N}\operatorname{NCC}(X_c,Y_c).
$$

This per-channel, per-exemplar normalization differs from treating the feature map as one jointly normalized volume. It reduces sensitivity to unequal channel magnitudes and domain-dependent activation statistics. The paper reports that MCNCC improved retrieval over raw correlation, joint normalization, cosine similarity, and Euclidean distance. In the FID-300 shoeprint benchmark, unlearned MCNCC achieved top-1% and top-5% accuracies of $72.67\%$ and $82.33\%$, while the fine-tuned learned model achieved $79.67\%$ and $86.33\%$ [1804.05305].

The learned variant adds domain-specific projections and channel weights, optimized with a Siamese hinge-loss objective. The CNN feature extractor remains distinct from the matching rule: the network produces feature maps, while MCNCC performs the normalized comparison.

### Orientation-score and roto-translation matching

“Template Matching via Densities on the Roto-Translation Group” applies correlation to orientation-score representations [1603.03304]. An image is lifted to

$$
U_f:\mathbb{R}^2\rtimes S^1\rightarrow\mathbb{C},
$$

using a wavelet-type transform. The modulus $|U_f|$ supplies phase-invariant orientation evidence. Templates are defined on the roto-translation group

$$
SE(2)=\mathbb{R}^2\rtimes S^1,
$$

and detection correlates a three-dimensional template—two spatial dimensions and orientation—with the orientation-score volume.

The supplementary material gives a weighted, locally centered and variance-normalized generalized NCC on $\mathbb{R}^2$ and $SE(2)$. The main experiments, however, use unnormalized correlation after local intensity preprocessing because exact normalized correlation was considered computationally expensive. The reported detector combines spatial intensity templates with $SE(2)$ orientation templates and uses B-spline regression, logistic or linear objectives, and left-invariant geometric regularization.

The paper reports success rates of $99.83\%$ for optic nerve head detection on 1737 images, $99.32\%$ for fovea detection on 1616 images, and $95.86\%$ for pupil detection on 1521 images. These results concern the complete representation-learning and correlation-based detector, not classical raw-intensity NCC alone [1603.03304].

### Spatial-temporal correlation

“Spatio-temporal normalized cross-correlation for estimation of the displacement field in ultrasound elastography” extends normalized correlation from a spatial window to a spatial-temporal box [1804.05305]. If $A_l(j)$ and $B_l(j)$ are corresponding samples in frame $l$, STNCC is

$$
\operatorname{STNCC}(A,B)
=
\frac{
\sum_{l=1}^{n}\sum_{j=1}^{W}A_l(j)B_l(j)
}{
\sqrt{\sum_{l=1}^{n}\sum_{j=1}^{W}A_l(j)^2}
\sqrt{\sum_{l=1}^{n}\sum_{j=1}^{W}B_l(j)^2}
}.
$$

The reported formulation does not subtract local means; it is an energy-normalized inner product over $nW$ samples. The displacement remains two-dimensional, while the temporal dimension supplies additional evidence. The method assumes approximately constant displacement throughout the spatial-temporal box.

The experiments use seven frames. In simulations, STNCC produced SNR and CNR values of $132.50$ and $11.59$ at noise amplitude $0.3$, compared with $39.00$ and $6.91$ for conventional NCC. At noise amplitude $0.7$, NCC failed while STNCC produced SNR $15.33$ and CNR $4.62$. Phantom and in-vivo experiments similarly reported improved SNR and CNR, although larger temporal support can oversmooth displacement transitions when the constant-displacement assumption fails [1804.05305].

### Rotation-aware tensor matching

“Fast Normalized Cross-Correlation for Template Matching with Rotations” integrates rotated templates into a symmetric tensor [2311.07561]. Rather than computing one FFT-based correlation for every sampled orientation, it constructs tensor-valued correlation maps. For tensor order $n$ and quaternion dimension $d'=4$, the number of independent components is

$$
\binom{n+d'-1}{n}.
$$

For $n=4$, this is

$$
\binom{7}{4}=35.
$$

The orientation estimate is recovered from a dominant tensor $Z$-eigenvector. The method is motivated by the large number of rotations required for three-dimensional matching, where sampled orientation counts are reported as $7112$, $45123$, and $553680$ for approximate angular accuracies of $13^\circ$, $7^\circ$, and $3^\circ$. The corresponding potential reductions relative to 35 tensor components are approximately $203$, $1239$, and $184560$.

The tensor construction begins with centering and normalization under an operator $S$, but the proof introduces a related operator $S'$. Consequently, the tensor score is not necessarily bounded by $[-1,1]$ in the same way as classical NCC. The method is therefore a rotation-aware correlation construction with an important normalization caveat rather than a direct textbook NCC implementation [2311.07561].

## 5. Optimization, learning, and robustification

### Least-squares NCC

“Least Squares Normalized Cross Correlation” rewrites NCC as a least-squares problem [1810.04320]. Define

$$
\mathcal{N}(a)
=
\frac{a-\mu_a\mathbf{1}}{\sigma_a},
\qquad
\sigma_a=\|a-\mu_a\mathbf{1}\|.
$$

Then

$$
\operatorname{NCC}(a,b)
=
\mathcal{N}(a)^\mathsf{T}\mathcal{N}(b),
$$

and

$$
\operatorname{ZNSSD}(a,b)
=
\|\mathcal{N}(a)-\mathcal{N}(b)\|^2
=
2-2\operatorname{NCC}(a,b).
$$

Maximizing NCC is therefore exactly equivalent to minimizing zero-mean normalized SSD, including proportional gradients. This allows NCC to be optimized with Gauss–Newton, inverse-compositional, or ESM updates rather than exhaustive translation search.

The central technical result is the exact normalization Jacobian:

$$
\frac{\partial\mathcal{N}(a)}{\partial a}
=
\frac{
\mathbb{I}-\mathcal{N}(a)\mathcal{N}(a)^\mathsf{T}
}{
\sigma_a
}
\left(
\mathbb{I}
-
\frac{\mathbf{1}\mathbf{1}^\mathsf{T}}{M}
\right).
$$

The derivative accounts for changes in both the local mean and local norm. Its efficient implementation uses rank-one operations and reduces the cost from $O(M^2)$ to $O(M)$.

The method can use multiple local patches, each normalized independently. This permits separate affine photometric variation in different regions. For occlusion robustness, patch-level Geman–McClure weighting is used:

$$
\rho(s)=\frac{s}{s+\tau^2},
\qquad \tau=0.5.
$$

The paper deliberately robustifies complete normalized patches rather than individual pixels, because pixelwise outliers contaminate the mean and variance of their entire patch. Sparse oriented edgelet patches further reduce computation. In the reported Graffiti2 experiments, local normalization and robustification improved convergence under illumination changes and simulated occlusion, while robust sparse variants provided substantial speed reductions [1810.04320].

### Learned preprocessing followed by NCC

“Deep Learning Improves Template Matching by Normalized Cross Correlation” retains NCC as the final matching mechanism but learns a Siamese convolutional preprocessing transformation [1705.08593]. If $\psi_\theta$ is the shared transformation,

$$
C_\theta(u)
=
\operatorname{NCC}
\left(
\psi_\theta(T),
\psi_\theta(I)_u
\right).
$$

The training objective maximizes the difference between the primary and secondary correlation peaks. A $20$-pixel exclusion window is used during training. Negative template-source pairs are also trained to have low maximum NCC. The resulting system uses a FusionNet architecture, an FFT-based NCC layer, and weak supervision in which the true match location is not supplied.

On serial electron-microscopy images, the learned preprocessing reduced false matches by approximately $2$–$7$ times relative to a tuned Gaussian bandpass baseline. For adjacent sections with 224-pixel templates, false matches fell from $160$ for bandpass preprocessing to $69$ for the convnet. For across-section matching with 160-pixel templates, false matches fell from $1504$ to $227$ [1705.08593].

The learned representation does not replace the interpretable NCC response. Peak height and peak separation remain confidence-like measures. The method can fail when a template contains few of the learned distinctive structures, such as templates dominated by cell bodies. Transfer to substantially different imaging domains is not guaranteed [1705.08593].

### Continuous template matching with NCC-derived costs

“A Neural Template Matching Method to Detect Knee Joint Areas” formulates bilateral knee localization as continuous optimization of a negative-NCC cost [2209.11791]. For mean-centered patches $\mathbf{u}$ and $\mathbf{v}$,

$$
c^{gl}(u,v)
=
1-
\frac{
\widetilde{\mathbf{u}}^\mathsf{T}\widetilde{\mathbf{v}}
}{
\|\widetilde{\mathbf{u}}\|
\|\widetilde{\mathbf{v}}\|
}.
$$

The method also evaluates two subwindow costs and combines them as

$$
\widetilde{c}(u,v)
=
\frac{1}{2}
\left(
c^{gl}(u,v)
+
\max\{c^r(u,v),c^g(u,v)\}
\right).
$$

The maximum subwindow cost prevents a good match in one region from fully compensating for a poor match in the other. Candidate patches are generated by differentiable zoom, translation, and mild rotation. A Siamese ResNet-18-based optimizer predicts continuous transformation parameters, while a second Adam-based sharpening stage refines them.

On 400 test images, mean combined losses were $0.221$ and $0.249$ for sliding-window matching on OAI and MOST, compared with $0.141$ and $0.157$ for neural matching followed by sharpening. The method uses one manually annotated side of a single bilateral image and relies on bilateral scale and vertical-position regularization [2209.11791].

## 6. Applications, alternatives, and failure modes

NCC has been used for image registration, object detection, visual tracking, stereo and motion estimation, medical image analysis, spectroscopy, detector calibration, and signal alignment. Its suitability depends on whether pixelwise or featurewise correspondence is meaningful.

In medical imaging, reviewed applications include mammogram positioning and breast symmetry, resting-state fMRI component matching, and general image registration. NCC can be combined with SSD, Dice coefficients, invariant features, deformable models, active contours, segmentation, and decision-making systems [1610.07231].

In spectroscopic radial-velocity extraction, template matching is closely related to correlation but need not use NCC explicitly. “A novel framework for semi-Bayesian radial velocities through template matching” uses a noise-weighted $\chi^2$ method and S-BART, a likelihood over a common radial-velocity shift across spectral orders [2205.00067]. In a simplified homoscedastic, fixed-continuum limit, maximizing the likelihood becomes equivalent to maximizing an unnormalized cross-correlation. NCC is recovered only after centering and energy normalization. S-BART additionally models pixel-dependent variance, template uncertainty, continuum nuisance parameters, and a joint posterior.

For Compton-edge calibration, “The Automatic Calibration Method of the Compton Edge Based on Normalized Cross-correlation and Simulated Annealing Algorithm” uses a Pearson-type NCC to select a measured spectral interval resembling a theoretical plateau-to-edge template [2507.16282]. The template is sampled at 100 points, candidate measured intervals are interpolated to the same length, and the interval with maximum NCC is selected before Gaussian-broadened response fitting and simulated annealing. The method is intended to reduce sensitivity to low count rates, spectral overlap, and subjective interval selection. Its reproducibility is limited by unspecified candidate-window lengths, interpolation details, background treatment, and the precise simulated-annealing objective.

NCC is also used as a morphology-confidence measure in ballistocardiogram heartbeat detection. “Confidence analysis-based hybrid heartbeat detection for ballistocardiogram using template matching and deep learning” averages normalized correlations between detected heartbeat episodes and a dynamic template [2512.22926]. The primary template-matching detector additionally uses dynamic time warping, so it is not a bare sliding NCC algorithm. In the hybrid system, morphology confidence is combined with normalized interval variability to select between template matching and deep learning. The reported hybrid average absolute interval error was $20.73$ ms, compared with $50.01$ ms for template matching alone and $30.86$ ms for deep learning alone [2512.22926].

Several studies emphasize that ordinary correlation and NCC should not be conflated. “Kunchenko's Polynomials for Template Matching” compares a Kunchenko-polynomial procedure with cross-correlation and SSD on synthetic one-dimensional Gaussian signals, but does not establish an NCC baseline [1107.2085]. “Comparing Cross Correlation-Based Similarities” studies unnormalized cross-correlation and nonlinear Jaccard and coincidence correlations, not standard NCC [2111.08513]. “A Counterexample in Cross-Correlation Template Matching” gives a counterexample to ordinary unnormalized correlation under sampling-grid mismatch and noise, but does not determine whether NCC succeeds or fails on the same construction [2410.19085]. “Robust Visual Tracking Revisited: From Correlation Filter to Template Matching” contrasts dense correlation with reciprocal-nearest-neighbor patch similarity, but does not provide a controlled NCC-versus-MBS experiment [1904.06842].

The principal NCC failure modes are:

- **Geometric variation**: scale, rotation, translation beyond the search model, and deformation disrupt pixelwise correspondence.
- **Occlusion and clutter**: a corrupted region can dominate or distort the score unless local or robust formulations are used.
- **Repeated structures**: secondary peaks may be large and ambiguous.
- **Nonuniform illumination**: one global gain and bias do not model spatially varying photometric changes.
- **Sampling and segmentation mismatch**: NCC may improve energy comparability without resolving unequal sample counts, unknown boundaries, or discontinuity misalignment.
- **Uniform regions**: zero variance makes the score undefined.
- **Representation mismatch**: raw intensity NCC may be less informative than feature-space, orientation-space, or multichannel matching.
- **Computational scale**: exhaustive searches over large images, many transformations, or high-dimensional parameter spaces can be expensive.

Accordingly, NCC is often used as one component of a larger system. Deep feature extraction, geometric representations, local normalization, sparse sampling, temporal aggregation, continuous optimization, candidate generation, robust weighting, and learned preprocessing each address limitations that are not removed by classical photometric normalization alone.

Source: https://www.emergentmind.com/topics/normalized-cross-correlation-template-matching