diou_loss.py 3.3 KB

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