opencv之matchTemplate

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);
    
    }




你可能感兴趣的:(opencv之matchTemplate)