OpenCV模板匹配

代码:

#include <iostream> 
#include "opencv2/opencv.hpp"

using namespace std;
using namespace cv;
 
int main( int argc, char** argv ) 
{ 
    Mat img; 
    Mat tpl; 
    Mat res; 
	Mat mask;
    Point        minloc, maxloc; 
    double        minval, maxval; 
    int            img_width, img_height; 
    int            tpl_width, tpl_height; 
    int            res_width, res_height; 
 
    /* check for arguments */ 
    if( argc < 3 ) { 
        cerr << "Usage: template_match <reference> <template>" << endl; 
        return 1; 
    } 
 
    /* load reference image */ 
    img = imread( argv[1] ); 
 
    /* always check */ 
	if( img.empty() ) { 
        cerr <<  "Cannot load file " << argv[1] << endl; 
        return 1;  
    } 
 
    /* load template image */ 
    tpl = imread( argv[2] ); 
 
    /* always check */ 
	if( tpl.empty()) { 
        cerr <<  "Cannot load file " << argv[2] << endl; 
        return 1; 
    } 
 
    /* get image's properties */ 
	img_width  = img.cols; 
	img_height = img.rows; 
	tpl_width  = tpl.cols; 
	tpl_height = tpl.rows; 
    res_width  = img_width - tpl_width + 1; 
    res_height = img_height - tpl_height + 1; 
 
    /* create new image for template matching computation */ 
    res = cvCreateImage( cvSize( res_width, res_height ), IPL_DEPTH_32F, 1 ); 
 
    /* choose template matching method to be used */ 
    matchTemplate( img, tpl, res, CV_TM_SQDIFF );  
    minMaxLoc( res, &minval, &maxval, &minloc, &maxloc,mask); 
 
    /* draw white rectangle */ 
    rectangle( img,  
                 cvPoint( minloc.x, minloc.y ),  
                 cvPoint( minloc.x + tpl_width, minloc.y + tpl_height ), 
                 cvScalar( 255, 255, 255, 0 ), 1, 0, 0 );     
 
    /* display images */ 
	imshow( "reference", img ); 
    imshow( "template", tpl ); 
 
    /* wait until user press a key to exit */ 
    cvWaitKey( 0 );  
    return 0; 
} 

函数minMaxLoc()

作用:找到矩阵中全局最大值和最小值。

     C++: void minMaxLoc(InputArray src, double* minVal, double* maxVal=0, Point* minLoc=0, Point* maxLoc=0, InputArraymask=noArray())

具体参数含义参考:http://docs.opencv.org/modules/core/doc/operations_on_arrays.html#minmaxloc


函数 matchTemplate()

作用:比较模板图像和源图像重叠区域的匹配。

     C++: void matchTemplate(InputArray image, InputArray templ, OutputArray result, int method)

具体参数含义参考:http://docs.opencv.org/modules/imgproc/doc/object_detection.html


结果

模板图像


匹配之后


图中白色框区域是匹配区域,效果很不错哦!


文章参考:http://www.cnblogs.com/gnuhpc/archive/2012/12/07/2807494.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值