findContours, number of elements in hierarchy (Python) [closed]

asked 2015-05-26 04:24:19 -0600

Dobiasd gravatar image

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(
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


to access the data but


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?

edit retag flag offensive reopen merge delete

Closed for the following reason question is not relevant or outdated by sturkmen
close date 2020-10-14 09:41:45.015036