diou_loss.py 3.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. import torch
  2. from ..utils import _log_api_usage_once
  3. from ._utils import _loss_inter_union, _upcast_non_float
  4. def distance_box_iou_loss(
  5. boxes1: torch.Tensor,
  6. boxes2: torch.Tensor,
  7. reduction: str = "none",
  8. eps: float = 1e-7,
  9. ) -> torch.Tensor:
  10. """
  11. Gradient-friendly IoU loss with an additional penalty that is non-zero when the
  12. distance between boxes' centers isn't zero. Indeed, for two exactly overlapping
  13. boxes, the distance IoU is the same as the IoU loss.
  14. This loss is symmetric, so the boxes1 and boxes2 arguments are interchangeable.
  15. Both sets of boxes are expected to be in ``(x1, y1, x2, y2)`` format with
  16. ``0 <= x1 < x2`` and ``0 <= y1 < y2``, and The two boxes should have the
  17. same dimensions.
  18. Args:
  19. boxes1 (Tensor[N, 4]): first set of boxes
  20. boxes2 (Tensor[N, 4]): second set of boxes
  21. reduction (string, optional): Specifies the reduction to apply to the output:
  22. ``'none'`` | ``'mean'`` | ``'sum'``. ``'none'``: No reduction will be
  23. applied to the output. ``'mean'``: The output will be averaged.
  24. ``'sum'``: The output will be summed. Default: ``'none'``
  25. eps (float, optional): small number to prevent division by zero. Default: 1e-7
  26. Returns:
  27. Tensor: Loss tensor with the reduction option applied.
  28. Reference:
  29. Zhaohui Zheng et al.: Distance Intersection over Union Loss:
  30. https://arxiv.org/abs/1911.08287
  31. """
  32. # Original Implementation from https://github.com/facebookresearch/detectron2/blob/main/detectron2/layers/losses.py
  33. if not torch.jit.is_scripting() and not torch.jit.is_tracing():
  34. _log_api_usage_once(distance_box_iou_loss)
  35. boxes1 = _upcast_non_float(boxes1)
  36. boxes2 = _upcast_non_float(boxes2)
  37. loss, _ = _diou_iou_loss(boxes1, boxes2, eps)
  38. # Check reduction option and return loss accordingly
  39. if reduction == "none":
  40. pass
  41. elif reduction == "mean":
  42. loss = loss.mean() if loss.numel() > 0 else 0.0 * loss.sum()
  43. elif reduction == "sum":
  44. loss = loss.sum()
  45. else:
  46. raise ValueError(
  47. f"Invalid Value for arg 'reduction': '{reduction} \n Supported reduction modes: 'none', 'mean', 'sum'"
  48. )
  49. return loss
  50. def _diou_iou_loss(
  51. boxes1: torch.Tensor,
  52. boxes2: torch.Tensor,
  53. eps: float = 1e-7,
  54. ) -> tuple[torch.Tensor, torch.Tensor]:
  55. intsct, union = _loss_inter_union(boxes1, boxes2)
  56. iou = intsct / (union + eps)
  57. # smallest enclosing box
  58. x1, y1, x2, y2 = boxes1.unbind(dim=-1)
  59. x1g, y1g, x2g, y2g = boxes2.unbind(dim=-1)
  60. xc1 = torch.min(x1, x1g)
  61. yc1 = torch.min(y1, y1g)
  62. xc2 = torch.max(x2, x2g)
  63. yc2 = torch.max(y2, y2g)
  64. # The diagonal distance of the smallest enclosing box squared
  65. diagonal_distance_squared = ((xc2 - xc1) ** 2) + ((yc2 - yc1) ** 2) + eps
  66. # centers of boxes
  67. x_p = (x2 + x1) / 2
  68. y_p = (y2 + y1) / 2
  69. x_g = (x1g + x2g) / 2
  70. y_g = (y1g + y2g) / 2
  71. # The distance between boxes' centers squared.
  72. centers_distance_squared = ((x_p - x_g) ** 2) + ((y_p - y_g) ** 2)
  73. # The distance IoU is the IoU penalized by a normalized
  74. # distance between boxes' centers squared.
  75. loss = 1 - iou + (centers_distance_squared / diagonal_distance_squared)
  76. return loss, iou