0

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?

enter image description here

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

Jeru Luke
  • 20,118
  • 13
  • 80
  • 87
Rueen1963
  • 41
  • 2
  • 13
  • Please post an image with your letters. – PSchn Sep 05 '16 at 15:16
  • 1
    Possible duplicate of [How can I sort contours from left to right and top to bottom?](http://stackoverflow.com/questions/38654302/how-can-i-sort-contours-from-left-to-right-and-top-to-bottom) – Martin Evans Sep 05 '16 at 15:18
  • 2
    The algorithm scans the image rowise starting from the top-left corner. So the first letter is the one with the lowest y-value. So first t (y:9),then l(y:9), h(y:10), b(y:11), then last e (y:25), then r(y:26) , e(y:27) and o(y:26). So no random order ;) – PSchn Sep 05 '16 at 16:20

1 Answers1

2

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!