iou.py 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128
  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__ = ["intersection_over_union"]
  19. def _iou_update(
  20. preds: torch.Tensor, target: torch.Tensor, iou_threshold: Optional[float], replacement_val: float = 0
  21. ) -> torch.Tensor:
  22. """Compute the IoU matrix between two sets of boxes."""
  23. if preds.ndim != 2 or preds.shape[-1] != 4:
  24. raise ValueError(f"Expected preds to be of shape (N, 4) but got {preds.shape}")
  25. if target.ndim != 2 or target.shape[-1] != 4:
  26. raise ValueError(f"Expected target to be of shape (N, 4) but got {target.shape}")
  27. from torchvision.ops import box_iou
  28. if preds.numel() == 0: # if no boxes are predicted
  29. return torch.zeros(target.shape[0], target.shape[0], device=target.device, dtype=torch.float32)
  30. if target.numel() == 0: # if no boxes are true
  31. return torch.zeros(preds.shape[0], preds.shape[0], device=preds.device, dtype=torch.float32)
  32. iou = box_iou(preds, target)
  33. if iou_threshold is not None:
  34. iou[iou < iou_threshold] = replacement_val
  35. return iou
  36. def _iou_compute(iou: torch.Tensor, aggregate: bool = True) -> torch.Tensor:
  37. if not aggregate:
  38. return iou
  39. return iou.diag().mean() if iou.numel() > 0 else torch.tensor(0.0, device=iou.device)
  40. def intersection_over_union(
  41. preds: torch.Tensor,
  42. target: torch.Tensor,
  43. iou_threshold: Optional[float] = None,
  44. replacement_val: float = 0,
  45. aggregate: bool = True,
  46. ) -> torch.Tensor:
  47. r"""Compute Intersection over Union between two sets of boxes.
  48. Both sets of boxes are expected to be in (x1, y1, x2, y2) format with 0 <= x1 < x2 and 0 <= y1 < y2.
  49. Args:
  50. preds:
  51. The input tensor containing the predicted bounding boxes.
  52. target:
  53. The tensor containing the ground truth.
  54. iou_threshold:
  55. Optional IoU thresholds for evaluation. If set to `None` the threshold is ignored.
  56. replacement_val:
  57. Value to replace values under the threshold with.
  58. aggregate:
  59. Return the average value instead of the full matrix of values
  60. Example::
  61. By default iou is aggregated across all box pairs e.g. mean along the diagonal of the IoU matrix:
  62. >>> import torch
  63. >>> from torchmetrics.functional.detection import intersection_over_union
  64. >>> preds = torch.tensor(
  65. ... [
  66. ... [296.55, 93.96, 314.97, 152.79],
  67. ... [328.94, 97.05, 342.49, 122.98],
  68. ... [356.62, 95.47, 372.33, 147.55],
  69. ... ]
  70. ... )
  71. >>> target = torch.tensor(
  72. ... [
  73. ... [300.00, 100.00, 315.00, 150.00],
  74. ... [330.00, 100.00, 350.00, 125.00],
  75. ... [350.00, 100.00, 375.00, 150.00],
  76. ... ]
  77. ... )
  78. >>> intersection_over_union(preds, target)
  79. tensor(0.5879)
  80. Example::
  81. By setting `aggregate=False` the full IoU matrix is returned:
  82. >>> import torch
  83. >>> from torchmetrics.functional.detection import intersection_over_union
  84. >>> preds = torch.tensor(
  85. ... [
  86. ... [296.55, 93.96, 314.97, 152.79],
  87. ... [328.94, 97.05, 342.49, 122.98],
  88. ... [356.62, 95.47, 372.33, 147.55],
  89. ... ]
  90. ... )
  91. >>> target = torch.tensor(
  92. ... [
  93. ... [300.00, 100.00, 315.00, 150.00],
  94. ... [330.00, 100.00, 350.00, 125.00],
  95. ... [350.00, 100.00, 375.00, 150.00],
  96. ... ]
  97. ... )
  98. >>> intersection_over_union(preds, target, aggregate=False)
  99. tensor([[0.6898, 0.0000, 0.0000],
  100. [0.0000, 0.5086, 0.0000],
  101. [0.0000, 0.0000, 0.5654]])
  102. """
  103. if not _TORCHVISION_AVAILABLE:
  104. raise ModuleNotFoundError(
  105. f"`{intersection_over_union.__name__}` requires that `torchvision` is installed."
  106. " Please install with `pip install torchmetrics[detection]`."
  107. )
  108. iou = _iou_update(preds, target, iou_threshold, replacement_val)
  109. return _iou_compute(iou, aggregate)