PIXELBANKv9.1.0
Menu

Normalized Cross-Correlation

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:

Identical arrays have perfect correlation.

  1. Compute means: T_mean = (1+2+3+4)/4 = 2.5 P_mean = (1+2+3+4)/4 = 2.5

  2. Compute centered values: T - T_mean: [-1.5, -0.5, 0.5, 1.5] P - P_mean: [-1.5, -0.5, 0.5, 1.5]

  3. Numerator: sum of products = (-1.5)×(-1.5) + (-0.5)×(-0.5) + 0.5×0.5 + 1.5×1.5 = 2.25 + 0.25 + 0.25 + 2.25 = 5.0

  4. Denominator: sqrt(var_T × var_P) var_T = var_P = 5.0 denom = sqrt(5.0 × 5.0) = 5.0

  5. NCC = 5.0 / 5.0 = 1.0

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
solution.py

Test Results

0/0
Run code to see test results.
Normalized Cross-Correlation - Medium | PixelBank