Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

findContours, number of elements in hierarchy (Python)

x-post (SO)

Given this minimal example code

import numpy as np
import cv2

img = np.zeros((512,512,1), np.uint8)
cv2.rectangle(img, (100,100), (200,200), 255, -1)
cv2.rectangle(img, (300,300), (400,400), 255, -1)
#cv2.imwrite('img.png', img)
contours,hierarchy = cv2.findContours(
    img,
    cv2.RETR_TREE,
    cv2.CHAIN_APPROX_SIMPLE)
print hierarchy
print len(hierarchy)

that produces the following image:

enter image description here

I would expect hierarchy to look like this

[[ 1 -1 -1 -1]
 [-1  0 -1 -1]]

because the documentation clearly states

hierarchy –
Optional output vector, containing information about the image topology.
It has as many elements as the number of contours.
For each i-th contour contours[i] , the elements
hierarchy[i][0] , hiearchy[i][1] , hiearchy[i][2] , and hiearchy[i][3]
are set to 0-based indices in contours of the next and previous contours
at the same hierarchical level,
the first child contour and the parent contour, respectively.

But actually it looks like this:

[[[ 1 -1 -1 -1]
  [-1  0 -1 -1]]]

This means that hierarchy does not have 2 elements (like the documentation suggests), but only 1 element. Thus I do not have to use

hierarchy[i][0]
hierarchy[i][1]
...

to access the data but

hierarchy[0][i][0]
hierarchy[0][i][1]
...

Is there a deeper meaning behind this that I am missing, am I doing something wrong, or is the documentation just incorrect / the function broken?