#include<opencv2/opencv.hpp>
#include<opencv2/highgui.hpp>
#include<opencv2/imgproc.hpp>
#include<opencv2/core.hpp>
#include<math.h>
#include<iostream>
#include<vector>
using namespace std;
using namespace cv;
int main(int argc, char** argv)
{
Mat result;
Mat src = imread("mario.png", IMREAD_COLOR);
Mat templ = imread("cin.png", IMREAD_COLOR);
int match_method = TM_CCOEFF_NORMED;
if (src.empty() || templ.empty())
{
cout << "加载图片失败" << endl;
return -1;
}
int srcW, srcH, templatW, templatH;
srcW = src.cols;
srcH = src.rows;
templatW = templ.cols;
templatH = templ.rows;
if (srcW < templatW || srcH < templatH)
{
cout << "模板不能比原图小" << endl;
return -1;
}
int resultW = srcW - templatW + 1;
int resultH = srcH - templatH + 1;
result.create(Size(resultW, resultH), CV_32FC1);
matchTemplate(src, templ, result, match_method);
cout << "depth:" << result.depth() << endl;
cout << "type:" << result.type() << endl;
cout << "channels:" << result.channels() << endl;
cout << "total:" << result.total() << endl;
Point matchLoc;
int count = 0;
if (result.channels() == 1)
{
MatIterator_<float> it_begin, it_end;
for (it_begin = result.begin<float>(), it_end = result.end<float>(); it_begin != it_end; it_begin++)
{
if (*it_begin >= 0.8)
{
count++;
matchLoc = it_begin.pos();
rectangle(src, matchLoc, Point(matchLoc.x + templ.cols, matchLoc.y + templ.rows), Scalar(255, 0, 0), 2, 8, 0);
}
}
cout <<"count = "<<count << endl;
}
namedWindow("output", WINDOW_AUTOSIZE);
moveWindow("output", src.cols, 0);
imshow("output", src);
imshow("result", result);
waitKey(0);
return 0;
}
运行结果: