给定这个最小的示例代码
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()
哪个输出让我们检查:
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/