2016-06-10 20 views
0

的周長我使用OpenCV的2.4.13OpenCV中找到一個連接部件

我試圖找到一個連接部件的周邊,我想用ConnectedComponentWithStats,但它不返回周邊,只有區域,寬度等... 有一種方法來找到與輪廓但不是相反的區域(我的意思是一個組件,而不是整個圖像)。

方法arcLength不能正常工作,因爲我有組件的所有點,不僅是輪廓。

我知道有一種BF方法可以通過遍歷組件的每個像素來查找它,看看他是否有不在相同組件中的鄰居。但我想要一個花費更少的功能。否則,如果您知道將組件與findContours方法找到的輪廓相鏈接的方式,它也適合我。

感謝

+0

周邊的更快的方法有一個沒有區別輪廓和連接的組件,你可以上傳你的輸入圖像嗎? –

+0

連接的組件還有輪廓中的像素不是? – Akainiro

回答

0

最簡單的事情可能是使用findContours

您可以計算由connectedComponents(WithStats)計算出的第i個分量的輪廓,因此它們是與您的標籤對齊。使用CHAIN_APPROX_NONE您將獲得輪廓中的所有點,因此矢量的size()已經是邊界的度量。最後,您可以使用arcLength(...),以獲得更準確的結果:

Mat1i labels; 
int n_labels = connectedComponents(img, labels); 

for (int i = 1; i < n_labels; ++i) 
{ 
    // Get the mask for the i-th contour 
    Mat1b mask_i = labels == i; 

    // Compute the contour 
    vector<vector<Point>> contours;  
    findContours(mask_i.clone(), contours, RETR_EXTERNAL, CHAIN_APPROX_NONE); 

    if (!contours.empty()) 
    { 
     // The first contour (and probably the only one) 
     // is the one you're looking for 

     // Compute the perimeter 
     double perimeter_i = contours[0].size(); 
    } 
} 
+0

好的,我不知道我可以在一個特定的組件上使用findContours和一個蒙版,謝謝! – Akainiro

+0

很高興幫助; D – Miki

+0

問題:你爲什麼使用mask_i.clone()? mask_i不夠嗎? – Akainiro

0

添加到@三木的回答,這是找到連接組件

//getting the connected components with statistics 
cv::Mat1i labels, stats; 
cv::Mat centroids; 

int lab = connectedComponentsWithStats(img, labels, stats, centroids); 

for (int i = 1; i < lab; ++i) 
{ 
    //Rectangle around the connected component 
    cv::Rect rect(stats(i, 0), stats(i, 1), stats(i, 2), stats(i, 3)); 

    // Get the mask for the i-th contour 
    Mat1b mask_i = labels(rect) == i; 

    // Compute the contour 
    vector<vector<Point>> contours;  
    findContours(mask_i, contours, RETR_EXTERNAL, CHAIN_APPROX_NONE); 

    if(contours.size() <= 0) 
     continue;   

    //Finding the perimeter 
    double perimeter = contours[0].size(); 
    //you can use this as well for measuring perimeter 
    //double perimeter = arcLength(contours[0], true); 

}