iou.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  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 collections.abc import Sequence
  15. from typing import Any, List, Optional, Union
  16. import torch
  17. from torch import Tensor
  18. from torchmetrics.detection.helpers import _fix_empty_tensors, _input_validator
  19. from torchmetrics.functional.detection.iou import _iou_compute, _iou_update
  20. from torchmetrics.metric import Metric
  21. from torchmetrics.utilities.data import dim_zero_cat
  22. from torchmetrics.utilities.imports import _MATPLOTLIB_AVAILABLE, _TORCHVISION_AVAILABLE
  23. from torchmetrics.utilities.plot import _AX_TYPE, _PLOT_OUT_TYPE
  24. if not _TORCHVISION_AVAILABLE:
  25. __doctest_skip__ = ["IntersectionOverUnion", "IntersectionOverUnion.plot"]
  26. elif not _MATPLOTLIB_AVAILABLE:
  27. __doctest_skip__ = ["IntersectionOverUnion.plot"]
  28. class IntersectionOverUnion(Metric):
  29. r"""Computes Intersection Over Union (IoU).
  30. As input to ``forward`` and ``update`` the metric accepts the following input:
  31. - ``preds`` (:class:`~List`): A list consisting of dictionaries each containing the key-values
  32. (each dictionary corresponds to a single image). Parameters that should be provided per dict:
  33. - ``boxes`` (:class:`~torch.Tensor`): float tensor of shape ``(num_boxes, 4)`` containing ``num_boxes``
  34. detection boxes of the format specified in the constructor.
  35. By default, this method expects ``(xmin, ymin, xmax, ymax)`` in absolute image coordinates.
  36. - labels: ``IntTensor`` of shape ``(num_boxes)`` containing 0-indexed detection classes for
  37. the boxes.
  38. - ``target`` (:class:`~List`): A list consisting of dictionaries each containing the key-values
  39. (each dictionary corresponds to a single image). Parameters that should be provided per dict:
  40. - ``boxes`` (:class:`~torch.Tensor`): float tensor of shape ``(num_boxes, 4)`` containing ``num_boxes`` ground
  41. truth boxes of the format specified in the constructor.
  42. By default, this method expects ``(xmin, ymin, xmax, ymax)`` in absolute image coordinates.
  43. - ``labels`` (:class:`~torch.Tensor`): integer tensor of shape ``(num_boxes)`` containing 0-indexed ground truth
  44. classes for the boxes.
  45. As output of ``forward`` and ``compute`` the metric returns the following output:
  46. - ``iou_dict``: A dictionary containing the following key-values:
  47. - iou: (:class:`~torch.Tensor`)
  48. - iou/cl_{cl}: (:class:`~torch.Tensor`), if argument ``class metrics=True``
  49. Args:
  50. box_format:
  51. Input format of given boxes. Supported formats are ``[`xyxy`, `xywh`, `cxcywh`]``.
  52. iou_thresholds:
  53. Optional IoU thresholds for evaluation. If set to `None` the threshold is ignored.
  54. class_metrics:
  55. Option to enable per-class metrics for IoU. Has a performance impact.
  56. respect_labels:
  57. Ignore values from boxes that do not have the same label as the ground truth box. Else will compute Iou
  58. between all pairs of boxes.
  59. kwargs:
  60. Additional keyword arguments, see :ref:`Metric kwargs` for more info.
  61. Example::
  62. >>> import torch
  63. >>> from torchmetrics.detection import IntersectionOverUnion
  64. >>> preds = [
  65. ... {
  66. ... "boxes": torch.tensor([
  67. ... [296.55, 93.96, 314.97, 152.79],
  68. ... [298.55, 98.96, 314.97, 151.79]]),
  69. ... "labels": torch.tensor([4, 5]),
  70. ... }
  71. ... ]
  72. >>> target = [
  73. ... {
  74. ... "boxes": torch.tensor([[300.00, 100.00, 315.00, 150.00]]),
  75. ... "labels": torch.tensor([5]),
  76. ... }
  77. ... ]
  78. >>> metric = IntersectionOverUnion()
  79. >>> metric(preds, target)
  80. {'iou': tensor(0.8614)}
  81. Example::
  82. The metric can also return the score per class:
  83. >>> import torch
  84. >>> from torchmetrics.detection import IntersectionOverUnion
  85. >>> preds = [
  86. ... {
  87. ... "boxes": torch.tensor([
  88. ... [296.55, 93.96, 314.97, 152.79],
  89. ... [298.55, 98.96, 314.97, 151.79]]),
  90. ... "labels": torch.tensor([4, 5]),
  91. ... }
  92. ... ]
  93. >>> target = [
  94. ... {
  95. ... "boxes": torch.tensor([
  96. ... [300.00, 100.00, 315.00, 150.00],
  97. ... [300.00, 100.00, 315.00, 150.00]
  98. ... ]),
  99. ... "labels": torch.tensor([4, 5]),
  100. ... }
  101. ... ]
  102. >>> metric = IntersectionOverUnion(class_metrics=True)
  103. >>> metric(preds, target)
  104. {'iou': tensor(0.7756), 'iou/cl_4': tensor(0.6898), 'iou/cl_5': tensor(0.8614)}
  105. Raises:
  106. ModuleNotFoundError:
  107. If torchvision is not installed with version 0.8.0 or newer.
  108. """
  109. is_differentiable: bool = False
  110. higher_is_better: Optional[bool] = True
  111. full_state_update: bool = True
  112. groundtruth_labels: List[Tensor]
  113. pred_labels: List[Tensor]
  114. iou_matrix: List[Tensor]
  115. _iou_type: str = "iou"
  116. _invalid_val: float = -1.0
  117. def __init__(
  118. self,
  119. box_format: str = "xyxy",
  120. iou_threshold: Optional[float] = None,
  121. class_metrics: bool = False,
  122. respect_labels: bool = True,
  123. **kwargs: Any,
  124. ) -> None:
  125. super().__init__(**kwargs)
  126. if not _TORCHVISION_AVAILABLE:
  127. raise ModuleNotFoundError(
  128. f"Metric `{self._iou_type.upper()}` requires that `torchvision` is installed."
  129. " Please install with `pip install torchmetrics[detection]`."
  130. )
  131. allowed_box_formats = ("xyxy", "xywh", "cxcywh")
  132. if box_format not in allowed_box_formats:
  133. raise ValueError(f"Expected argument `box_format` to be one of {allowed_box_formats} but got {box_format}")
  134. self.box_format = box_format
  135. self.iou_threshold = iou_threshold
  136. if not isinstance(class_metrics, bool):
  137. raise ValueError("Expected argument `class_metrics` to be a boolean")
  138. self.class_metrics = class_metrics
  139. if not isinstance(respect_labels, bool):
  140. raise ValueError("Expected argument `respect_labels` to be a boolean")
  141. self.respect_labels = respect_labels
  142. self.add_state("groundtruth_labels", default=[], dist_reduce_fx=None)
  143. self.add_state("pred_labels", default=[], dist_reduce_fx=None)
  144. self.add_state("iou_matrix", default=[], dist_reduce_fx=None)
  145. @staticmethod
  146. def _iou_update_fn(*args: Any, **kwargs: Any) -> Tensor:
  147. return _iou_update(*args, **kwargs)
  148. @staticmethod
  149. def _iou_compute_fn(*args: Any, **kwargs: Any) -> Tensor:
  150. return _iou_compute(*args, **kwargs)
  151. def update(self, preds: list[dict[str, Tensor]], target: list[dict[str, Tensor]]) -> None:
  152. """Update state with predictions and targets."""
  153. _input_validator(preds, target, ignore_score=True)
  154. for p_i, t_i in zip(preds, target):
  155. det_boxes = self._get_safe_item_values(p_i["boxes"])
  156. gt_boxes = self._get_safe_item_values(t_i["boxes"])
  157. self.groundtruth_labels.append(t_i["labels"])
  158. self.pred_labels.append(p_i["labels"])
  159. iou_matrix = self._iou_update_fn(det_boxes, gt_boxes, self.iou_threshold, self._invalid_val) # N x M
  160. if self.respect_labels:
  161. if det_boxes.numel() > 0 and gt_boxes.numel() > 0:
  162. label_eq = p_i["labels"].unsqueeze(1) == t_i["labels"].unsqueeze(0) # N x M
  163. else:
  164. label_eq = torch.eye(iou_matrix.shape[0], dtype=bool, device=iou_matrix.device) # type: ignore[call-overload]
  165. iou_matrix[~label_eq] = self._invalid_val
  166. self.iou_matrix.append(iou_matrix)
  167. def _get_safe_item_values(self, boxes: Tensor) -> Tensor:
  168. from torchvision.ops import box_convert
  169. boxes = _fix_empty_tensors(boxes)
  170. if boxes.numel() > 0:
  171. boxes = box_convert(boxes, in_fmt=self.box_format, out_fmt="xyxy")
  172. return boxes
  173. def _get_gt_classes(self) -> list:
  174. """Returns a list of unique classes found in ground truth and detection data."""
  175. if len(self.groundtruth_labels) > 0:
  176. return torch.cat(self.groundtruth_labels).unique().tolist()
  177. return []
  178. def compute(self) -> dict:
  179. """Computes IoU based on inputs passed in to ``update`` previously."""
  180. # compute global IoU score using only valid values.
  181. valid_matrices = [
  182. mat[mat != self._invalid_val] for mat in self.iou_matrix if torch.any(mat != self._invalid_val)
  183. ]
  184. score = torch.cat(valid_matrices, 0).mean() if valid_matrices else torch.tensor(0.0, device=self.device)
  185. results: dict[str, Tensor] = {f"{self._iou_type}": score}
  186. if torch.isnan(score): # if no valid boxes are found
  187. results[f"{self._iou_type}"] = torch.tensor(0.0, device=score.device)
  188. if self.class_metrics:
  189. # union of ground truth and predicted labels
  190. all_labels = dim_zero_cat([dim_zero_cat(self.groundtruth_labels), dim_zero_cat(self.pred_labels)])
  191. classes = all_labels.unique().tolist() if all_labels.numel() > 0 else []
  192. for cl in classes:
  193. masked_iou = torch.zeros_like(score)
  194. observed = torch.zeros_like(score)
  195. for mat, gt_lab in zip(self.iou_matrix, self.groundtruth_labels):
  196. scores = mat[:, gt_lab == cl]
  197. valid_scores = scores[scores != self._invalid_val]
  198. masked_iou += valid_scores.sum()
  199. observed += valid_scores.numel()
  200. # return 0.0 if no valid scores are observed.
  201. if observed.item() == 0:
  202. results.update({f"{self._iou_type}/cl_{cl}": torch.tensor(0.0, device=score.device)})
  203. else:
  204. results.update({f"{self._iou_type}/cl_{cl}": masked_iou / observed})
  205. return results
  206. def plot(
  207. self, val: Optional[Union[Tensor, Sequence[Tensor]]] = None, ax: Optional[_AX_TYPE] = None
  208. ) -> _PLOT_OUT_TYPE:
  209. """Plot a single or multiple values from the metric.
  210. Args:
  211. val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results.
  212. If no value is provided, will automatically call `metric.compute` and plot that result.
  213. ax: An matplotlib axis object. If provided will add plot to that axis
  214. Returns:
  215. Figure object and Axes object
  216. Raises:
  217. ModuleNotFoundError:
  218. If `matplotlib` is not installed
  219. .. plot::
  220. :scale: 75
  221. >>> import torch
  222. >>> from torchmetrics.detection import IntersectionOverUnion
  223. >>> preds = [
  224. ... {
  225. ... "boxes": torch.tensor([[296.55, 93.96, 314.97, 152.79], [298.55, 98.96, 314.97, 151.79]]),
  226. ... "scores": torch.tensor([0.236, 0.56]),
  227. ... "labels": torch.tensor([4, 5]),
  228. ... }
  229. ... ]
  230. >>> target = [
  231. ... {
  232. ... "boxes": torch.tensor([[300.00, 100.00, 315.00, 150.00]]),
  233. ... "labels": torch.tensor([5]),
  234. ... }
  235. ... ]
  236. >>> metric = IntersectionOverUnion()
  237. >>> metric.update(preds, target)
  238. >>> fig_, ax_ = metric.plot()
  239. .. plot::
  240. :scale: 75
  241. >>> # Example plotting multiple values
  242. >>> import torch
  243. >>> from torchmetrics.detection import IntersectionOverUnion
  244. >>> preds = [
  245. ... {
  246. ... "boxes": torch.tensor([[296.55, 93.96, 314.97, 152.79], [298.55, 98.96, 314.97, 151.79]]),
  247. ... "scores": torch.tensor([0.236, 0.56]),
  248. ... "labels": torch.tensor([4, 5]),
  249. ... }
  250. ... ]
  251. >>> target = lambda : [
  252. ... {
  253. ... "boxes": torch.tensor([[300.00, 100.00, 315.00, 150.00]]) + torch.randint(-10, 10, (1, 4)),
  254. ... "labels": torch.tensor([5]),
  255. ... }
  256. ... ]
  257. >>> metric = IntersectionOverUnion()
  258. >>> vals = []
  259. >>> for _ in range(20):
  260. ... vals.append(metric(preds, target()))
  261. >>> fig_, ax_ = metric.plot(vals)
  262. """
  263. return self._plot(val, ax)