boxes_overlap.py 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165
  1. import numpy as np
  2. def paired_intersection(boxes1, boxes2):
  3. """Compute paired intersection areas between boxes.
  4. Args:
  5. boxes1: a numpy array with shape [N, 4] holding N boxes
  6. boxes2: a numpy array with shape [N, 4] holding N boxes
  7. Returns:
  8. a numpy array with shape [N,] representing itemwise intersection area
  9. References:
  10. `core.box_list_ops.matched_intersection` in Tensorflow object detection API
  11. Notes:
  12. can called as itemwise_intersection, matched_intersection, aligned_intersection
  13. """
  14. max_x_mins = np.maximum(boxes1[:, 0], boxes2[:, 0])
  15. max_y_mins = np.maximum(boxes1[:, 1], boxes2[:, 1])
  16. min_x_maxs = np.minimum(boxes1[:, 2], boxes2[:, 2])
  17. min_y_maxs = np.minimum(boxes1[:, 3], boxes2[:, 3])
  18. intersect_widths = np.maximum(0, min_x_maxs - max_x_mins)
  19. intersect_heights = np.maximum(0, min_y_maxs - max_y_mins)
  20. return intersect_widths * intersect_heights
  21. def pairwise_intersection(boxes1, boxes2):
  22. """Compute pairwise intersection areas between boxes.
  23. Args:
  24. boxes1: a numpy array with shape [N, 4] holding N boxes.
  25. boxes2: a numpy array with shape [M, 4] holding M boxes.
  26. Returns:
  27. a numpy array with shape [N, M] representing pairwise intersection area.
  28. References:
  29. `core.box_list_ops.intersection` in Tensorflow object detection API
  30. `utils.box_list_ops.intersection` in Tensorflow object detection API
  31. """
  32. if boxes1.shape[0] * boxes2.shape[0] == 0:
  33. return np.zeros((boxes1.shape[0], boxes2.shape[0]), dtype=boxes1.dtype)
  34. swap = False
  35. if boxes1.shape[0] > boxes2.shape[0]:
  36. boxes1, boxes2 = boxes2, boxes1
  37. swap = True
  38. intersect_areas = np.empty((boxes1.shape[0], boxes2.shape[0]), dtype=boxes1.dtype)
  39. for i in range(boxes1.shape[0]):
  40. max_x_mins = np.maximum(boxes1[i, 0], boxes2[:, 0])
  41. max_y_mins = np.maximum(boxes1[i, 1], boxes2[:, 1])
  42. min_x_maxs = np.minimum(boxes1[i, 2], boxes2[:, 2])
  43. min_y_maxs = np.minimum(boxes1[i, 3], boxes2[:, 3])
  44. intersect_widths = np.maximum(0, min_x_maxs - max_x_mins)
  45. intersect_heights = np.maximum(0, min_y_maxs - max_y_mins)
  46. intersect_areas[i, :] = intersect_widths * intersect_heights
  47. if swap:
  48. intersect_areas = intersect_areas.T
  49. return intersect_areas
  50. def paired_overlap_ratio(boxes1, boxes2, ratio_type='iou'):
  51. """Compute paired overlap ratio between boxes.
  52. Args:
  53. boxes1: a numpy array with shape [N, 4] holding N boxes
  54. boxes2: a numpy array with shape [N, 4] holding N boxes
  55. ratio_type:
  56. iou: Intersection-over-union (iou).
  57. ioa: Intersection-over-area (ioa) between two boxes box1 and box2 is defined as
  58. their intersection area over box2's area. Note that ioa is not symmetric,
  59. that is, IOA(box1, box2) != IOA(box2, box1).
  60. min: Compute the ratio as the area of intersection between box1 and box2,
  61. divided by the minimum area of the two bounding boxes.
  62. Returns:
  63. a numpy array with shape [N,] representing itemwise overlap ratio.
  64. References:
  65. `core.box_list_ops.matched_iou` in Tensorflow object detection API
  66. `structures.boxes.matched_boxlist_iou` in detectron2
  67. `mmdet.core.bbox.bbox_overlaps`, see https://mmdetection.readthedocs.io/en/v2.17.0/api.html#mmdet.core.bbox.bbox_overlaps
  68. """
  69. intersect_areas = paired_intersection(boxes1, boxes2)
  70. areas1 = (boxes1[:, 2] - boxes1[:, 0]) * (boxes1[:, 3] - boxes1[:, 1])
  71. areas2 = (boxes2[:, 2] - boxes2[:, 0]) * (boxes2[:, 3] - boxes2[:, 1])
  72. if ratio_type in ['union', 'iou', 'giou']:
  73. union_areas = areas1 - intersect_areas
  74. union_areas += areas2
  75. intersect_areas /= union_areas
  76. elif ratio_type == 'min':
  77. min_areas = np.minimum(areas1, areas2)
  78. intersect_areas /= min_areas
  79. elif ratio_type == 'ioa':
  80. intersect_areas /= areas2
  81. else:
  82. raise ValueError('Unsupported ratio_type. Got {}'.format(ratio_type))
  83. if ratio_type == 'giou':
  84. min_xy_mins = np.minimum(boxes1[:, 0:2], boxes2[:, 0:2])
  85. max_xy_mins = np.maximum(boxes1[:, 2:4], boxes2[:, 2:4])
  86. # mebb = minimum enclosing bounding boxes
  87. mebb_whs = np.maximum(0, max_xy_mins - min_xy_mins)
  88. mebb_areas = mebb_whs[:, 0] * mebb_whs[:, 1]
  89. union_areas -= mebb_areas
  90. union_areas /= mebb_areas
  91. intersect_areas += union_areas
  92. return intersect_areas
  93. def pairwise_overlap_ratio(boxes1, boxes2, ratio_type='iou'):
  94. """Compute pairwise overlap ratio between boxes.
  95. Args:
  96. boxes1: a numpy array with shape [N, 4] holding N boxes
  97. boxes2: a numpy array with shape [M, 4] holding M boxes
  98. ratio_type:
  99. iou: Intersection-over-union (iou).
  100. ioa: Intersection-over-area (ioa) between two boxes box1 and box2 is defined as
  101. their intersection area over box2's area. Note that ioa is not symmetric,
  102. that is, IOA(box1, box2) != IOA(box2, box1).
  103. min: Compute the ratio as the area of intersection between box1 and box2,
  104. divided by the minimum area of the two bounding boxes.
  105. Returns:
  106. a numpy array with shape [N, M] representing pairwise overlap ratio.
  107. References:
  108. `utils.np_box_ops.iou` in Tensorflow object detection API
  109. `utils.np_box_ops.ioa` in Tensorflow object detection API
  110. `utils.np_box_ops.giou` in Tensorflow object detection API
  111. `mmdet.core.bbox.bbox_overlaps`, see https://mmdetection.readthedocs.io/en/v2.17.0/api.html#mmdet.core.bbox.bbox_overlaps
  112. `torchvision.ops.box_iou`, see https://pytorch.org/vision/stable/ops.html#torchvision.ops.box_iou
  113. `torchvision.ops.generalized_box_iou`, see https://pytorch.org/vision/stable/ops.html#torchvision.ops.generalized_box_iou
  114. http://ww2.mathworks.cn/help/vision/ref/bboxoverlapratio.html
  115. """
  116. intersect_areas = pairwise_intersection(boxes1, boxes2)
  117. areas1 = (boxes1[:, 2] - boxes1[:, 0]) * (boxes1[:, 3] - boxes1[:, 1])
  118. areas2 = (boxes2[:, 2] - boxes2[:, 0]) * (boxes2[:, 3] - boxes2[:, 1])
  119. if ratio_type in ['union', 'iou', 'giou']:
  120. union_areas = np.expand_dims(areas1, axis=1) - intersect_areas
  121. union_areas += np.expand_dims(areas2, axis=0)
  122. intersect_areas /= union_areas
  123. elif ratio_type == 'min':
  124. min_areas = np.minimum(np.expand_dims(areas1, axis=1), np.expand_dims(areas2, axis=0))
  125. intersect_areas /= min_areas
  126. elif ratio_type == 'ioa':
  127. intersect_areas /= np.expand_dims(areas2, axis=0)
  128. else:
  129. raise ValueError('Unsupported ratio_type. Got {}'.format(ratio_type))
  130. if ratio_type == 'giou':
  131. min_xy_mins = np.minimum(boxes1[:, None, 0:2], boxes2[:, 0:2])
  132. max_xy_mins = np.maximum(boxes1[:, None, 2:4], boxes2[:, 2:4])
  133. # mebb = minimum enclosing bounding boxes
  134. mebb_whs = np.maximum(0, max_xy_mins - min_xy_mins)
  135. mebb_areas = mebb_whs[:, :, 0] * mebb_whs[:, :, 1]
  136. union_areas -= mebb_areas
  137. union_areas /= mebb_areas
  138. intersect_areas += union_areas
  139. return intersect_areas