我有一个模板,我想知道模板是否存在于图像中。好吧,我在Google上搜索了很多,得出的结论是,我需要使用cvMatchTemplate
和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
是该图像的灰度。有什么想法吗?
最佳答案
您需要将flower.jpg
和flo.jpg
都转换为单通道图像。即使flo.jpg
是灰度的,您也将其加载为三通道图像。 result
图像也应该是IPL_DEPTH_32F
的IPL_DEPTH_8U
instad。
这是正确的代码(未经测试):
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);