n久之前在网上搜的的代码···想保存一份···· thx to the author
code 如下:
#include "StdAfx.h" #include "opencv2/highgui/highgui.hpp" #include "opencv2/imgproc/imgproc.hpp" #include <iostream> #include <stdio.h> using namespace std; using namespace cv; /// 全局变量 Mat img; Mat templ; Mat result; char* image_window = "Source Image"; char* result_window = "Result window"; char *dst_window = "Dest_windows"; int match_method; int max_Trackbar = 5; /// 函数声明 void MatchingMethod( int, void* ); /** @主函数 */ int main( int argc, char** argv ) { /// 载入原图像和模板块 img = imread( "d:\\me.jpg"); templ = imread("d:\\1.bmp" ); /* IplImage *img_src = cvLoadImage("d:\\me.jpg", 1); IplImage *img_dst = cvLoadImage("d:\\eye.jpg", 1); img(img_src, 0); img(img_dst, 0); */ /// 创建窗口 namedWindow( image_window, CV_WINDOW_AUTOSIZE ); namedWindow( result_window, CV_WINDOW_AUTOSIZE ); namedWindow( dst_window, CV_WINDOW_AUTOSIZE ); /// 创建滑动条 char* trackbar_label = "Method: \n 0: SQDIFF \n 1: SQDIFF NORMED \n 2: TM CCORR \n 3: TM CCORR NORMED \n 4: TM COEFF \n 5: TM COEFF NORMED"; createTrackbar( trackbar_label, image_window, &match_method, max_Trackbar, MatchingMethod ); MatchingMethod( 0, 0 ); waitKey(0); return 0; } /** * @函数 MatchingMethod * @简单的滑动条回调函数 */ void MatchingMethod( int, void* ) { /// 将被显示的原图像 Mat img_display; img.copyTo( img_display ); /// 创建输出结果的矩阵 int result_cols = img.cols - templ.cols + 1; int result_rows = img.rows - templ.rows + 1; result.create( result_cols, result_rows, CV_32FC1 ); /// 进行匹配和标准化 matchTemplate( img, templ, result, match_method ); normalize( result, result, 0, 1, NORM_MINMAX, -1, Mat() ); /// 通过函数 minMaxLoc 定位最匹配的位置 double minVal; double maxVal; Point minLoc; Point maxLoc; Point matchLoc; minMaxLoc( result, &minVal, &maxVal, &minLoc, &maxLoc, Mat() ); /// 对于方法 SQDIFF 和 SQDIFF_NORMED, 越小的数值代表更高的匹配结果. 而对于其他方法, 数值越大匹配越好 if( match_method == CV_TM_SQDIFF || match_method == CV_TM_SQDIFF_NORMED ) { matchLoc = minLoc; } else { matchLoc = maxLoc; } rectangle( img_display, matchLoc, Point( matchLoc.x + templ.cols , matchLoc.y + templ.rows ), Scalar::all(0), 2, 8, 0 ); rectangle( result, matchLoc, Point( matchLoc.x + templ.cols , matchLoc.y + templ.rows ), Scalar::all(0), 2, 8, 0 ); imshow( image_window, img_display ); imshow( result_window, result ); imshow( dst_window, templ ); return; }