實現模板匹配
阿新 • • 發佈:2018-11-22
1、 函式
void matchTemplate(InputArray image,InputArray templ,OutputArray result,int method)
引數一:待搜尋影象陣列,且需為8位或者32位浮點型影象
引數二:搜尋模板,有相同的型別,且尺寸不大於輸入影象
引數三:比較結果的對映影象
引數四:匹配的演算法
平方差匹配方法:TM_SQDIFF
歸一化平方差匹配法:TM_SQDIFF_NORMED
相關匹配法:TM_CCORR
歸一化相關匹配法:TM_CCORR_NORMED
係數匹配法:TM_CCOEFF
歸一化相關係數匹配法:TM_CCOEFF_NORMED
#include <opencv2/imgproc/imgproc.hpp> #include <opencv2/highgui/highgui.hpp> #include <iostream> #define WINDOW_NAME1 "原始圖" #define WINDOW_NAME2 "效果圖" using namespace std; using namespace cv; Mat g_srcImage,g_templateImage,g_resultImage; int g_nMatchMethod; int g_nMaxTrackbarNum = 5; void on_Matching(int,void *); int main(int argc,char *argv[]) { if(argc!=3) return -1; g_srcImage = imread(argv[1],1); g_templateImage = imread(argv[2],1); namedWindow(WINDOW_NAME1,WINDOW_AUTOSIZE); namedWindow(WINDOW_NAME2,WINDOW_AUTOSIZE); createTrackbar("方法",WINDOW_NAME1,&g_nMatchMethod,g_nMaxTrackbarNum,on_Matching); on_Matching(0,0); waitKey(0); return 0; } void on_Matching(int,void *) { Mat srcImage; g_srcImage.copyTo(srcImage); int resultImage_cols = g_srcImage.cols - g_templateImage.cols +1; int resultImage_rows = g_srcImage.rows - g_templateImage.rows +1; g_resultImage.create(resultImage_rows,resultImage_cols,CV_32FC1); matchTemplate(g_srcImage,g_templateImage,g_resultImage,g_nMatchMethod); normalize(g_resultImage,g_resultImage,0,1,NORM_MINMAX,-1,Mat()); double minValue,maxValue; Point minLocation,maxLocation,matchLocation; minMaxLoc(g_resultImage,&minValue,&maxValue,&minLocation,&maxLocation,Mat()); if(g_nMatchMethod==TM_SQDIFF||g_nMatchMethod==TM_SQDIFF_NORMED) matchLocation = minLocation; else matchLocation = maxLocation; rectangle(g_srcImage,matchLocation,Point(matchLocation.x + g_templateImage.cols,matchLocation.y+g_templateImage.rows),Scalar(0,0,255),2,8,0); rectangle(g_resultImage,matchLocation,Point(matchLocation.x + g_templateImage.cols,matchLocation.y+g_templateImage.rows),Scalar(0,0,255),2,8,0); imshow(WINDOW_NAME1,g_srcImage); imshow(WINDOW_NAME2,g_resultImage); }
結果圖:
來自:opencv3程式設計入門 毛星雲pdf