您的问题可能是,模板匹配不是比例不变的,您的模板大小不适合对象大小。
使用此输入和代码,我得到该输出:
输入图像:

输入模板:

代码:基本上取自opencv教程:http ://docs.opencv.org/doc/tutorials/imgproc/histograms/template_matching/template_matching.html
int main()
{
cv::Mat input = cv::imread("../inputData/TemplateMatch.jpg");
cv::Mat gray;
cv::cvtColor(input,gray,CV_BGR2GRAY);
cv::Mat templ = cv::imread("../inputData/Template2.jpg");
cv::Mat img = input;
cv::Mat result;
/// Create the result matrix
int result_cols = img.cols - templ.cols + 1;
int result_rows = img.rows - templ.rows + 1;
result.create( result_cols, result_rows, CV_32FC1 );
int match_method = CV_TM_SQDIFF;
/// Do the Matching and Normalize
matchTemplate( img, templ, result, match_method );
normalize( result, result, 0, 1, cv::NORM_MINMAX, -1, cv::Mat() );
/// Localizing the best match with minMaxLoc
double minVal; double maxVal; cv::Point minLoc; cv::Point maxLoc;
cv::Point matchLoc;
minMaxLoc( result, &minVal, &maxVal, &minLoc, &maxLoc, cv::Mat() );
/// For SQDIFF and SQDIFF_NORMED, the best matches are lower values. For all the other methods, the higher the better
if( match_method == CV_TM_SQDIFF || match_method == CV_TM_SQDIFF_NORMED )
{ matchLoc = minLoc; }
else
{ matchLoc = maxLoc; }
/// Show me what you got
cv::rectangle( input, matchLoc, cv::Point( matchLoc.x + templ.cols , matchLoc.y + templ.rows ), cv::Scalar::all(0), 2, 8, 0 );
cv::rectangle( result, matchLoc, cv::Point( matchLoc.x + templ.cols , matchLoc.y + templ.rows ), cv::Scalar::all(0), 2, 8, 0 );
cv::imshow("input", input);
cv::imshow("template", templ);
cv::imwrite("../outputData/TemplateMatch.jpg", input);
cv::waitKey(0);
return 0;
}
输出:
