boxes_overlap.py 7.3 KB

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