Using hierarchy in findContours () in OpenCV?

The hierarchy returned by findContours has the following form:
hierarchy[idx][{0,1,2,3}]={next contour (same level), previous contour (same level), child contour, parent contour}

CV_RETR_CCOMP, returns a hierarchy of outer contours and holes.
This means elements 2 and 3 of hierarchy[idx] have at most one of these not equal to -1: that is, each element has either no parent or child, or a parent but no child, or a child but no parent.

An element with a parent but no child would be a boundary of a hole.

That means you basically go through hierarchy[idx] and draw anything with hierarchy[idx][3]>-1.

Something like (works in Python, but haven’t tested the C++. Idea is fine though.):

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 );
        }
    }
}

Leave a Comment