Template matching is a technique for finding areas of an image that are similar to a patch (template).
Its application may be robotics or manufacturing.
A patch is a small image with certain features. The goal of template matching is to find the patch/template in an image.
To find them we need both:
- Source Image (S) : The space to find the matches in
- Template Image (T) : The template image
The template image T is slided over the source image S (moved over the source image), and the program tries to find matches using statistics.
Template matching example
Lets have a look at the code:
import numpy as np
First we load both the source image and template image with imread(). We resize themand convert them to grayscale for faster detection:
We use the cv2.matchTemplate(image,template,method) method to find the most similar area in the image. The third argument is the statistical method.
This method has six matching methods: CV_TM_SQDIFF, CV_TM_SQDIFF_NORMED, CV_TM_CCORR, CV_TM_CCORR_NORMED, CV_TM_CCOEFF and CV_TM_CCOEFF_NORMED.
which are simply different statistical comparison methods
Finally, we get the rectangle variables and display the image.
Template matching is not scale invariant nor is it rotation invariant. It is a very basic and straightforward method where we find the most correlating area. Thus, this method of object detection depends on the kind of application you want to build. For non scale and rotation changing input, this method works great.