简体   繁体   中英

C++ OpenCV sort contour hierarchy by level

I have a contour (RETR_TREE). I do understand, that I have a tree of contours denoted by the array

hierarchy[][4]

Structure is [Next, Previous, First_Child, Parent]

( http://docs.opencv.org/trunk/doc/py_tutorials/py_imgproc/py_contours/py_contours_hierarchy/py_contours_hierarchy.html )

My problem is to get the level of the current contour. I want to know the level. I have absolute no idea how to get this level from the parent, child, next or previous contour.

Can anyone provide code to get the level of the contour in the tree?

Thank you very much

When you want to get the level of contour you have to go to the parent of the parent of the parent, until you reach the root. This is true for any data structure that is tree, not only this one.

int nodeIndex = ....; // the contour whose depth you want to know
int depth=0;
// move from child to parent until you reach the outermost contour
while(hierarchy[nodeIndex][3] != -1) {
    depth++;
    nodeIndex = hierarchy[nodeIndex][3];
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM