boxbase.py 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. import math
  2. def is_in(box1, box2) -> bool:
  3. """box1是否完全在box2里面."""
  4. x0_1, y0_1, x1_1, y1_1 = box1
  5. x0_2, y0_2, x1_2, y1_2 = box2
  6. return (
  7. x0_1 >= x0_2 # box1的左边界不在box2的左边外
  8. and y0_1 >= y0_2 # box1的上边界不在box2的上边外
  9. and x1_1 <= x1_2 # box1的右边界不在box2的右边外
  10. and y1_1 <= y1_2
  11. ) # box1的下边界不在box2的下边外
  12. def bbox_relative_pos(bbox1, bbox2):
  13. """判断两个矩形框的相对位置关系.
  14. Args:
  15. bbox1: 一个四元组,表示第一个矩形框的左上角和右下角的坐标,格式为(x1, y1, x1b, y1b)
  16. bbox2: 一个四元组,表示第二个矩形框的左上角和右下角的坐标,格式为(x2, y2, x2b, y2b)
  17. Returns:
  18. 一个四元组,表示矩形框1相对于矩形框2的位置关系,格式为(left, right, bottom, top)
  19. 其中,left表示矩形框1是否在矩形框2的左侧,right表示矩形框1是否在矩形框2的右侧,
  20. bottom表示矩形框1是否在矩形框2的下方,top表示矩形框1是否在矩形框2的上方
  21. """
  22. x1, y1, x1b, y1b = bbox1
  23. x2, y2, x2b, y2b = bbox2
  24. left = x2b < x1
  25. right = x1b < x2
  26. bottom = y2b < y1
  27. top = y1b < y2
  28. return left, right, bottom, top
  29. def bbox_distance(bbox1, bbox2):
  30. """计算两个矩形框的距离。
  31. Args:
  32. bbox1 (tuple): 第一个矩形框的坐标,格式为 (x1, y1, x2, y2),其中 (x1, y1) 为左上角坐标,(x2, y2) 为右下角坐标。
  33. bbox2 (tuple): 第二个矩形框的坐标,格式为 (x1, y1, x2, y2),其中 (x1, y1) 为左上角坐标,(x2, y2) 为右下角坐标。
  34. Returns:
  35. float: 矩形框之间的距离。
  36. """
  37. def dist(point1, point2):
  38. return math.sqrt((point1[0] - point2[0]) ** 2 + (point1[1] - point2[1]) ** 2)
  39. x1, y1, x1b, y1b = bbox1
  40. x2, y2, x2b, y2b = bbox2
  41. left, right, bottom, top = bbox_relative_pos(bbox1, bbox2)
  42. if top and left:
  43. return dist((x1, y1b), (x2b, y2))
  44. elif left and bottom:
  45. return dist((x1, y1), (x2b, y2b))
  46. elif bottom and right:
  47. return dist((x1b, y1), (x2, y2b))
  48. elif right and top:
  49. return dist((x1b, y1b), (x2, y2))
  50. elif left:
  51. return x1 - x2b
  52. elif right:
  53. return x2 - x1b
  54. elif bottom:
  55. return y1 - y2b
  56. elif top:
  57. return y2 - y1b
  58. return 0.0