PIXELBANKv9.1.0
Menu

Template Matching Best Location

Implement a template matching algorithm to find the best location of a given template within a search image using Normalized Cross-Correlation (NCC). This involves sliding the template across the search region and computing similarity at each position.

The concept of template matching is crucial in object tracking, as it enables the location of an object to be determined between frames. The NCC measure is used to quantify the similarity between the template and the search image at each position, providing a score that indicates the degree of match.

Here are the steps to follow:

  1. Slide the template across the search image, considering each possible position.
  2. At each position, extract the corresponding patch from the search image.
  3. Compute the NCC between the template and the extracted patch.
NCC=βˆ‘i=1n(tiβˆ’tΛ‰)(piβˆ’pΛ‰)βˆ‘i=1n(tiβˆ’tΛ‰)2βˆ‘i=1n(piβˆ’pΛ‰)2NCC = \frac{\sum_{i=1}^{n}(t_i - \bar{t})(p_i - \bar{p})}{\sqrt{\sum_{i=1}^{n}(t_i - \bar{t})^2 \sum_{i=1}^{n}(p_i - \bar{p})^2}}

This technique is widely used in video surveillance systems to track objects across frames.

Example:

Input:
image = [[0,0,0,0],
        [0,1,2,0],
        [0,3,4,0],
        [0,0,0,0]]
template = [[1,2],[3,4]]
Output:
(1, 1)
Reasoning:

Sliding template across valid positions:

  • Position (0,0): patch=[[0,0],[0,1]] β†’ NCC with [[1,2],[3,4]] = low
  • Position (0,1): patch=[[0,0],[1,2]] β†’ partial match
  • Position (0,2): patch=[[0,0],[2,0]] β†’ low
  • Position (1,0): patch=[[0,1],[0,3]] β†’ partial match
  • Position (1,1): patch=[[1,2],[3,4]] β†’ EXACT MATCH, NCC = 1.0
  • Position (1,2): patch=[[2,0],[4,0]] β†’ partial match
  • Position (2,0): patch=[[0,3],[0,0]] β†’ low
  • Position (2,1): patch=[[3,4],[0,0]] β†’ partial match
  • Position (2,2): patch=[[4,0],[0,0]] β†’ low

Best match at (1,1) with NCC = 1.0

Constraints:

  • image: 2D search region (larger than template)
  • template: 2D template to find
  • Return best (row, col) location (top-left corner of match)
  • If multiple positions tie, return the first one found
πŸ”’

Editor locked

The code editor is locked for Pro problems. It is only available for free problems. Please upgrade to gain access to the code editor for all problems.

solution.py

Test Results

0/0
Run code to see test results.
Template Matching Best Location - Medium | PixelBank