cvMatchTemplate函数实现的模板匹配,此函数也可自己实现,楼主自己做了一种匹配方法准确度还有待提升,所以在此还是用的opencv的函数,下面先对这个函数做个说明:
比较模板和重叠的图像区域
void cvMatchTemplate( const CvArr* image, const CvArr* templ, CvArr* result, int method );
实现代码如下:
int picProcessBasics::IMGGetTargetRect(IplImage* srcImage, IplImage* dest,CvRect *targetRect)
{
if(NULL == srcImage || NULL == dest)
return -1;
int srcW, srcH, templatW, templatH, resultH, resultW;
double minValue, maxValue;
CvPoint minLoc, maxLoc;
IplImage *result = NULL;
srcW = srcImage->width;
srcH = srcImage->height;
templatW = dest->width;
templatH = dest->height;
resultW = srcW - templatW + 1;
resultH = srcH - templatH + 1;
result = cvCreateImage(cvSize(resultW, resultH), 32, 1);
cvMatchTemplate(srcImage,dest,result,CV_TM_CCORR_NORMED);
cvMinMaxLoc(result, &minValue, &maxValue, &minLoc, &maxLoc,0);
targetRect->x = maxLoc.x;
targetRect->y = maxLoc.y;
targetRect->height = dest->height;
targetRect->width = dest->width;
cvReleaseImage(&result);
return 0;
}
static void testIMGGetTargetRect()
{
IplImage *pSrcImage =NULL;
IplImage *pDstImage =NULL;
char pic_path[MAX_PATH]={0};
char tempS[MAX_PATH]={0};
picProcessBasics mytest;
CvRect targetRect;
GetCurrentDirectory(MAX_PATH,pic_path);
sprintf(tempS, "%s%s", pic_path,"\\pic\\stuff.jpg");
pSrcImage = cvLoadImage(tempS, CV_LOAD_IMAGE_UNCHANGED);
sprintf(tempS, "%s%s", pic_path,"\\pic\\myTestTarget.png");
pDstImage = cvLoadImage(tempS, CV_LOAD_IMAGE_UNCHANGED);
mytest.IMGGetTargetRect(pSrcImage,pDstImage,&targetRect);
CvPoint pt1;
pt1.x=targetRect.x;
pt1.y=targetRect.y;
CvPoint pt2;
pt2.x=targetRect.x+targetRect.width;
pt2.y=targetRect.y+targetRect.height;
cvRectangle(pSrcImage,pt1,pt2,Scalar(0,255,0));
sprintf(tempS, "%s%s", pic_path,"\\picResult\\testIMGGetTargetRect.jpg");
cvSaveImage( tempS, pSrcImage,0);
cvReleaseImage(&pSrcImage);
cvReleaseImage(&pDstImage);
}
原图像:
目标图像:
检测到目标的结果: