box_ops.py 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  1. # Copyright (c) Meta Platforms, Inc. and affiliates. All Rights Reserved
  2. # pyre-unsafe
  3. """
  4. Utilities for bounding box manipulation and GIoU.
  5. """
  6. from typing import Tuple
  7. import torch
  8. def box_cxcywh_to_xyxy(x):
  9. x_c, y_c, w, h = x.unbind(-1)
  10. b = [(x_c - 0.5 * w), (y_c - 0.5 * h), (x_c + 0.5 * w), (y_c + 0.5 * h)]
  11. return torch.stack(b, dim=-1)
  12. def box_cxcywh_to_xywh(x):
  13. x_c, y_c, w, h = x.unbind(-1)
  14. b = [(x_c - 0.5 * w), (y_c - 0.5 * h), (w), (h)]
  15. return torch.stack(b, dim=-1)
  16. def box_xywh_to_xyxy(x):
  17. x, y, w, h = x.unbind(-1)
  18. b = [(x), (y), (x + w), (y + h)]
  19. return torch.stack(b, dim=-1)
  20. def box_xywh_to_cxcywh(x):
  21. x, y, w, h = x.unbind(-1)
  22. b = [(x + 0.5 * w), (y + 0.5 * h), (w), (h)]
  23. return torch.stack(b, dim=-1)
  24. def box_xyxy_to_xywh(x):
  25. x, y, X, Y = x.unbind(-1)
  26. b = [(x), (y), (X - x), (Y - y)]
  27. return torch.stack(b, dim=-1)
  28. def box_xyxy_to_cxcywh(x):
  29. x0, y0, x1, y1 = x.unbind(-1)
  30. b = [(x0 + x1) / 2, (y0 + y1) / 2, (x1 - x0), (y1 - y0)]
  31. return torch.stack(b, dim=-1)
  32. def box_area(boxes):
  33. """
  34. Batched version of box area. Boxes should be in [x0, y0, x1, y1] format.
  35. Inputs:
  36. - boxes: Tensor of shape (..., 4)
  37. Returns:
  38. - areas: Tensor of shape (...,)
  39. """
  40. x0, y0, x1, y1 = boxes.unbind(-1)
  41. return (x1 - x0) * (y1 - y0)
  42. def masks_to_boxes(masks):
  43. """Compute the bounding boxes around the provided masks
  44. The masks should be in format [N, H, W] where N is the number of masks, (H, W) are the spatial dimensions.
  45. Returns a [N, 4] tensors, with the boxes in xyxy format
  46. """
  47. if masks.numel() == 0:
  48. return torch.zeros((0, 4), device=masks.device)
  49. h, w = masks.shape[-2:]
  50. y = torch.arange(0, h, dtype=torch.float, device=masks.device)
  51. x = torch.arange(0, w, dtype=torch.float, device=masks.device)
  52. y, x = torch.meshgrid(y, x)
  53. x_mask = masks * x.unsqueeze(0)
  54. x_max = x_mask.flatten(1).max(-1)[0] + 1
  55. x_min = x_mask.masked_fill(~(masks.bool()), 1e8).flatten(1).min(-1)[0]
  56. y_mask = masks * y.unsqueeze(0)
  57. y_max = y_mask.flatten(1).max(-1)[0] + 1
  58. y_min = y_mask.masked_fill(~(masks.bool()), 1e8).flatten(1).min(-1)[0]
  59. boxes = torch.stack([x_min, y_min, x_max, y_max], 1)
  60. # Invalidate boxes corresponding to empty masks.
  61. boxes = boxes * masks.flatten(-2).any(-1)
  62. return boxes
  63. def box_iou(boxes1, boxes2):
  64. """
  65. Batched version of box_iou. Boxes should be in [x0, y0, x1, y1] format.
  66. Inputs:
  67. - boxes1: Tensor of shape (..., N, 4)
  68. - boxes2: Tensor of shape (..., M, 4)
  69. Returns:
  70. - iou, union: Tensors of shape (..., N, M)
  71. """
  72. area1 = box_area(boxes1)
  73. area2 = box_area(boxes2)
  74. # boxes1: (..., N, 4) -> (..., N, 1, 2)
  75. # boxes2: (..., M, 4) -> (..., 1, M, 2)
  76. lt = torch.max(boxes1[..., :, None, :2], boxes2[..., None, :, :2])
  77. rb = torch.min(boxes1[..., :, None, 2:], boxes2[..., None, :, 2:])
  78. wh = (rb - lt).clamp(min=0) # (..., N, M, 2)
  79. inter = wh[..., 0] * wh[..., 1] # (..., N, M)
  80. union = area1[..., None] + area2[..., None, :] - inter
  81. iou = inter / union
  82. return iou, union
  83. def generalized_box_iou(boxes1, boxes2):
  84. """
  85. Batched version of Generalized IoU from https://giou.stanford.edu/
  86. Boxes should be in [x0, y0, x1, y1] format
  87. Inputs:
  88. - boxes1: Tensor of shape (..., N, 4)
  89. - boxes2: Tensor of shape (..., M, 4)
  90. Returns:
  91. - giou: Tensor of shape (..., N, M)
  92. """
  93. iou, union = box_iou(boxes1, boxes2)
  94. # boxes1: (..., N, 4) -> (..., N, 1, 2)
  95. # boxes2: (..., M, 4) -> (..., 1, M, 2)
  96. lt = torch.min(boxes1[..., :, None, :2], boxes2[..., None, :, :2])
  97. rb = torch.max(boxes1[..., :, None, 2:], boxes2[..., None, :, 2:])
  98. wh = (rb - lt).clamp(min=0) # (..., N, M, 2)
  99. area = wh[..., 0] * wh[..., 1] # (..., N, M)
  100. return iou - (area - union) / area
  101. @torch.jit.script
  102. def fast_diag_generalized_box_iou(boxes1, boxes2):
  103. assert len(boxes1) == len(boxes2)
  104. box1_xy = boxes1[:, 2:]
  105. box1_XY = boxes1[:, :2]
  106. box2_xy = boxes2[:, 2:]
  107. box2_XY = boxes2[:, :2]
  108. # assert (box1_xy >= box1_XY).all()
  109. # assert (box2_xy >= box2_XY).all()
  110. area1 = (box1_xy - box1_XY).prod(-1)
  111. area2 = (box2_xy - box2_XY).prod(-1)
  112. lt = torch.max(box1_XY, box2_XY) # [N,2]
  113. lt2 = torch.min(box1_XY, box2_XY)
  114. rb = torch.min(box1_xy, box2_xy) # [N,2]
  115. rb2 = torch.max(box1_xy, box2_xy)
  116. inter = (rb - lt).clamp(min=0).prod(-1)
  117. tot_area = (rb2 - lt2).clamp(min=0).prod(-1)
  118. union = area1 + area2 - inter
  119. iou = inter / union
  120. return iou - (tot_area - union) / tot_area
  121. @torch.jit.script
  122. def fast_diag_box_iou(boxes1, boxes2):
  123. assert len(boxes1) == len(boxes2)
  124. box1_xy = boxes1[:, 2:]
  125. box1_XY = boxes1[:, :2]
  126. box2_xy = boxes2[:, 2:]
  127. box2_XY = boxes2[:, :2]
  128. # assert (box1_xy >= box1_XY).all()
  129. # assert (box2_xy >= box2_XY).all()
  130. area1 = (box1_xy - box1_XY).prod(-1)
  131. area2 = (box2_xy - box2_XY).prod(-1)
  132. lt = torch.max(box1_XY, box2_XY) # [N,2]
  133. rb = torch.min(box1_xy, box2_xy) # [N,2]
  134. inter = (rb - lt).clamp(min=0).prod(-1)
  135. union = area1 + area2 - inter
  136. iou = inter / union
  137. return iou
  138. def box_xywh_inter_union(
  139. boxes1: torch.Tensor, boxes2: torch.Tensor
  140. ) -> Tuple[torch.Tensor, torch.Tensor]:
  141. # Asuumes boxes in xywh format
  142. assert boxes1.size(-1) == 4 and boxes2.size(-1) == 4
  143. boxes1 = box_xywh_to_xyxy(boxes1)
  144. boxes2 = box_xywh_to_xyxy(boxes2)
  145. box1_tl_xy = boxes1[..., :2]
  146. box1_br_xy = boxes1[..., 2:]
  147. box2_tl_xy = boxes2[..., :2]
  148. box2_br_xy = boxes2[..., 2:]
  149. area1 = (box1_br_xy - box1_tl_xy).prod(-1)
  150. area2 = (box2_br_xy - box2_tl_xy).prod(-1)
  151. assert (area1 >= 0).all() and (area2 >= 0).all()
  152. tl = torch.max(box1_tl_xy, box2_tl_xy)
  153. br = torch.min(box1_br_xy, box2_br_xy)
  154. inter = (br - tl).clamp(min=0).prod(-1)
  155. union = area1 + area2 - inter
  156. return inter, union