boxes_clip.py 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637
  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. x_min, y_min, x_max, y_max = reference_box[:4]
  8. boxes = np.array(boxes, dtype=np.float32, copy=copy)
  9. lower = np.array([[x_min, y_min, x_min, y_min]])
  10. upper = np.array([[x_max, y_max, x_max, y_max]])
  11. np.clip(boxes[:, :4], lower, upper, boxes[:,:4])
  12. return boxes
  13. def clip_boxes_to_image(boxes, image_width, image_height, subpixel=True, copy=True):
  14. """Clip boxes to image boundaries.
  15. References:
  16. `clip_boxes` in py-faster-rcnn
  17. `core.boxes_op_list.clip_to_window` in TensorFlow object detection API.
  18. `structures.Boxes.clip` in detectron2
  19. Notes:
  20. Equivalent to `clip_boxes(boxes, [0,0,image_width-1,image_height-1], copy)`
  21. """
  22. boxes = np.array(boxes, dtype=np.float32, copy=copy)
  23. if not subpixel:
  24. image_width -= 1
  25. image_height -= 1
  26. np.clip(boxes[:, 0], 0, image_width, boxes[:, 0])
  27. np.clip(boxes[:, 1], 0, image_height, boxes[:, 1])
  28. np.clip(boxes[:, 2], 0, image_width, boxes[:, 2])
  29. np.clip(boxes[:, 3], 0, image_height, boxes[:, 3])
  30. return boxes