boxes_clip.py 1.1 KB

12345678910111213141516171819202122232425262728293031323334
  1. import numpy as np
  2. def clip_boxes(boxes, reference_box, copy=True):
  3. """Clip boxes to reference box.
  4. References:
  5. `clip_to_window` in TensorFlow object detection API.
  6. """
  7. if copy:
  8. boxes = boxes.copy()
  9. ref_x_min, ref_y_min, ref_x_max, ref_y_max = reference_box[:4]
  10. lower = np.array([ref_x_min, ref_y_min, ref_x_min, ref_y_min])
  11. upper = np.array([ref_x_max, ref_y_max, ref_x_max, ref_y_max])
  12. np.clip(boxes[..., :4], lower, upper, boxes[..., :4])
  13. return boxes
  14. def clip_boxes_to_image(boxes, image_width, image_height, subpixel=True, copy=True):
  15. """Clip boxes to image boundaries.
  16. References:
  17. `clip_boxes` in py-faster-rcnn
  18. `core.boxes_op_list.clip_to_window` in TensorFlow object detection API.
  19. `structures.Boxes.clip` in detectron2
  20. Notes:
  21. Equivalent to `clip_boxes(boxes, [0,0,image_width-1,image_height-1], copy)`
  22. """
  23. if not subpixel:
  24. image_width -= 1
  25. image_height -= 1
  26. reference_box = [0, 0, image_width, image_height]
  27. return clip_boxes(boxes, reference_box, copy)