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

标签 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)

产生以下图像:

我希望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]
...

我所缺少的是更深层的含义吗?我做错了什么吗?或者文档只是不正确/功能已损坏?

最佳答案

迟到的答案
我尝试了下面的代码

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]

关于python - OpenCV,Python,findContours,层次结构中的元素数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30396983/

相关文章:

netbeans - 带有 mingw 的 Opencv2.4.0 在 Windows 中崩溃

python - 如何使用python检测复选框

android - 通过 Activity 使用OpenCV时Android崩溃

C++:升级到 GTX970 后 cv::gpu::GpuMat::upload 出现长时间延迟

python - 在 Python 中查找字符串中长度最短的单词

python - 什么时候使用 __call__ 是个好主意?

python - 如何在按钮中显示图像?

python - 系统 ('hostname' ) 从 MATLAB 到 Python

python - 视频流变得失真的QImage

python - CFFI如何避免手动设置LD_LIBRARY_PATH