ciou.py 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127
  1. # Copyright The PyTorch Lightning team.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. from typing import Optional
  15. import torch
  16. from torchmetrics.utilities.imports import _TORCHVISION_AVAILABLE
  17. if not _TORCHVISION_AVAILABLE:
  18. __doctest_skip__ = ["complete_intersection_over_union"]
  19. def _ciou_update(
  20. preds: torch.Tensor, target: torch.Tensor, iou_threshold: Optional[float], replacement_val: float = 0
  21. ) -> torch.Tensor:
  22. if preds.ndim != 2 or preds.shape[-1] != 4:
  23. raise ValueError(f"Expected preds to be of shape (N, 4) but got {preds.shape}")
  24. if target.ndim != 2 or target.shape[-1] != 4:
  25. raise ValueError(f"Expected target to be of shape (N, 4) but got {target.shape}")
  26. from torchvision.ops import complete_box_iou
  27. if preds.numel() == 0: # if no boxes are predicted
  28. return torch.zeros(target.shape[0], target.shape[0], device=target.device, dtype=torch.float32)
  29. if target.numel() == 0: # if no boxes are true
  30. return torch.zeros(preds.shape[0], preds.shape[0], device=preds.device, dtype=torch.float32)
  31. iou = complete_box_iou(preds, target)
  32. if iou_threshold is not None:
  33. iou[iou < iou_threshold] = replacement_val
  34. return iou
  35. def _ciou_compute(iou: torch.Tensor, aggregate: bool = True) -> torch.Tensor:
  36. if not aggregate:
  37. return iou
  38. return iou.diag().mean() if iou.numel() > 0 else torch.tensor(0.0, device=iou.device)
  39. def complete_intersection_over_union(
  40. preds: torch.Tensor,
  41. target: torch.Tensor,
  42. iou_threshold: Optional[float] = None,
  43. replacement_val: float = 0,
  44. aggregate: bool = True,
  45. ) -> torch.Tensor:
  46. r"""Compute Complete Intersection over Union (`CIOU`_) between two sets of boxes.
  47. Both sets of boxes are expected to be in (x1, y1, x2, y2) format with 0 <= x1 < x2 and 0 <= y1 < y2.
  48. Args:
  49. preds:
  50. The input tensor containing the predicted bounding boxes.
  51. target:
  52. The tensor containing the ground truth.
  53. iou_threshold:
  54. Optional IoU thresholds for evaluation. If set to `None` the threshold is ignored.
  55. replacement_val:
  56. Value to replace values under the threshold with.
  57. aggregate:
  58. Return the average value instead of the full matrix of values
  59. Example::
  60. By default iou is aggregated across all box pairs e.g. mean along the diagonal of the IoU matrix:
  61. >>> import torch
  62. >>> from torchmetrics.functional.detection import complete_intersection_over_union
  63. >>> preds = torch.tensor(
  64. ... [
  65. ... [296.55, 93.96, 314.97, 152.79],
  66. ... [328.94, 97.05, 342.49, 122.98],
  67. ... [356.62, 95.47, 372.33, 147.55],
  68. ... ]
  69. ... )
  70. >>> target = torch.tensor(
  71. ... [
  72. ... [300.00, 100.00, 315.00, 150.00],
  73. ... [330.00, 100.00, 350.00, 125.00],
  74. ... [350.00, 100.00, 375.00, 150.00],
  75. ... ]
  76. ... )
  77. >>> complete_intersection_over_union(preds, target)
  78. tensor(0.5790)
  79. Example::
  80. By setting `aggregate=False` the IoU score per prediction and target boxes is returned:
  81. >>> import torch
  82. >>> from torchmetrics.functional.detection import complete_intersection_over_union
  83. >>> preds = torch.tensor(
  84. ... [
  85. ... [296.55, 93.96, 314.97, 152.79],
  86. ... [328.94, 97.05, 342.49, 122.98],
  87. ... [356.62, 95.47, 372.33, 147.55],
  88. ... ]
  89. ... )
  90. >>> target = torch.tensor(
  91. ... [
  92. ... [300.00, 100.00, 315.00, 150.00],
  93. ... [330.00, 100.00, 350.00, 125.00],
  94. ... [350.00, 100.00, 375.00, 150.00],
  95. ... ]
  96. ... )
  97. >>> complete_intersection_over_union(preds, target, aggregate=False)
  98. tensor([[ 0.6883, -0.2072, -0.3352],
  99. [-0.2217, 0.4881, -0.1913],
  100. [-0.3971, -0.1543, 0.5606]])
  101. """
  102. if not _TORCHVISION_AVAILABLE:
  103. raise ModuleNotFoundError(
  104. f"`{complete_intersection_over_union.__name__}` requires that `torchvision` is installed."
  105. " Please install with `pip install torchmetrics[detection]`."
  106. )
  107. iou = _ciou_update(preds, target, iou_threshold, replacement_val)
  108. return _ciou_compute(iou, aggregate)