psnrb.py 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142
  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. import math
  15. from typing import Union
  16. import torch
  17. from torch import Tensor, tensor
  18. def _compute_bef(x: Tensor, block_size: int = 8) -> Tensor:
  19. """Compute block effect.
  20. Args:
  21. x: input image
  22. block_size: integer indication the block size
  23. Returns:
  24. Computed block effect
  25. Raises:
  26. ValueError:
  27. If the image is not a grayscale image
  28. """
  29. (
  30. _,
  31. channels,
  32. height,
  33. width,
  34. ) = x.shape
  35. if channels > 1:
  36. raise ValueError(f"`psnrb` metric expects grayscale images, but got images with {channels} channels.")
  37. h = torch.arange(width - 1)
  38. h_b = torch.tensor(range(block_size - 1, width - 1, block_size))
  39. h_bc = torch.tensor(list(set(h.tolist()).symmetric_difference(h_b.tolist())))
  40. v = torch.arange(height - 1)
  41. v_b = torch.tensor(range(block_size - 1, height - 1, block_size))
  42. v_bc = torch.tensor(list(set(v.tolist()).symmetric_difference(v_b.tolist())))
  43. d_b = (x[:, :, :, h_b] - x[:, :, :, h_b + 1]).pow(2.0).sum()
  44. d_bc = (x[:, :, :, h_bc] - x[:, :, :, h_bc + 1]).pow(2.0).sum()
  45. d_b += (x[:, :, v_b, :] - x[:, :, v_b + 1, :]).pow(2.0).sum()
  46. d_bc += (x[:, :, v_bc, :] - x[:, :, v_bc + 1, :]).pow(2.0).sum()
  47. n_hb = height * (width / block_size) - 1
  48. n_hbc = (height * (width - 1)) - n_hb
  49. n_vb = width * (height / block_size) - 1
  50. n_vbc = (width * (height - 1)) - n_vb
  51. d_b /= n_hb + n_vb
  52. d_bc /= n_hbc + n_vbc
  53. t = math.log2(block_size) / math.log2(min(height, width)) if d_b > d_bc else 0
  54. return t * (d_b - d_bc)
  55. def _psnrb_compute(
  56. sum_squared_error: Tensor,
  57. bef: Tensor,
  58. num_obs: Tensor,
  59. data_range: Tensor,
  60. ) -> Tensor:
  61. """Computes peak signal-to-noise ratio.
  62. Args:
  63. sum_squared_error: Sum of square of errors over all observations
  64. bef: block effect
  65. num_obs: Number of predictions or observations
  66. data_range: the range of the data.
  67. """
  68. sum_squared_error = sum_squared_error / num_obs + bef
  69. return 10 * torch.log10(data_range**2 / sum_squared_error)
  70. def _psnrb_update(preds: Tensor, target: Tensor, block_size: int = 8) -> tuple[Tensor, Tensor, Tensor]:
  71. """Updates and returns variables required to compute peak signal-to-noise ratio.
  72. Args:
  73. preds: Predicted tensor
  74. target: Ground truth tensor
  75. block_size: Integer indication the block size
  76. """
  77. sum_squared_error = torch.sum(torch.pow(preds - target, 2))
  78. num_obs = tensor(target.numel(), device=target.device)
  79. bef = _compute_bef(preds, block_size=block_size)
  80. return sum_squared_error, bef, num_obs
  81. def peak_signal_noise_ratio_with_blocked_effect(
  82. preds: Tensor,
  83. target: Tensor,
  84. data_range: Union[float, tuple[float, float]],
  85. block_size: int = 8,
  86. ) -> Tensor:
  87. r"""Computes `Peak Signal to Noise Ratio With Blocked Effect` (PSNRB) metrics.
  88. .. math::
  89. \text{PSNRB}(I, J) = 10 * \log_{10} \left(\frac{\max(I)^2}{\text{MSE}(I, J)-\text{B}(I, J)}\right)
  90. Where :math:`\text{MSE}` denotes the `mean-squared-error`_ function.
  91. Args:
  92. preds: estimated signal
  93. target: ground truth signal
  94. data_range: the range of the data. If a tuple is provided then the range is calculated as the difference and
  95. input is clamped between the values.
  96. block_size: integer indication the block size
  97. Return:
  98. Tensor with PSNRB score
  99. Example:
  100. >>> from torch import rand
  101. >>> from torchmetrics.functional.image import peak_signal_noise_ratio_with_blocked_effect
  102. >>> preds = rand(1, 1, 28, 28)
  103. >>> target = rand(1, 1, 28, 28)
  104. >>> peak_signal_noise_ratio_with_blocked_effect(preds, target, data_range=1.0)
  105. tensor(7.8402)
  106. """
  107. if isinstance(data_range, tuple):
  108. preds = torch.clamp(preds, min=data_range[0], max=data_range[1])
  109. target = torch.clamp(target, min=data_range[0], max=data_range[1])
  110. data_range_val = tensor(data_range[1] - data_range[0])
  111. else:
  112. data_range_val = tensor(float(data_range))
  113. sum_squared_error, bef, num_obs = _psnrb_update(preds, target, block_size=block_size)
  114. return _psnrb_compute(sum_squared_error, bef, num_obs, data_range_val)