v9.1.1
Menu

Normalized Cross-Correlation

mediumFREEObject TrackingTrackingCV: Motion Estimation

You are given a template and an image patch and need to compute their normalized cross-correlation (NCC).

NCC measures similarity between a template and a patch, normalized for brightness and contrast:

NCC=∑i(Ti−Tˉ)(Pi−Pˉ)∑i(Ti−Tˉ)2⋅∑i(Pi−Pˉ)2NCC = \frac{\sum_i (T_i - \bar{T})(P_i - \bar{P})}{\sqrt{\sum_i (T_i - \bar{T})^2 \cdot \sum_i (P_i - \bar{P})^2}}

Where:

  • TiT_i are template pixel values, Tˉ\bar{T} is template mean
  • PiP_i are patch pixel values, Pˉ\bar{P} is patch mean

NCC ranges from -1 (inverse correlation) to +1 (perfect match).

Example

Input
template = [[1, 2], [3, 4]]
patch = [[1, 2], [3, 4]]
Output
1.0
Reasoning
  • Inputs: template and patch are both 2×22 \times 2 grids of pixel intensities, here identical: 1,2,3,41, 2, 3, 4. Only corresponding positions are compared, so treat each grid as four paired values (Ti,Pi)(T_i, P_i).
  • Means: Tˉ=Pˉ=1+2+3+44=2.5\bar{T} = \bar{P} = \frac{1+2+3+4}{4} = 2.5. Subtracting them removes overall brightness, leaving deviations −1.5,−0.5,0.5,1.5-1.5, -0.5, 0.5, 1.5 for both grids.
  • Numerator: the deviations multiply pairwise to 2.25,0.25,0.25,2.252.25, 0.25, 0.25, 2.25, which add up to 55.
  • Denominator: each grid's squared deviations also sum to 55, so the scale is 5⋅5=5\sqrt{5 \cdot 5} = 5.
  • Output: 55\frac{5}{5} gives 1.0, a perfect match.
  • Notice: NCC ignores brightness and contrast. A patch of 12,14,16,1812, 14, 16, 18 (that is, 2T+102T + 10) still scores 1.01.0. Reversing the order to 4,3,2,14, 3, 2, 1 flips every product's sign and scores −1.0-1.0. A flat grid has zero spread, so the score falls back to 0.00.0 by definition.

Constraints

  • template and patch are 2D arrays of same size
  • Return NCC score rounded to 4 decimal places
  • If either has zero variance, return 0.0

More from CV: Motion Estimation

solution.py

Test results

Sign in to run your code against the test cases.