2011-12-11 79 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.