Ask Your Question
0

How would I sort contours from cvFindContours using RETR_TREE into a tree/pyrimid based on hierarchy?

asked 2014-09-15 14:18:25 -0600

CVNovice gravatar image

updated 2014-09-15 15:40:02 -0600

For example if I were to input the hierarchy from 4.RETR_TREE here

hierarchy = 
    array([[[ 7, -1,  1, -1],
            [-1, -1,  2,  0],
            [-1, -1,  3,  1],
            [-1, -1,  4,  2],
            [-1, -1,  5,  3],
            [ 6, -1, -1,  4],
            [-1,  5, -1,  4],
            [ 8,  0, -1, -1],
            [-1,  7, -1, -1]]])

I would like to get this output:

{0:{1:{2:{3:{4:{5:{},6:{}}}}}},
7:{},
8:{}}

I am looking to do this to build a tree model in Qt so I can easily see which contours contain which others. If you have a better idea of how to turn the hierarchy data into a Qt tree model that would also be appreciated.

Thanks in advance!

edit retag flag offensive close merge delete

Comments

It's really(!) against netiquette to post your question twice without even saying to do so. In many cases, the question will be answered once and the poster won't even publish the answer at the other places (you are a nice exception from the rule...). But please at least make it visible that you copy/pasted the question.

FooBar gravatar imageFooBar ( 2014-10-23 02:14:12 -0600 )edit

Thanks for the tip. I didn't realize that. I just thought this forum would be more knowledgeable about opencv specifically while stack would be a good source of broader knowledge and has a larger user base. I'm not quite sure why it would be bad to post on two different forums?? It seems its just a better way to have more people see the question and potential answer.

CVNovice gravatar imageCVNovice ( 2015-04-17 11:17:28 -0600 )edit

1 answer

Sort by ยป oldest newest most voted
1

answered 2014-10-22 21:26:41 -0600

CVNovice gravatar image
import numpy as np
H = np.array(
    [[ 7, -1,  1, -1],
     [-1, -1,  2,  0],
     [-1, -1,  3,  1],
     [-1, -1,  4,  2],
     [-1, -1,  5,  3],
     [ 6, -1, -1,  4],
     [-1,  5, -1,  4],
     [ 8,  0, -1, -1],
     [-1,  7, -1, -1]])

def T(i):
    children = [(h, j) for j, h in enumerate(H) if h[3] == i]
    children.sort(key = lambda h: h[0][1])
    return {c[1]: T(c[1]) for c in children}

print T(-1)

Thanks to Falko at stack overflow for this answer.

edit flag offensive delete link more

Question Tools

Stats

Asked: 2014-09-15 14:18:25 -0600

Seen: 801 times

Last updated: Oct 22 '14