Computer Engineering is coming soon

We're still writing and reviewing the notes for every subject, and we'll open it when every subject is ready. Meanwhile you can practise aptitude, ask Aria about any subject, or see the branches that are ready.

Template matching and dynamic programming

Template matching finds where a small pattern (template) appears in a larger signal or image; dynamic programming gives exact, efficient methods for sequence and deformable alignments such as edit distance and Dynamic Time Warping (DTW).

Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.

Why it matters

Template matching is used when you need to locate or recognise a known pattern (shape, patch, short signal) inside a larger image or time-series — for example locating a logo in an image, finding a known phoneme pattern in speech, or matching a handwritten digit to a stored prototype. Dynamic programming is the main tool engineers use when matching sequences or deformable templates where positions are not one-to-one: it gives optimal alignments for edit distance, Dynamic Time Warping (DTW) and many deformable-model problems under clear cost models.

Key ideas

Start from first principles and definitions. Define every term before using it.

  • Template: a small pattern (array of pixel intensities or a short sequence) used as the reference to find matching occurrences inside a larger signal or image. Usually denoted T. Unit: intensity units of sensor (often unitless).

  • Image patch / search window: the part of the large image or signal compared to the template at one candidate location. Denoted I_x (I at location x).

  • Template matching: the process of computing a matching score (higher-is-better) or a matching distance (lower-is-better) between T and I_x for every candidate location x; then selecting locations with best score/distance.

  • Sliding-window search: try all possible alignments of T inside the image by moving a rectangular window; compute the matching score at each position. Diagram to draw for exam: a large rectangle labelled “image I”, a small rectangle inside labelled “template window T”, an arrow showing the window sliding step-by-step horizontally and vertically; label one sample position x.

  • Cross-correlation (unnormalised): For discrete 2D signals, the cross-correlation at offset (u,v) is the sum of products between image patch and template. Assumes brightness linearity (intensities multiply meaningfully) and that image and template sizes match at the position.

  • Normalized cross-correlation (NCC): removes sensitivity to affine changes in brightness (mean and contrast) by subtracting patch and template means and dividing by their norms. NCC ranges between -1 and 1; value 1 means perfect linear match. It is undefined if either patch or the template has zero variance (zero norm); implementers must guard against division by zero.

  • Sum of squared differences (SSD) and Sum of absolute differences (SAD): measure dissimilarity; SSD is sensitive to brightness offset and scale. SSD can be related algebraically to cross-correlation — an identity often used to compute many SSD scores efficiently.

  • Algebraic identity used in derivations: SSD(I_x, T) = sum(I_x^2) + sum(T^2) - 2 · cross_corr(I_x, T). This expresses SSD using cross-correlation and two sums that can be computed efficiently (e.g., with integral images for sums of I and I^2).

  • Dynamic programming (DP): a method to solve optimisation problems that have overlapping subproblems and optimal substructure. In sequence/template matching, DP computes optimal alignments by filling a cost matrix where each cell stores the optimal cost up to that point.

  • Edit distance (Levenshtein distance): the minimum number of insertions, deletions and substitutions required to transform one discrete sequence (e.g., a string of symbols) into another. The DP recurrence is exact and runs in O(n·m) time for sequences of lengths n and m.

  • Dynamic Time Warping (DTW): computes an optimal alignment (warping) between two real-valued sequences by allowing non-linear time-warping (repeating or skipping elements). DTW enforces continuity and monotonicity constraints on the warping path and minimises accumulated local distances (usually squared or absolute difference). The DP recurrence is identical in form to edit-distance DP except costs are real-valued and operations correspond to step choices along the path.

  • DP path constraints to draw in a diagram: an n-by-m grid where rows index sequence A and columns index sequence B. The optimal path starts at (1,1) and ends at (n,m). Show allowed moves: right (insert), down (delete), diagonal (match/substitute). Label monotonicity (indices never decrease) and continuity (steps of size at most 1 in each axis).

Assumptions behind each method: brightness constancy for correlation-based methods (unless you normalise), i.i.d. zero-mean Gaussian noise often assumed when deriving SSD as an MLE, and that cost-additivity and local decisions lead to global optimum (DP requires optimal substructure which holds for edit distance and DTW under standard definitions).

Derivations commonly asked in exams:

  • Derive SSD identity from algebra: expand sum(I - T)^2 and group terms to show the SSD = sum(I^2) + sum(T^2) - 2·sum(I·T). This leads to fast computation via precomputed sums.
  • Derive NCC formula: subtract means and divide by norms; show that if one patch is an affine-scaled version of the other, NCC = ±1.
  • Derive the DP recurrence for edit distance and DTW from optimal substructure: the best alignment up to (i,j) uses the best of the three predecessor cells plus the local cost.

Formulas

cross_corr(u,v) = Σ_{i,j} I(i+u, j+v) · T(i,j) — I and T intensities (unitless), sum over template indices; applies when template is fully inside image at offset (u,v).

SSD(u,v) = Σ_{i,j} (I(i+u,j+v) - T(i,j))^2 — SSD (unit: intensity^2), lower is better; applies for equal-size patches.

SSD = Σ I^2 + Σ T^2 - 2·Σ(I·T) — Σ over template support; symbols unitless or intensity^2; used to compute SSD from correlation and precomputed sums.

NCC(u,v) = Σ_{i,j} [I'(i+u,j+v) · T'(i,j)] / (‖I'_{patch}‖ · ‖T'‖) — I' and T' denote zero-mean patches (subtract means); NCC is unitless and in [-1,1]; applies when you want brightness-invariant matching. Undefined when any denominator is zero (flat patch/template); handle this case explicitly.

