Sorting contours left to right in Python (OpenCV)

前端 未结 1 521
慢半拍i
慢半拍i 2021-02-06 16:48

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 allocat

相关标签:
1条回答
  • 2021-02-06 17:26

    Implements de sort function of list in python like here.

    In the implemented function you calculate the center and verify if the X position is gretter or smaller them the other. If gretter return 1, smaller -1 and equals 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
    

    For sure you can do better if you calculate the centers only once.

    then just do

    contours.sort(greater)
    
    0 讨论(0)
提交回复
热议问题