#include <iostream>
#include <opencv2/opencv.hpp>
using namespace std;
using namespace cv;
Mat img1, img2, img3, img4,img_result, img_gray1, img_gray2, img_gray3, img_hsv1, img_hsv2, img_hsv3;
MatND img_hist1, img_hist2, img_hist3;
char win1[] = "window1";
char win2[] = "window2";
char win3[] = "window3";
char win4[] = "window4";
char win5[] = "window5";
int threshold_value = 0;
int max_value = 255;
RNG rng(12345);
int Demo_Match_Template();
string convertToString(double d);
void Demo_Match(int,void*);
int index = 0;
int match_threshold = 20;
int max_track = 255;
int match_method = CV_TM_SQDIFF;
//模板匹配
int Demo_Match_Template()
{
namedWindow(win1, CV_WINDOW_AUTOSIZE);
//namedWindow(win2, CV_WINDOW_AUTOSIZE);
namedWindow(win3, CV_WINDOW_AUTOSIZE);
img1 = imread("D://images//1//p5.jpg");
img2 = imread("D://images//1//p5_1.jpg");
if (img1.empty()||img2.empty())
{
cout << "could not load image..." << endl;
return 0;
}
//imshow(win1, img1);
createTrackbar("Trace bar", win1, &match_threshold, max_track, Demo_Match);
Demo_Match(0,0);
imshow(win1, img1);
return 0;
}
void Demo_Match(int, void*)
{
int width = img1.cols - img2.cols + 1;
int height = img1.rows - img2.rows + 1;
img3 = Mat(width,height,CV_32FC1);
matchTemplate(img1, img2, img3, match_method, Mat());
//归一化
normalize(img3, img3, 0, 1, NORM_MINMAX,-1,Mat());
Point minLoc;
Point maxLoc;
Point tempLoc;
double min, max;
minMaxLoc(img3, &min, &max, &minLoc, &maxLoc, Mat());
if (match_method==CV_TM_SQDIFF || match_method==CV_TM_SQDIFF_NORMED)
{
tempLoc = minLoc;
}
else
{
tempLoc = maxLoc;
}
img1.copyTo(img4);
//绘制矩形
rectangle(img4, Rect(tempLoc.x, tempLoc.y,img2.cols,img2.rows),Scalar(0,0,255),2,8);
//rectangle(img3, Rect(tempLoc.x, tempLoc.y, img2.cols, img2.rows), Scalar(0, 0, 255), 2, 8);
imshow(win2,img2);
imshow(win3,img4);
}
string convertToString(double d)
{
ostringstream os;
if (os << d)
{
return os.str();
}
return "Invalid conversion...";
}
int main()
{
Demo_Match_Template();
waitKey(0);
return 0;
}
原文地址:https://www.cnblogs.com/herd/p/9737314.html