dists.py 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136
  1. # Copyright The 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 Any, Literal, Optional, Sequence, Union
  15. import torch
  16. from torch import Tensor
  17. from torchmetrics.functional.image.dists import _dists_update
  18. from torchmetrics.metric import Metric
  19. from torchmetrics.utilities.imports import _MATPLOTLIB_AVAILABLE, _TORCHVISION_AVAILABLE
  20. from torchmetrics.utilities.plot import _AX_TYPE, _PLOT_OUT_TYPE
  21. if not _MATPLOTLIB_AVAILABLE:
  22. __doctest_skip__ = ["DeepImageStructureAndTextureSimilarity.plot"]
  23. if not _TORCHVISION_AVAILABLE:
  24. __doctest_skip__ = ["DeepImageStructureAndTextureSimilarity", "DeepImageStructureAndTextureSimilarity.plot"]
  25. class DeepImageStructureAndTextureSimilarity(Metric):
  26. """Calculates Deep Image Structure and Texture Similarity (DISTS) score.
  27. The metric is a full-reference image quality assessment (IQA) model that combines sensitivity to structural
  28. distortions (e.g., artifacts due to noise, blur, or compression) with a tolerance of texture resampling
  29. (exchanging the content of a texture region with a new sample of the same texture). The metric is based on
  30. a convolutional neural network (CNN) that transforms the reference and distorted images to a new representation.
  31. Within this representation, a set of measurements are developed that are sufficient to capture the appearance
  32. of a variety of different visual distortions.
  33. As input to ``forward`` and ``update`` the metric accepts the following input
  34. - ``preds`` (:class:`~torch.Tensor`): tensor with images of shape ``(N, 3, H, W)``
  35. - ``target`` (:class:`~torch.Tensor`): tensor with images of shape ``(N, 3, H, W)``
  36. As output of `forward` and `compute` the metric returns the following output
  37. - ``lpips`` (:class:`~torch.Tensor`): returns float scalar tensor with average LPIPS value over samples
  38. Args:
  39. reduction: specifies the reduction to apply to the output.
  40. kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info.
  41. Raises:
  42. ValueError:
  43. If `reduction` is not one of ["mean", "sum"]
  44. Example:
  45. >>> from torch import rand
  46. >>> from torchmetrics.image.dists import DeepImageStructureAndTextureSimilarity
  47. >>> metric = DeepImageStructureAndTextureSimilarity()
  48. >>> preds = rand(10, 3, 100, 100)
  49. >>> target = rand(10, 3, 100, 100)
  50. >>> metric(preds, target)
  51. tensor(0.1882, grad_fn=<CloneBackward0>)
  52. """
  53. score: Tensor
  54. total: Tensor
  55. is_differentiable: bool = True
  56. higher_is_better: bool = False
  57. full_state_update: bool = False
  58. plot_lower_bound: float = 0.0
  59. def __init__(self, reduction: Optional[Literal["mean", "sum"]] = "mean", **kwargs: Any) -> None:
  60. super().__init__(**kwargs)
  61. allowed_reductions = ("mean", "sum")
  62. if reduction not in allowed_reductions:
  63. raise ValueError(f"Argument `reduction` expected to be one of {allowed_reductions} but got {reduction}")
  64. self.reduction = reduction
  65. self.add_state("score", default=torch.tensor(0.0), dist_reduce_fx="sum")
  66. self.add_state("total", default=torch.tensor(0.0), dist_reduce_fx="sum")
  67. def update(self, preds: Tensor, target: Tensor) -> None:
  68. """Update the metric state."""
  69. scores = _dists_update(preds, target)
  70. self.score += scores.sum()
  71. self.total += preds.shape[0]
  72. def compute(self) -> Tensor:
  73. """Computes the DISTS score."""
  74. return self.score / self.total if self.reduction == "mean" else self.score
  75. def plot(
  76. self, val: Optional[Union[Tensor, Sequence[Tensor]]] = None, ax: Optional[_AX_TYPE] = None
  77. ) -> _PLOT_OUT_TYPE:
  78. """Plot a single or multiple values from the metric.
  79. Args:
  80. val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results.
  81. If no value is provided, will automatically call `metric.compute` and plot that result.
  82. ax: An matplotlib axis object. If provided will add plot to that axis
  83. Returns:
  84. Figure and Axes object
  85. Raises:
  86. ModuleNotFoundError:
  87. If `matplotlib` is not installed
  88. .. plot::
  89. :scale: 75
  90. >>> # Example plotting a single value
  91. >>> import torch
  92. >>> from torchmetrics.image.dists import DeepImageStructureAndTextureSimilarity
  93. >>> metric = DeepImageStructureAndTextureSimilarity()
  94. >>> metric.update(torch.rand(10, 3, 100, 100), torch.rand(10, 3, 100, 100))
  95. >>> fig_, ax_ = metric.plot()
  96. .. plot::
  97. :scale: 75
  98. >>> # Example plotting multiple values
  99. >>> import torch
  100. >>> from torchmetrics.image.dists import DeepImageStructureAndTextureSimilarity
  101. >>> metric = DeepImageStructureAndTextureSimilarity()
  102. >>> values = [ ]
  103. >>> for _ in range(3):
  104. ... values.append(metric(torch.rand(10, 3, 100, 100), torch.rand(10, 3, 100, 100)))
  105. >>> fig_, ax_ = metric.plot(values)
  106. """
  107. return self._plot(val, ax)