补充:
#include ""中的内容相对于当前cpp文件目录
cvLoadImage("")中的路径相对于工程目录
cvMatchTemplate
计算结果矩阵中的最小值,最大值以及坐标:cvMinMaxLoc
画矩形:cvRectTangle
程序:
#include "cv.h" #include "cxcore.h" #include "highgui.h" #include <iostream> int MatchTemplate(int argc,char** argv) { //步骤1:加载模板图像,目标图像,创建结果图像 IplImage* MatchTemplate=cvLoadImage("e:\\picture\\MatchTemplate.jpg",0); //注意必须为单通道图像 IplImage* MatchTemplateDst=cvLoadImage("e:\\picture\\MatchTemplateDst.jpg",0); IplImage* MatchTemplateDstColor=cvLoadImage("e:\\picture\\MatchTemplateDst.jpg",1); cvNamedWindow("MatchTemplate"); cvNamedWindow("MatchTemplateDst"); cvShowImage("MatchTemplate",MatchTemplate); cvShowImage("MatchTemplateDst",MatchTemplateDst); int ResultImageX=MatchTemplateDst->width-MatchTemplate->width+1; int ResultImageY=MatchTemplateDst->height-MatchTemplate->height+1; IplImage* ResultImage=cvCreateImage(cvSize(ResultImageX,ResultImageY),32,1); cvZero(ResultImage); //步骤2:匹配图像,保存结果 cvMatchTemplate(MatchTemplateDst,MatchTemplate,ResultImage,CV_TM_CCOEFF); //步骤3:确定匹配图像坐标并且框出结果 double MinResultBefore=0; double MaxResultBefore=0; for(int i=0;i<10;i++) { double MinResult=0; double MaxResult=0; static int ResultNum=0; //计算符合的结果数目 CvPoint MinPtLeftUp; CvPoint MaxPtLeftUp; cvMinMaxLoc(ResultImage,&MinResult,&MaxResult,&MinPtLeftUp,&MaxPtLeftUp); //计算结果矩形中最大最小值及其坐标 if(ResultNum==0) { MinResultBefore=MinResult; MaxResultBefore=MaxResult; ResultNum++; } if(MaxResultBefore-MaxResult<1000000) { int MaxPtRightDownX=MaxPtLeftUp.x+MatchTemplate->width; int MaxPtRightDownY=MaxPtLeftUp.y+MatchTemplate->height; std::cout<<"MaxResult:"<<MaxResult<<std::endl; std::cout<<"MaxPtRightDownX:"<<MaxPtRightDownX<<std::endl; std::cout<<"MaxPtRightDownY:"<<MaxPtRightDownY<<std::endl; CvPoint MaxPtRightDown=cvPoint(MaxPtRightDownX,MaxPtRightDownY); cvRectangle(MatchTemplateDstColor,MaxPtLeftUp,MaxPtRightDown,cvScalar(0,255,0,NULL)); int SetResultLeftUpX=MaxPtLeftUp.x-MatchTemplate->width+1; int SetResultLeftUpY=MaxPtLeftUp.y-MatchTemplate->height+1; SetResultLeftUpX>0?SetResultLeftUpX:0; SetResultLeftUpY>0?SetResultLeftUpY:0; CvPoint SetResultLeftUp=cvPoint(SetResultLeftUpX,SetResultLeftUpY); CvPoint SetResultRightDown=cvPoint(MaxPtRightDownX,MaxPtRightDownY); cvRectangle(ResultImage,SetResultLeftUp,SetResultRightDown,cvRealScalar(MinResult),CV_FILLED); MinResultBefore=MinResult; MaxResultBefore=MaxResult; ResultNum++; } else { std::cout<<"ResultNum is "<<ResultNum<<std::endl; break; } } cvNamedWindow("Result"); cvShowImage("Result",MatchTemplateDstColor); cvWaitKey(0); cvDestroyWindow("MatchTemplate"); cvDestroyWindow("MatchTemplateDst"); cvDestroyWindow("Result"); cvReleaseImage(&MatchTemplate); cvReleaseImage(&MatchTemplateDst); return 0; }
第21集 目标匹配
时间: 2024-10-12 04:54:17