pythonopencv模板匹配多⽬标_OpenCv多⽬标模板匹配具体思路如下:⾸先,通过cvMatchTemplate模板进⾏匹配,匹配完成之后会产⽣⼀张结果单通道的灰⾊图像,再利⽤cvMinMaxLoc函数查数组中全局最⼩值。每次最⼩值肯定只有⼀个,所以需要把每次到的最⼩值(数组区域处理其它值,本⽂处理为最⼤值,也就是匹配最不像的值),这样就可以继续查全局接剩余较⼩的区域了。
CvPoint getNextMinLoc(IplImage *result, CvPoint minLoc, int maxVaule, int templatW, int templatH)
{
// 先将第⼀个最⼩值点附近两倍模板宽度和⾼度的都设置为最⼤值防⽌产⽣⼲扰
int startX = minLoc.x - templatW;rectangle函数opencv
int startY = minLoc.y - templatH;
int endX = minLoc.x + templatW;
int endY = minLoc.y + templatH;
if(startX < 0 || startY < 0)
{
startX = 0;
startY = 0;
}
if(endX > result->width - 1 || endY > result->height - 1)
{
endX = result->width - 1;
endY = result->height - 1;
}
for(int y = startY; y < endY; y++)
for(int x = startX; x < endX; x++)
cvSetReal2D(result, y, x, maxVaule);
double new_minVaule, new_maxValue;
CvPoint new_minLoc, new_maxLoc;
cvMinMaxLoc(result, &new_minVaule, &new_maxValue, &new_minLoc, &new_maxLoc);
return new_minLoc;
}
int main()
{
IplImage *src = cvLoadImage("E:/src.jpg");
IplImage *templat = cvLoadImage("E:/template.jpg");
IplImage *result; // 模板匹配结果
if(!src || !templat)
{
cout << "打开图⽚失败" << endl;
return 0;
}
int srcW, srcH, templatW, templatH, resultH, resultW;
srcW = src->width;
srcH = src->height;
templatW = templat->width;
templatH = templat->height;
if(srcW < templatW || srcH < templatH)
{
cout << "模板不能⽐原图⼩" << endl;
return 0;
}
resultW = srcW - templatW + 1;
resultH = srcH - templatH + 1;
result = cvCreateImage(cvSize(resultW, resultH), 32, 1); //匹配⽅法计算的结果最⼩值为float
cvMatchTemplate(src, templat, result, CV_TM_SQDIFF); //⽅差最⼩,匹配最好
double minValue, maxValue;
CvPoint minLoc, maxLoc;
cvMinMaxLoc(result, &minValue, &maxValue, &minLoc, &maxLoc);
cvRectangle(src, minLoc, cvPoint(minLoc.x + templatW, minLoc.y+ templatH), cvScalar(0,0,255));
CvPoint new_minLoc;
// 计算下⼀个最⼩值
new_minLoc = getNextMinLoc(result, minLoc, maxValue, templatW, templatH);
cvRectangle(src, new_minLoc, cvPoint(new_minLoc.x + templatW, new_minLoc.y+ templatH), cvScalar(0,0,255)); cvNamedWindow("srcResult", 1);
cvNamedWindow("templat", 1);
cvShowImage("srcResult", src);
cvShowImage("templat", templat);
cvWaitKey(0);
cvReleaseImage(&result);
cvReleaseImage(&templat);
cvReleaseImage(&src); return 0;
}
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论