2017-07-19 239 views
1

我试图用findContour/matchShape函数在较大的图片中找到一个对象(对象可能有所不同,因此无法照看颜色或类似的东西,像SIFT这样的Featuredetectors也doesn't的工作,因为对象可以是对称的)使用OpenCV时的匹配问题matchShapes函数

enter image description here

我已经写了下面的代码:

Mat scene = imread... 
Mat Template = imread... 
Mat imagegray1, imagegray2, imageresult1, imageresult2; 
int thresh=80; 
double ans=0, result=0; 

// Preprocess pictures 
cvtColor(scene, imagegray1,CV_BGR2GRAY); 
cvtColor(Template,imagegray2,CV_BGR2GRAY); 

GaussianBlur(imagegray1,imagegray1, Size(5,5),2); 
GaussianBlur(imagegray2,imagegray2, Size(5,5),2); 

Canny(imagegray1, imageresult1,thresh, thresh*2); 
Canny(imagegray2, imageresult2,thresh, thresh*2); 


vector<vector <Point> > contours1; 
vector<vector <Point> > contours2; 
vector<Vec4i>hierarchy1, hierarchy2; 
// Template 
findContours(imageresult2,contours2,hierarchy2,CV_RETR_EXTERNAL,CV_CHAIN_APPROX_SIMPLE,cvPoint(0,0)); 
// Szene 
findContours(imageresult1,contours1,hierarchy1,CV_RETR_EXTERNAL,CV_CHAIN_APPROX_SIMPLE,cvPoint(0,0)); 

imshow("template", Template); 
double helper = INT_MAX; 
int idx_i = 0, idx_j = 0; 
// Match all contours with eachother 
for(int i = 0; i < contours1.size(); i++) 
{ 
    for(int j = 0; j < contours2.size(); j++) 
    { 
     ans=matchShapes(contours1[i],contours2[j],CV_CONTOURS_MATCH_I1 ,0); 
     // find the best matching contour 
     if((ans < helper)) 
     { 
      idx_i = i; 
      helper = ans; 
     } 
    } 
} 
    // draw the best contour 

drawContours(scene, contours1, idx_i, 
Scalar(255,255,0),3,8,hierarchy1,0,Point()); 

当我使用其中只有模板位于一个场景,我得到一个良好的匹配结果是:图片中的我有麻烦检测对象 enter image description here

但是,当有多个对象:最新的代码我可是问题使用 enter image description here

希望有人能告诉我。谢谢

回答

1

你在第二个图像(几乎每个字母)都有大量的轮廓。

2nd image with contours

由于matchShape检查尺度不变胡矩(http://docs.opencv.org/3.1.0/d3/dc0/group__imgproc__shape.html#gab001db45c1f1af6cbdbe64df04c4e944)也是一个非常小的轮廓可以适合你正在寻找的形状。

此外,原来的形状不正确区分像一个面积不包括所有的轮廓时,可以看到更小的50

if(contourArea(contours1[i]) > 50) 
    drawContours(scene, contours1, i, Scalar(255, 255, 0), 1); 

2nd image with contours larger 50

要与其他词说出来,没有问题与您的代码。轮廓可能无法很好地检测到。我建议看看approxCurveconvexHull并尝试用这种方法关闭轮廓。或以某种方式改进Canny的使用。

然后,您可以使用先验知识来限制您正在寻找的轮廓的大小(也可能是旋转?)。

+0

感谢您的答案和解释什么是“错误”。我目前正试图按照你的建议 – Drian