I am following this question:
How can I sort contours from left to right and top to bottom?
to sort contours from left-to-right and top-to-bottom. However, m
What you actually need is to devise a formula to convert your contour information to a rank and use that rank to sort the contours, Since you need to sort the contours from top to Bottom and left to right so your formula must involve the origin
of a given contour to calculate its rank. For example we can use this simple method:
def get_contour_precedence(contour, cols):
origin = cv2.boundingRect(contour)
return origin[1] * cols + origin[0]
It gives a rank to each contour depending upon the origin of contour. It varies largely when two consecutive contours lie vertically but varies marginally when contours are stacked horizontally. So in this way, First the contours would be grouped from Top to Bottom and in case of Clash the less variant value among the horizontal laid contours would be used.
import cv2
def get_contour_precedence(contour, cols):
tolerance_factor = 10
origin = cv2.boundingRect(contour)
return ((origin[1] // tolerance_factor) * tolerance_factor) * cols + origin[0]
img = cv2.imread("/Users/anmoluppal/Downloads/9VayB.png", 0)
_, img = cv2.threshold(img, 70, 255, cv2.THRESH_BINARY)
im, contours, h = cv2.findContours(img.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
contours.sort(key=lambda x:get_contour_precedence(x, img.shape[1]))
# For debugging purposes.
for i in xrange(len(contours)):
img = cv2.putText(img, str(i), cv2.boundingRect(contours[i])[:2], cv2.FONT_HERSHEY_COMPLEX, 1, [125])
If you see closely, the third row where 3, 4, 5, 6
contours are placed the 6
comes between 3 and 5, The reason is that the 6
th contour is slightly below the line of 3, 4, 5
contours.
Tell me is you want the output in other way around we can tweak the get_contour_precedence
to get 3, 4, 5, 6
ranks of contour corrected.