1. 程式人生 > >opencv之matchTemplate

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

R(x,y)= \sum _{x',y'} (T(x',y')-I(x+x',y+y'))^2

  • method=CV_TM_SQDIFF_NORMED

    R(x,y)= \frac{\sum_{x',y'} (T(x',y')-I(x+x',y+y'))^2}{\sqrt{\sum_{x',y'}T(x',y')^2 \cdot \sum_{x',y'} I(x+x',y+y')^2}}

  • method=CV_TM_CCORR

    R(x,y)= \sum _{x',y'} (T(x',y')  \cdot I(x+x',y+y'))

  • method=CV_TM_CCORR_NORMED

    R(x,y)= \frac{\sum_{x',y'} (T(x',y') \cdot I(x+x',y+y'))}{\sqrt{\sum_{x',y'}T(x',y')^2 \cdot \sum_{x',y'} I(x+x',y+y')^2}}

  • method=CV_TM_CCOEFF

    R(x,y)= \sum _{x',y'} (T'(x',y')  \cdot I'(x+x',y+y'))

    where

    \begin{array}{l} T'(x',y')=T(x',y') - 1/(w  \cdot h)  \cdot \sum _{x'',y''} T(x'',y'') \\ I'(x+x',y+y')=I(x+x',y+y') - 1/(w  \cdot h)  \cdot \sum _{x'',y''} I(x+x'',y+y'') \end{array}

  • method=CV_TM_CCOEFF_NORMED

    R(x,y)= \frac{ \sum_{x',y'} (T'(x',y') \cdot I'(x+x',y+y')) }{ \sqrt{\sum_{x',y'}T'(x',y')^2 \cdot \sum_{x',y'} I'(x+x',y+y')^2} }

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