Author: Steven Zhai
Copyright Notice: The copyright belongs to the author. For commercial reprints, please contact the author for authorization. For non-commercial reprints, please indicate the source
function prototype
void matchTemplate( InputArray image, InputArray templ,OutputArray result, int method, InputArray mask = noArray());
Parameter Description
- Image of type InputArray, input image.
- templ of type InputArray, the image to be matched.
- A result of type OutputArray, which outputs the matching result.
- Int type method, matching method, see below for details.
- Mask of type InputArray, mask.
Introduction to matching methods
The template matching function has 6 matching methods. It will be found that if the original image is 1000*1000 and the template is 100*100, the resulting image size is 900*900. The formulas and principles corresponding to each method are as follows.
1.CV_TM_SQDIFF, square difference matching method. The smaller the value obtained, the better the match.
2. CV_TM_SQDIFF_NORMED, normalized squared difference matching method. The smaller the value obtained, the better the match.
3.CV_TM_CCORR, correlation matching method. The higher the value obtained, the better the match. This method is susceptible to background interference.
4. CV_TM_CCORR_NORMED, normalized correlation matching method. The higher the value obtained, the better the match. This method is susceptible to background interference.
5. CV_TM_CCOEFF, the correlation coefficient method, is also a zero-mean cross-correlation method. After subtracting the mean, the correlation is calculated. The higher the value obtained, the better the match. This method has better applicability.
6. CV_TM_CCOEFF_NORMED, normalized correlation coefficient method. The higher the value obtained, the better the match. This method has better applicability.
test code
#include <iostream>
#include <opencv2\opencv.hpp>
#include <opencv2/highgui/highgui.hpp>
using namespace cv;
using namespace std;
int main()
{
cv::Mat src = imread("test1.jpg");
cv::Mat sample = imread("t.png");
// 匹配
cv::Mat result;
matchTemplate(src, sample, result, CV_TM_CCOEFF);
// 归一化
normalize(result, result, 0, 1, NORM_MINMAX, -1, Mat());
// 获取最小值
double minValue; double maxValue; Point minLocation; Point maxLocation;
Point matchLocation;
minMaxLoc(result, &minValue, &maxValue, &minLocation, &maxLocation, Mat());
matchLocation = maxLocation;
// 框选结果
cv::Mat draw = src.clone();
rectangle(draw, matchLocation, Point(matchLocation.x + sample.cols, matchLocation.y + sample.rows), Scalar(255, 0, 0), 2, 8, 0);
imshow("src", src);
imshow("sample", sample);
imshow("draw", draw);
waitKey(0);
return 0;
}
Test effect
If the article helps you, you can give me a like and let me know, I will be very happy~ Come on!