2017-07-19 246 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