你的问题可能是,模板匹配不具有尺度不变性,而你的模板大小不适合物体的大小。
使用此输入和代码,我获得以下输出:
输入图像:
![enter image description here](https://istack.dev59.com/Zfc7f.webp)
输入模板:
![enter image description here](https://istack.dev59.com/ADe1V.webp)
代码:基本上取自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;
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;
matchTemplate( img, templ, result, match_method );
normalize( result, result, 0, 1, cv::NORM_MINMAX, -1, cv::Mat() );
double minVal; double maxVal; cv::Point minLoc; cv::Point maxLoc;
cv::Point matchLoc;
minMaxLoc( result, &minVal, &maxVal, &minLoc, &maxLoc, cv::Mat() );
if( match_method == CV_TM_SQDIFF || match_method == CV_TM_SQDIFF_NORMED )
{ matchLoc = minLoc; }
else
{ matchLoc = maxLoc; }
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;
}
输出:
![在此输入图片描述](https://istack.dev59.com/vtwRj.webp)