2011-12-11 54 views
29

找到輪廓時,我使用了CV_RETR_CCOMP參數。這應該創建一個兩級層次結構 - 第一級用於外部輪廓,第二級用於孔的邊界。但是,我從來沒有使用過一個層次結構,所以我不熟悉這一點。在OpenCV中的findContours()中使用層次結構?

有人可以指示我如何訪問孔的邊界嗎?我想忽略外輪廓,只畫出空洞的邊界。代碼示例將不勝感激。我使用C++接口而不是C,所以請不要建議C函數(即使用findContours()而不是cvFindContours())。

+0

介於C++版本和C版本之間是微不足道的。僅供參考。 –

回答

36

通過findContours返回的層次結構具有如下形式: hierarchy[idx][{0,1,2,3}]={next contour (same level), previous contour (same level), child contour, parent contour}

CV_RETR_CCOMP,返回外輪廓和孔的層次結構。 這意味着hierarchy[idx]的元素2和3至多有一個不等於-1:也就是說,每個元素沒有父或子,或者父但沒有子,或者子沒有父。

具有父級但不包含子級的元素將是空洞的邊界。

這意味着你基本上會通過hierarchy[idx]並用hierarchy[idx][3]>-1繪製任何東西。

喜歡的東西(在Python的作品,但還沒有測試C++想法是好的,但。):

findContours(image, contours, hierarchy, CV_RETR_CCOMP, CV_CHAIN_APPROX_SIMPLE); 

if (!contours.empty() && !hierarchy.empty()) { 

    // loop through the contours/hierarchy 
    for (int i=0; i<contours.size(); i++) { 

     // look for hierarchy[i][3]!=-1, ie hole boundaries 
     if (hierarchy[i][3] != -1) { 
      // random colour 
      Scalar colour((rand()&255), (rand()&255), (rand()&255)); 
      drawContours(outImage, contours, i, colour); 
     } 
    } 
} 
+1

@ Farhad確保你做了一些測試。層次可能不是你所期望的。我試圖從http://stackoverflow.com/questions/8449378/finding-contours-in-opencv您的圖像和圖像框架是父母,外輪廓是一個孩子,內輪廓既不是。 – SSteve

+0

@Farhad對不起,我的意思是圖像框架是一個孩子,圓的外輪廓是父母。 – SSteve

+0

謝謝,我想我必須找到解決辦法。 – fdh

3

AFAIK使用CV_RETR_CCOMP時,所有的孔都在同一水平上。

int firstHoleIndex = hierarchy[0][2]; 
for (int i = firstHoleIndex; i >= 0 ; i = hierarchy[i][0]) 
// contours.at(i) is a hole. Do something with it.