OpenCV的。匹配时绘制矩形 [英] OpenCV. Drawing rectangle when matching
问题描述
我使用OpenCv查找与参考图像上的模板匹配的区域。当代码找到与模板匹配的区域时,在该区域周围绘制一个矩形,但我想要的是当代码找不到该区域时代码不会绘制任何矩形
i use OpenCv to find an area witch match a template on a reference image. When the code find the area witch match a template draw a rectangle around the area but what i want is when the code doesnt find the area the code doesnt draw any rectangle
代码:
IplImage *res;
CvPoint minloc, maxloc;
double minval, maxval;
int img_width, img_height;
int tpl_width, tpl_height;
int res_width, res_height;
NSString *path = [[NSBundle mainBundle] pathForResource:@"reference" ofType:@"jpg"];
reference.image = [UIImage imageWithContentsOfFile:path];
NSString *pathPatron = [[NSBundle mainBundle] pathForResource:@"template" ofType:@"jpg"];
template.image = [UIImage imageWithContentsOfFile:pathPatron];
IplImage *img = [self CreateIplImageFromUIImage:original.image];//
IplImage *tpl = [self CreateIplImageFromUIImage:patron.image];
img_width = img->width;
img_height = img->height;
tpl_width = tpl->width;
tpl_height = tpl->height;
res_width = img_width - tpl_width + 1;
res_height = img_height - tpl_height + 1;
res = cvCreateImage( cvSize( res_width, res_height ), IPL_DEPTH_32F, 1 );
/* choose template matching method to be used */
cvMatchTemplate( img, tpl, res, CV_TM_SQDIFF );
cvMinMaxLoc( res, &minval, &maxval, &minloc, &maxloc, 0 );
/* draw red rectangle */
cvRectangle( img,
cvPoint( minloc.x, minloc.y ),
cvPoint( minloc.x + tpl_width, minloc.y + tpl_height ),
cvScalar( 0, 0, 255, 0 ), 1, 0, 0 );
/* display images */
reference.image = [self UIImageFromIplImage:img];
cvReleaseImage(&img);
cvReleaseImage(&tpl);
cvReleaseImage(&res);
提前致谢
推荐答案
cvMatchTemplate
并没有真正找到匹配项 - 它只是为您的图像和模板计算相似度图。接下来,您需要确定是否存在真实匹配或没有匹配。最简单的解决方案是与某个阈值进行比较:
cvMatchTemplate
does not really find the match - it just calculates similarity map for your image and template. Next you need to decide if there is a real match or there are no matches. The simplest solution is a comparison with some threshold:
if (minval < THRESHOLD)
{
//draw rectangle
}
您需要进行一些实验才能找到工作值 THRESHOLD
。
You need to make some experiments to find a working value of the THRESHOLD
.
这篇关于OpenCV的。匹配时绘制矩形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!