在OpenCV中的findContours()中使用层次结构?

fdh*_*fdh 31 c++ opencv image list image-processing

找到轮廓时,我使用了CV_RETR_CCOMP参数.这应该创建一个两级层次结构 - 第一个级别用于外部轮廓,第二个级别用于孔的边界.但是,我之前从未使用过层次结构,因此我对此并不熟悉.

有人可以指导我如何访问洞的边界吗?我想忽略外部轮廓,只绘制孔边界.代码示例将不胜感激.我使用的是C++接口而不是C,所以请不要建议C函数(即使用findContours()而不是cvFindContours()).

mat*_*fee 41

返回的层次结构findContours具有以下形式: hierarchy[idx][{0,1,2,3}]={next contour (same level), previous contour (same level), child contour, parent contour}

CV_RETR_CCOMP,返回外轮廓和孔的层次结构.这意味着元素2和3中hierarchy[idx]至多有一个不等于-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 );
        }
    }
}
Run Code Online (Sandbox Code Playgroud)