I'm trying to sort bounding box in sequence either clockwise or anti clockwise. To achieve this I'm trying this approach by calculating angle between center of bounding box and center of image and arranging them in ascending order as shown in below code
import cv2
import matplotlib.pyplot as plt
import numpy as np
from math import sqrt
import math
bbox = [[(747, 497), (798, 561)],[(1010, 656), (1071, 689)],[(637, 207), (681, 265)],[(679, 99), (726, 126)], [(1002, 131), (1059, 155)],[(829, 124), (892, 187)]]
final_sort = []
img = cv2.imread(r'input.png')
h,w = img.shape[:2]
c1x,c1y = h/2,w/2
for idx, bb in enumerate(bbox):
c2x,c2y = ((bb[0][0]+bb[1][0])/2,(bb[0][1]+bb[1][1])/2)
dx = c1x-c2x
dy = c1y- c2y
angle = math.atan2(dy, dx)
final_sort.append([idx,angle,[bb[0][0],bb[0][1],bb[1][0],bb[1][1]]])
final_sort.sort(key = lambda final_sort:final_sort[1])
new_bbox = []
for idx,(i,j,k) in enumerate(final_sort):
print(k)
new_bbox.append(k)
image = cv2.rectangle(img, (k[0],k[1]), (k[2],k[3]), (0,255,0), 2)
center = ((k[0]+k[2])/2,(k[1]+k[3])/2)
x,y = int(center[0]),int(center[1])
cv2.circle(img, (int(x), int(y)), 5, (255,255,255), -1)
cv2.putText(img, str(idx), (k[0], y),
cv2.FONT_HERSHEY_SIMPLEX, 5, (255,255,255), 2)
cv2.imwrite('output.png',img)
source image is [input image][1]
When I draw this resultant sorted bounding box I get the image as this [output image][2] but not as I expected which is index either should be in clockwise or anti clockwise manner from top as shown in this image [expected image][3] Any suggestions or guide to accomplish this will be highly appreciated