问题
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