Sorting paths from left to right in Python (OpenCV)

I am using Python and OpenCV to detect contours in my image. But when I run the following code to draw only a specific outline using the outline index, since the allocated indices are random, I get the wrong output.

So, I got to know Centroids (in my case, all centroids lie on the same horizontal line). Is there a way to sort the contour indices from left to right (0 to n) based on the x value of the centroid?

Could you please show the code for this? 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)

      

+3


source to share


1 answer


Implements a list sorting function in python like here .

In the implemented function, you compute the center and check if the X position is smoother or less than the other. If gretter returns 1, less than -1 and equal to 0.

def greater(a, b):
    momA = cv2.moments(a)        
    (xa,ya) = int(momA['m10']/momA['m00']), int(momA['m01']/momA['m00'])

    momB = cv2.moments(b)        
    (xb,yb) = int(momB['m10']/momB['m00']), int(momB['m01']/momB['m00'])
    if xa>xb 
        return 1

    if xa == xb
        return 0
    else
        return -1

      



Of course, you can do better if you only calculate the centers once.

then just

contours.sort(greater)

      

+2


source







All Articles