Levenshtein D(i,j) = min{ D(i-1,j) + 1, D(i,j-1) + 1, D(i-1,j-1) + cost_sub } with base D(0,0)=0, D(i,0)=i, D(0,j)=j. cost_sub = 0 if symbol_i == symbol_j else 1. D unitless (count of edits).

DTW(i,j) = d(i,j) + min{ DTW(i-1,j), DTW(i,j-1), DTW(i-1,j-1) } with appropriate boundary initialization. Common initializations: set D(1,1)=d(1,1) and fill the first row/column by cumulative sums using only right/down moves, or equivalently set D(0,0)=0 and D(0,j)=D(i,0)=+∞. d(i,j) = local distance (e.g., (x_i - y_j)^2). DTW cost unit depends on d (often squared amplitude units).

Note: all sums are discrete sums over template indices or sequence indices; units are image intensity (unitless) or intensity^2 for squared sums.

Worked examples

Example 1 — 2×2 template matching using NCC and SSD (numerical step-by-step) Template T = [[1,2],[3,4]] (unit: intensity), patch I = [[2,3],[4,5]]. Compute SSD and NCC at this location. Step 1: list T and I as vectors T = [1,2,3,4], I = [2,3,4,5]. Step 2: compute SSD = Σ (I_k - T_k)^2 = (2-1)^2 + (3-2)^2 + (4-3)^2 + (5-4)^2 = 1+1+1+1 = 4. -> SSD = 4 (intensity^2). Step 3: compute means μ_T = (1+2+3+4)/4 = 2.5, μ_I = (2+3+4+5)/4 = 3.5. Step 4: zero-mean vectors T' = [-1.5,-0.5,0.5,1.5], I' = [-1.5,-0.5,0.5,1.5]. Step 5: dot product Σ T'_k·I'_k = 2.25+0.25+0.25+2.25 = 5.0. Step 6: norms ‖T'‖ = sqrt(5.0) and ‖I'‖ = sqrt(5.0). Step 7: NCC = 5.0 / (sqrt(5)·sqrt(5)) = 1.0. -> NCC = 1.0 (perfect match).

Example 2 — DTW between two sequences (numerical DP) Let X = [1,2,3,4], Y = [1,2,3]. Use squared difference d(i,j) = (x_i - y_j)^2. Compute local distance matrix d (rows i=1..4, cols j=1..3): row1: [0,1,4] row2: [1,0,1] row3: [4,1,0] row4: [9,4,1] DP initialization and filling (D is cumulative): D(1,1)=0 D(1,2)=0+1=1 D(1,3)=1+4=5 D(2,1)=0+1=1 D(2,2)=0+min(1,1,0)=0 D(2,3)=1+min(5,0,1)=1 D(3,1)=1+4=5 D(3,2)=1+min(0,5,1)=1 D(3,3)=0+min(1,1,0)=0 D(4,1)=5+9=14 D(4,2)=4+min(1,14,5)=5 D(4,3)=1+min(0,5,1)=1 Final DTW cost D(4,3) = 1 (units: squared amplitude). Optimal warping path example: (1,1) → (2,2) → (3,3) → (4,3).

Example 3 — Levenshtein edit distance (theory + steps) Compute distance between "kitten" and "sitting". Known minimal edits: kitten → sitten (substitute k→s) sitten → sittin (substitute e→i) sittin → sitting (insert g at end) Total edits = 3 → Levenshtein distance = 3. (DP table can be filled to show minimal cost.)

Common mistakes

  • Off-by-one indexing or wrong base cases when implementing DP; always set D(0,0) and row/column boundaries explicitly.
  • Using Euclidean distance vs squared distance inconsistently in DTW without adjusting interpretation (squared distances penalise large errors more).
  • Not enforcing monotonicity/continuity constraints for DTW leading to infeasible paths.
  • Confusing convolution and cross-correlation sign conventions (correlation does not flip the template; convolution flips kernel indices).

For your exam

Types of questions that appear: definitions (what is NCC, SSD, DTW), short notes (compare SSD vs NCC), derivations (derive SSD identity, derive DTW recurrence), numericals (compute SSD/NCC for a small patch or compute DTW / edit distance for short sequences), programs (implement DP for edit distance or DTW), and diagrams (draw sliding-window and DP cost matrix with path).

What to include for full marks:

  • For definitions: give the formal formula, the assumptions, and mention units and when the method applies.
  • For derivations: show algebra steps (e.g., expand Σ(I-T)^2), explain boundary conditions for DP, and name the optimal substructure property used.
  • For numericals: show the filled table or matrix, show intermediate partial sums, label axes clearly, carry units and give the final answer bolded.
  • For programs: present clear code, explain initialization and indexing, and give sample I/O. State time and space complexity (e.g., O(n·m)).

Quick check

  1. Write the algebraic identity that expresses SSD using cross-correlation.
  2. What are the three predecessor moves allowed in the standard DP for DTW or edit distance?
  3. What range of values can normalized cross-correlation (NCC) take, and what value indicates perfect match?

Answers: 1) SSD = Σ I^2 + Σ T^2 - 2·Σ(I·T). 2) Right (i,j-1), Down (i-1,j), Diagonal (i-1,j-1). 3) NCC in [-1,1]; NCC = 1 is perfect match.

Finished this topic? Mark it so your progress, study plan and readiness keep up.

Stuck on something here?