#include <iostream>
#include <opencv2\opencv.hpp>
#include <math.h>
using namespace cv;
using namespace std;
/*原图片*/
Mat src = imread("E:\\3.jpg");
Mat dst;
/*目标*/
Mat temp = imread("E:\\4.jpg");
void Match_Demo() {
Mat img_display;
src.copyTo(img_display);
int width = src.cols - temp.cols + 1;
int height = src.rows - temp.rows + 1;
dst.create(Size(width, height), CV_32FC1);
int match_method = TM_SQDIFF;
matchTemplate(src, temp, dst, match_method, Mat());
normalize(dst, dst, 0, 1, NORM_MINMAX, -1, Mat());
Point minLoc;
Point maxLoc;
double min, max;
Point temLoc;
//查找数组中的极值以及位置
minMaxLoc(dst, &min, &max, &minLoc, &maxLoc, Mat());
if (match_method == TM_SQDIFF || match_method == TM_SQDIFF_NORMED) {
temLoc = minLoc;
}
else {
temLoc = maxLoc;
}
// 绘制匹配结果
rectangle(img_display, temLoc, Point(temLoc.x + temp.cols, temLoc.y + temp.rows), Scalar(255,0,0), 2, LINE_AA);
rectangle(dst, temLoc, Point(temLoc.x + temp.cols, temLoc.y + temp.rows), Scalar::all(0), 2, LINE_AA);
//imshow("result", dst);
imshow("match_result", img_display);
}
int main()
{
Match_Demo();
waitKey(0);
return 0;
}
模板匹配的效果一般,原图像与目标必须非常相似才能匹配成功。
原图:
目标:
结果: