Search code examples
pythonnumpyopencvimage-processingscikit-image

OpenCV: Sorting array of circles


I need to sort an array of circles (as result of HoughCircles function) by top to bottom and left to right but I can't manage to do so.

I used the python built-in sorted method as follows:

circles = np.round(circles[0, :]).astype("int")
circles = sorted(circles, key=lambda v: [v[0], v[1]])

And I get the following result: image

For instance, in this example image it jumps from circle 61 to 64, from 96 to 100 and so on.

It wrongly sorted some circles, and it seems that it's because some circles are a pixel or two misaligned, causing these mistakes.

EDIT:

These are my raw data and sample image:

sample image

raw data of circles [[y, x, radius]]

sorting snippet


Solution

  • As an alternative, after you have sorted with [v[0],v[1]] you make a new sort over a slice of the original list with the number of rows as block size. The downside of this solution is that you will be tied to the number of rows on your answer sheet.

        ...
        circles = np.round(circles[0,:]).astype("int")
        circles = sorted(circles, key=lambda v: [v[0], v[1]])
    
        NUM_ROWS = 30
    
        sorted_cols = []
        for k in range(0, len(circles), NUM_ROWS):
            col = circles[k:k+NUM_ROWS]
            sorted_cols.extend(sorted(col, key=lambda v: v[1]))
    
        circles = sorted_cols
    
        img_colored = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
    
        if circles is not None:
        ...
    

    answer sheet comparison