1

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

godzillabeast
  • 155
  • 11
  • You can try to use `minAreaRect()` that will return you a `RotatedRect` and with `angle` obtain the rotation angle of that box – erik7854 Mar 16 '22 at 16:17
  • Connect bounding box centers by the convex hull of all centers and use contour stuff: https://stackoverflow.com/questions/1165647/how-to-determine-if-a-list-of-polygon-points-are-in-clockwise-order – Micka Mar 16 '22 at 16:33
  • Ah sorry, they are not aligned convex. Use delauny triangulation and make sure that there are no internal vertices left. – Micka Mar 16 '22 at 16:35
  • ok. Can you show how it can be done to this problem? any source or link will be helpful @Micka – godzillabeast Mar 16 '22 at 17:06
  • 4
    in your code you mix up x and y. c1x and c1y need to be w/2 and h/2 respectively. -- and... can you see where angle 0 will be? it's dx=0 dy>0 -- and your last loop... idx is one index, but i is another index! -- and you should sort the list only once, after the first loop is done. sorting in the loop is pointless. – Christoph Rackwitz Mar 16 '22 at 17:51
  • hey, tx fixing c1x and c1y solved my problem , thanks :) – godzillabeast Mar 16 '22 at 19:36

0 Answers0