OpenCV,Python,findContours,层次结构中的元素数量

时间:2015-05-22 12:40:08

标签: python opencv

给出这个最小的示例代码

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)

产生以下图像:

enter image description here

我希望hierarchy看起来像这样

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

因为documentation明确说明了

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.

但实际上它看起来像这样:

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

这意味着hierarchy没有2个元素(如文档所示),但只有1个元素。 因此我不必使用

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

访问数据但

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

这背后是否有更深层的含义,我错过了,我做错了什么,或者文档是不正确/功能坏了?

1 个答案:

答案 0 :(得分:0)

最新答案:)

我尝试了以下代码

import numpy as np
import cv2

img = np.zeros((512,512,1), np.uint8)
cv2.rectangle(img, (100,100), (200,200), 255, 5)
cv2.rectangle(img, (300,300), (400,400), 255, 5)
#cv2.imwrite('img.png', img)
_,contours,hierarchy = cv2.findContours(
    img,
    cv2.RETR_TREE,
    cv2.CHAIN_APPROX_SIMPLE)
print hierarchy
print len(hierarchy)
imgBGR=cv2.cvtColor(img,cv2.COLOR_GRAY2BGR)
print ('0 Blue')
cv2.drawContours(imgBGR,contours,0,(255,0,0),2)
print ('1 Purple')
cv2.drawContours(imgBGR,contours,1,(255,0,255),2)
print ('2 Red')
cv2.drawContours(imgBGR,contours,2,(0,0,255),2)
print ('3 Green')
cv2.drawContours(imgBGR,contours,3,(0,255,0),2)
cv2.imshow('imgBGR',imgBGR)
cv2.waitKey()

输出

enter image description here

检查:

hierarchy[0] [ 2 -1 1 -1]

hierarchy[Blue] [ Next is Red, Previous is none, First_Child is Purple, Parent is none]

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

hierarchy[Purple] [ Next is none, Previous is none, First_Child is none, Parent is Blue]

hierarchy[2] [-1 0 3 -1]

hierarchy[Red] [ Next is none, Previous is Blue, First_Child is Green, Parent is none]

hierarchy[3] [-1 -1 -1 2]

hierarchy[Green] [ Next is none, Previous is none, First_Child is none, Parent is Red]