Template matching is a method for finding the best matched location of a template image inside a larger image. We use the normalized cross-corrleation to compute the best match.
The following is an example showing a source image on the left with the template image in the middle. The matched score of output image is shown in the right.
Input
Template
Output score converted to U8
Implementation
The algorithm computes the normalized cross correlation (score) for every possible location of the template inside the source image. The location with the highest score is chosen as the best matching location between source and template image.
where:
\(T(x\prime, y\prime)\) refers to the template image.
\(I(x+x\prime, y+y\prime)\) refers to the source image.
\(M(x\prime, y\prime)\) refers to the mask.
\(x\prime\) and \(y\prime\) are the pixel coordinates inside the template image.
If the source image has a resolution W \(\times\) H and template image w \(\times\) h, then the output image has a resolution (W - w + 1) \(\times\) (H - h + 1). If the template exceeds a size of 400 pixels, the convolution will be computed in Fourier space, otherwise in original space.
C API functions
For list of limitations, constraints and backends that implements the algorithm, consult reference documentation of the following functions:
Briechle, K., & Hanebeck, U. D. (2001, March). Template matching using fast normalized cross correlation. In Optical Pattern Recognition XII (Vol. 4387, pp. 95-102). SPIE.
Chen, C. S., Huang, C. L., Yeh, C. W., & Chang, W. C. (2016). An accelerating CPU based correlation-based image alignment for real-time automatic optical inspection. Computers & Electrical Engineering, 49, 207-220.