OpenCV findContours are not in order

一笑奈何 提交于 2019-12-08 11:42:04

问题


When using OpenCV findContours method, how come the contours are not found in order?

inputImage = cv2.imread("randomImage.jpg",0)

im2, contours, hierarchy = cv2.findContours(inputImage.copy(),cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)

j=1

for cnt in reversed(contours):

    letter = inputImage[y:y+h, x:x+w]
    cv2.imwrite(str(j)+"sub/"+str(k)+'.png', letter) 
    k+=1

The input image consists of a few letters, for example "abcde". However, when the contours are saved to file they are saved in a random order like "c", "e", "d", "a", "b". Is there any reason for this?

output: t, l, h, b, e, r, g, o, e


回答1:


If you carefully observe the Opencv Contours hierarchy page, attaching it's link:https://docs.opencv.org/3.4.0/d9/d8b/tutorial_py_contours_hierarchy.html

You will observe that depending on the hierarchy and that you use the order of contours stored( in you case t l h b ... and so on) will differ.It will treat contours which do not have a child first then the contours that have a child.

But if you chose a hierarchy for example a RETR_CCOMP it will start taking contours from the most depth to contours with no child at last.

If you chose hierarchy like RETR_TREE then contour with maximum number of child is taken first.

That is how the contour is treated and not according to x,y coordinates. If you want to output such a sequence you should get a centroid and go for x,y sort.

Hope this is helpful!



来源:https://stackoverflow.com/questions/39333407/opencv-findcontours-are-not-in-order

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!