OpenCV
3.0.0-rc1
Open Source Computer Vision
|
In this tutorial you will learn how to:
Template matching is a technique for finding areas of an image that match (are similar) to a template image (patch).
We need two primary components:
our goal is to detect the highest matching area:
To identify the matching area, we have to compare the template image against the source image by sliding it:
For each location of T over I, you store the metric in the result matrix **(R)**. Each location \((x,y)\) in R contains the match metric:
the image above is the result R of sliding the patch with a metric TM_CCORR_NORMED. The brightest locations indicate the highest matches. As you can see, the location marked by the red circle is probably the one with the highest value, so that location (the rectangle formed by that point as a corner and width and height equal to the patch image) is considered the match.
Good question. OpenCV implements Template matching in the function cv::matchTemplate . The available methods are 6:
method=CV_TM_SQDIFF
\[R(x,y)= \sum _{x',y'} (T(x',y')-I(x+x',y+y'))^2\]
method=CV_TM_SQDIFF_NORMED
\[R(x,y)= \frac{\sum_{x',y'} (T(x',y')-I(x+x',y+y'))^2}{\sqrt{\sum_{x',y'}T(x',y')^2 \cdot \sum_{x',y'} I(x+x',y+y')^2}}\]
method=CV_TM_CCORR
\[R(x,y)= \sum _{x',y'} (T(x',y') \cdot I(x+x',y+y'))\]
method=CV_TM_CCORR_NORMED
\[R(x,y)= \frac{\sum_{x',y'} (T(x',y') \cdot I(x+x',y+y'))}{\sqrt{\sum_{x',y'}T(x',y')^2 \cdot \sum_{x',y'} I(x+x',y+y')^2}}\]
method=CV_TM_CCOEFF
\[R(x,y)= \sum _{x',y'} (T'(x',y') \cdot I'(x+x',y+y'))\]
where
\[\begin{array}{l} T'(x',y')=T(x',y') - 1/(w \cdot h) \cdot \sum _{x'',y''} T(x'',y'') \\ I'(x+x',y+y')=I(x+x',y+y') - 1/(w \cdot h) \cdot \sum _{x'',y''} I(x+x'',y+y'') \end{array}\]
method=CV_TM_CCOEFF_NORMED
\[R(x,y)= \frac{ \sum_{x',y'} (T'(x',y') \cdot I'(x+x',y+y')) }{ \sqrt{\sum_{x',y'}T'(x',y')^2 \cdot \sum_{x',y'} I'(x+x',y+y')^2} }\]
Testing our program with an input image such as:
and a template image:
The right match is shown below (black rectangle around the face of the guy at the right). Notice that CCORR and CCDEFF gave erroneous best matches, however their normalized version did it right, this may be due to the fact that we are only considering the "highest match" and not the other possible high matches.