0

I'm trying to sort the list of bounding boxes obtained after object detection from right to left and top to down. Below are the bounding box locations

bbox = [(637, 207, 681, 207),  (679, 99, 726, 99), (747, 497, 798, 497), (829, 124, 892, 124), (1002, 131, 1059, 131),  (1010, 656, 1071, 656)] 

I sorted this list based on xmin value as below

sorted(bbox,key=lambda x:x[2][0])

I ended up getting bounding box arrangement as shown in the below image [![sample image][1]][1]

the sequence is not in order , the sequence should start from left to right and top to bottom as shown in below image [![sample2][2]][2]

any suggestion or guide to achieve this will be highly appreciated

godzillabeast
  • 155
  • 11
  • 1. In your output point '1' is to the right of point '2' so do you want from right-to-left or left-to-right? 2. You mean the points should follow the drawn object? If so, please give the the coordinate system used, (a, b, c, d) are what exactly? – SiP Mar 14 '22 at 17:51
  • Yes right to left , coordinate system used are xmin,ymin,xmax,ymax – godzillabeast Mar 14 '22 at 18:04
  • This is not a simple sorting function. You have to think of the conditions to decide which point comes next. I think the information required is not present in the bbox. – SiP Mar 14 '22 at 18:10
  • See https://pyimagesearch.com/2015/04/20/sorting-contours-using-python-and-opencv/ – fmw42 Mar 14 '22 at 18:51
  • I implemented that but didn't work – godzillabeast Mar 14 '22 at 19:58
  • your second image directly contradicts what you wrote above it. what you *show* looks like **counterclockwise** order. so you should consider the center of the picture, and the angle between each point and the image center. – Christoph Rackwitz Mar 15 '22 at 13:46
  • angle between center of bounding box and image you mean? – godzillabeast Mar 16 '22 at 09:25

1 Answers1

0

You want the points sorted by closest to the upper-left corner? If so you need to calculate the distance from that corner and only then sort:

import numpy as np

bbox = [(637, 207, 681, 207),  (679, 99, 726, 99), (747, 497, 798, 497), (829, 124, 892, 124), (1002, 131, 1059, 131),  (1010, 656, 1071, 656)]
arr = np.array(bbox)
r = (arr[:, 0]**2 + arr[:, 1] **2)**0.5
print(np.argsort(r))

This will print out the order of the points. I assumed the first 2 coordinates in each point are the x and y and that the origin is in the upper-left corner.

SiP
  • 1,080
  • 3
  • 8