opencv之matchTemplate
阿新 • • 發佈:2019-02-16
C++:void matchTemplate(InputArray image, InputArray templ, OutputArray result, int method)
image: 搜尋物件影象 It must be 8-bit or 32-bit floating-point.
templ:模板影象,小於image,並且和image有相同的資料型別
result:比較結果 必須是單通單32位浮點數
method:比較演算法總共有六種如下所示
method=CV_TM_SQDIFF
-
method=CV_TM_SQDIFF_NORMED
-
method=CV_TM_CCORR
-
method=CV_TM_CCORR_NORMED
-
method=CV_TM_CCOEFF
where
-
method=CV_TM_CCOEFF_NORMED
-
#include<opencv2\core\core.hpp> #include<opencv2\highgui\highgui.hpp> #include<opencv2\imgproc\imgproc.hpp> #include<iostream> using namespace std; using namespace cv; Mat src,tmpl,result; int matchMethod = 0; Mat src_gray,tmpl_gray; void on_match(int,void*); int main() { src = imread("fruits.jpg"); tmpl = imread("template.jpg"); if (!src.data) return-1; cvtColor(src,src_gray,CV_RGB2GRAY); if (!tmpl.data) return-1; cvtColor(tmpl,tmpl_gray,CV_RGB2GRAY); namedWindow("MatchImage"); namedWindow("Result"); createTrackbar("匹配演算法","MatchImage",&matchMethod,5,on_match); on_match(matchMethod,0); waitKey(); return 0; } void on_match(int,void*) { Mat img = src_gray.clone(); matchTemplate(src_gray,tmpl_gray,result,matchMethod); ///定位 double minValue,maxValue; Point minLoc,maxLoc; Point matchLoc; minMaxLoc(result,&minValue,&maxValue,&minLoc,&maxLoc,Mat()); if( matchMethod == CV_TM_SQDIFF || matchMethod == CV_TM_SQDIFF_NORMED ) { matchLoc = minLoc; } else { matchLoc = maxLoc; } rectangle(img,matchLoc,Point(matchLoc.x+tmpl.cols,matchLoc.y+tmpl.rows),Scalar::all(0),2,8,0); rectangle( result, matchLoc, Point( matchLoc.x + tmpl.cols , matchLoc.y + tmpl.rows ), Scalar::all(0), 2, 8, 0 ); imshow("MatchImage",img); imshow("Result",result); }