title: Python OpenCV Contour Tree Hierarchy Structure
body: <p>I am trying to implement the algorithm found <a href="http://www.m.cs.osakafu-u.ac.jp/cbdar2007/proceedings/papers/O1-1.pdf" rel="nofollow noreferrer">here</a> in python with OpenCV.</p>
  <p>I am trying to implement the part of the algorithm that remove irrelevant edge boundaries based on the number of interior boundaries that they have.</p>
  <ul>
  <li>If the current edge boundary has exactly one or two interior edge boundaries, the internal boundaries can be ignored</li>
  <li>If the current edge boundary has more than two interior edge boundaries, it can be ignored</li>
  </ul>
  <p>I am having trouble determining the tree structure of the contours I have extracted from the image.</p>
  <p>My current source:</p>
  <pre><code>import cv2
  
  # Load the image
  img = cv2.imread('test.png')
  cv2.copyMakeBorder(img, 50,50,50,50,cv2.BORDER_CONSTANT, img, (255,255,255))
  
  # Split out each channel
  blue = cv2.split(img)[0]
  green = cv2.split(img)[1]
  red = cv2.split(img)[2]
  
  # Run canny edge detection on each channel
  blue_edges = cv2.Canny(blue, 1, 255)
  green_edges = cv2.Canny(green, 1, 255)
  red_edges = cv2.Canny(red, 1, 255)
  
  # Join edges back into image
  edges = blue_edges | green_edges | red_edges
  
  # Find the contours
  contours,hierarchy = cv2.findContours(edges.copy(),cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
  
  # For each contour, find the bounding rectangle and draw it
  for cnt in contours:
      x,y,w,h = cv2.boundingRect(cnt)
      cv2.rectangle(edges,(x,y),(x+w,y+h),(200,200,200),2)
  
  # Finally show the image
  cv2.imshow('img',edges)
  cv2.waitKey(0)
  cv2.destroyAllWindows()
  </code></pre>
  <p>I assumed that using <code>cv2.RETR_TREE</code> would give me a nice nested array of the contours but that doesn't seem to be the case. How do I retrieve the tree structure of my contours?</p>