batched_boxes.py 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. import numpy as np
  2. def convert_boxes_list_to_batched_boxes(boxes_list):
  3. """
  4. Args:
  5. boxes_list: list or tuple of ndarray with shape (N_i, 4+K)
  6. Returns:
  7. ndarray with shape (M, 5+K) where M is sum of N_i.
  8. References:
  9. `convert_boxes_to_roi_format` in TorchVision
  10. `mmdet.core.bbox.bbox2roi` in mmdetection
  11. `modeling.poolers.convert_boxes_to_pooler_format` in detectron2
  12. """
  13. assert isinstance(boxes_list, (list, tuple))
  14. # avoids a copy if there is only a single element in a list
  15. if len(boxes_list) == 1:
  16. concat_boxes = boxes_list[0]
  17. else:
  18. concat_boxes = np.concatenate(boxes_list, axis=0)
  19. indices_list = [np.full((len(b), 1), i, concat_boxes.dtype)
  20. for i, b in enumerate(boxes_list)]
  21. indices = np.concatenate(indices_list, axis=0)
  22. batched_boxes = np.hstack([indices, concat_boxes])
  23. return batched_boxes
  24. def convert_batched_boxes_to_boxes_list(batched_boxes):
  25. """
  26. References:
  27. `convert_boxes_to_roi_format` in TorchVision
  28. `mmdet.core.bbox.roi2bbox` in mmdetection
  29. """
  30. assert isinstance(batched_boxes, np.ndarray)
  31. assert batched_boxes.ndim == 2 and batched_boxes.shape[-1] >= 5
  32. boxes_list = []
  33. indices = np.unique(batched_boxes[:, 0])
  34. for index in indices:
  35. inds = (batched_boxes[:, 0] == index)
  36. boxes = batched_boxes[inds, 1:]
  37. boxes_list.append(boxes)
  38. return boxes_list