0

我有一个模板,我想知道该模板是否存在于图像中。好吧,我用谷歌搜索了很多,得出的结论是我需要使用cvMatchTemplateand cvMinMaxLoc

这是我的代码:

image = cvLoadImage("C:/images/flower.jpg",1);
templat = cvLoadImage("C:/images/flo.jpg",1);
image2=cvCreateImage( cvSize(image->width, image->height), IPL_DEPTH_8U, 1 );
result=cvCreateImage( cvSize(image->width, image->height), IPL_DEPTH_8U, 1 );
cvZero(result);
cvZero(image2);
cvCvtColor(image,image2,CV_BGR2GRAY);
cvMatchTemplate(image2, templat,result,CV_TM_CCORR_NORMED);

double min_val=0, max_val=0;
CvPoint min_loc, max_loc;
cvMinMaxLoc(result, &min_val, &max_val, &min_loc, &max_loc);

cvRectangle(image, max_loc, cvPoint(max_loc.x+templat->width,  
max_loc.y+templat->height), cvScalar(0), 1);

cvShowImage( "src", image );
cvShowImage( "result image", result);
cvWaitKey(0);

我的问题是当我运行上面的代码时,会显示一个消息框:

Unhandled exception at 0x747d812f in matching.exe: Microsoft C++ exception: cv::Exception at memory location 0x001ff6ec.. 

在黑屏中有一条消息:

OpenCV Error: Sizes of input arguments do not match <image and template should have the same type> in unknown function, file..\..\..\..\ocv\opencv\scr\cv\cvtempl.cpp, line 356.

请注意,这flower.jpg是彩色图像,flo.jpg是该图像的灰度。

对正在发生的事情有任何想法吗?

4

2 回答 2

2

您需要将两者都转换flower.jpgflo.jpg单通道图像。即使flo.jpg是灰度,您也将其加载为三通道图像。图像也result应该IPL_DEPTH_32FIPL_DEPTH_8U.

这是正确的代码(未经测试):

IplImage* image    = cvLoadImage("C:/images/flower.jpg", 1);
IplImage* templat  = cvLoadImage("C:/images/flo.jpg", 1);
IplImage* image2   = cvCreateImage(cvSize(image->width, image->height), IPL_DEPTH_8U, 1);
IplImage* templat2 = cvCreateImage(cvSize(templat->width, templat->height), IPL_DEPTH_8U, 1); 

cvCvtColor(image, image2, CV_BGR2GRAY);
cvCvtColor(templat, templat2, CV_BGR2GRAY);

int w = image->width - templat->width + 1;
int h = image->height - templat->height + 1;
result = cvCreateImage(cvSize(w, h), IPL_DEPTH_32F, 1);
cvMatchTemplate(image2, templat, result, CV_TM_CCORR_NORMED);

double min_val, max_val;
CvPoint min_loc, max_loc;
cvMinMaxLoc(result, &min_val, &max_val, &min_loc, &max_loc);

cvRectangle(image, max_loc, cvPoint(max_loc.x+templat->width, 
max_loc.y+templat->height), cvScalar(0), 1);

cvShowImage("src", image);
cvShowImage("result image", result);
cvWaitKey(0);
于 2013-04-19T12:07:36.260 回答
1

模板匹配假定两者image具有template相同数量的通道和通道深度。最简单的方法是以灰度加载它们:

Mat I = imread("lena.png", 0);
Mat T = imread("template.png", 0);

注意:我会命令使用 OpenCV2.0 C++ 接口。所以而不是cvLoadImage使用imread. 旧界面不再开发。

于 2013-04-19T12:28:32.990 回答