I'm using Python and OpenCV to detect contours in my image. But when I run the following code to draw only a specific contour using the contour index, since the indices allocated are random, I get the wrong output.
So I found out the Centroids (in my case all the centroids lie in the same horizontal line). Is there any way I can sort the contour indices from left to right (starting from 0 to n) based on the x value of the centroid?
Could you please show the code for the same? Any help would be greatly appreciated!
contours, hierarchy = cv2.findContours(thresh,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)
i = 9 ## Contour Index <----
cv2.drawContours(img,contours[i:i+1],-1,(0,0,255),2)
centroids = []
for cnt in contours:
mom = cv2.moments(cnt)
(x,y) = int(mom['m10']/mom['m00']), int(mom['m01']/mom['m00'])
cv2.circle(org,(x,y),4,(255,255,255),-1)
centroids.append((x,y)