Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

Add disparity evaluation metrics (#3743)

Leonardo Vanni51647e688162
diff --git a/docs/source/metrics.rst b/docs/source/metrics.rst
index 75c607bac..58b481cae 100644
--- a/docs/source/metrics.rst
+++ b/docs/source/metrics.rst
@@ -41,6 +41,13 @@ Optical Flow
.. autofunction:: aepe
.. autoclass:: AEPE
+Stereo
+------
+
+.. autofunction:: mean_absolute_disparity_error
+.. autofunction:: root_mean_squared_disparity_error
+.. autofunction:: mean_bad_pixel_error
+
Monitoring
----------
diff --git a/kornia/metrics/__init__.py b/kornia/metrics/__init__.py
index 839ad1653..212745796 100644
--- a/kornia/metrics/__init__.py
+++ b/kornia/metrics/__init__.py
@@ -18,12 +18,13 @@
"""Metrics submodule for Kornia.
This package provides evaluation metrics for computer vision, such as accuracy, mean IoU,
-PSNR, SSIM, and endpoint error.
+PSNR, SSIM, endpoint error, and stereo disparity error.
"""
from .accuracy import accuracy
from .average_meter import AverageMeter
from .confusion_matrix import confusion_matrix
+from .disparity import mean_absolute_disparity_error, mean_bad_pixel_error, root_mean_squared_disparity_error
from .endpoint_error import AEPE, aepe, average_endpoint_error
from .mean_average_precision import mean_average_precision
from .mean_iou import mean_iou, mean_iou_bbox
@@ -40,10 +41,13 @@ __all__ = [
"aepe",
"average_endpoint_error",
"confusion_matrix",
+ "mean_absolute_disparity_error",
"mean_average_precision",
+ "mean_bad_pixel_error",
"mean_iou",
"mean_iou_bbox",
"psnr",
+ "root_mean_squared_disparity_error",
"ssim",
"ssim3d",
]
diff --git a/kornia/metrics/disparity.py b/kornia/metrics/disparity.py
new file mode 100644
index 000000000..d3e20ed1b
--- /dev/null
+++ b/kornia/metrics/disparity.py
@@ -0,0 +1,222 @@
+# LICENSE HEADER MANAGED BY add-license-header
+#
+# Copyright 2018 Kornia Team
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+from typing import Optional
+
+import torch
+
+from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SAME_SHAPE
+
+
+def _is_broadcastable_to(shape: torch.Size, target_shape: torch.Size) -> bool:
+ """Check whether ``shape`` can be broadcast to ``target_shape``."""
+ if len(shape) > len(target_shape):
+ return False
+ return all(s in (1, t) for s, t in zip(reversed(shape), reversed(target_shape), strict=False))
+
+
+def _check_disparity_inputs(
+ input: torch.Tensor, target: torch.Tensor, valid_mask: Optional[torch.Tensor]
+) -> Optional[torch.Tensor]:
+ """Validate disparity metric inputs and return the valid mask broadcast to the input shape."""
+ KORNIA_CHECK_IS_TENSOR(input)
+ KORNIA_CHECK_IS_TENSOR(target)
+ KORNIA_CHECK_SAME_SHAPE(input, target)
+
+ if valid_mask is None:
+ return None
+
+ KORNIA_CHECK_IS_TENSOR(valid_mask)
+ KORNIA_CHECK(
+ _is_broadcastable_to(valid_mask.shape, input.shape),
+ f"valid_mask shape must be broadcastable to the input shape. Got: {valid_mask.shape} and {input.shape}",
+ )
+
+ return valid_mask.to(torch.bool).broadcast_to(input.shape)
+
+
+def _reduce_disparity_error(error: torch.Tensor, valid_mask: Optional[torch.Tensor], reduction: str) -> torch.Tensor:
+ """Reduce a per-pixel error map over the valid pixels according to ``reduction``."""
+ if reduction == "mean":
+ error = error.mean() if valid_mask is None else error[valid_mask].mean()
+ elif reduction == "sum":
+ error = error.sum() if valid_mask is None else error[valid_mask].sum()
+ elif reduction == "none":
+ if valid_mask is not None:
+ error = torch.where(valid_mask, error, torch.zeros_like(error))
+ else:
+ raise NotImplementedError("Invalid reduction option.")
+
+ return error
+
+
+def mean_absolute_disparity_error(
+ input: torch.Tensor,
+ target: torch.Tensor,
+ valid_mask: Optional[torch.Tensor] = None,
+ reduction: str = "mean",
+) -> torch.Tensor:
+ r"""Compute the mean absolute error (MAE) between two disparity maps.
+
+ Given predicted and ground truth disparity maps :math:`D` and :math:`D^{gt}` with
+ valid pixels :math:`\mathcal{V}`, the metric is:
+
+ .. math::
+
+ \text{MAE}(D, D^{gt}) = \frac{1}{|\mathcal{V}|}\sum_{p \in \mathcal{V}} |D_{p} - D^{gt}_{p}|
+
+ Args:
+ input: the predicted disparity map with arbitrary shape :math:`(*)`.
+ target: the ground truth disparity map with the same shape as ``input``.
+ valid_mask: optional mask broadcastable to the shape of ``input``, where nonzero
+ (``True``) values mark the pixels to evaluate. Non-boolean masks are converted
+ to boolean. If ``None``, all pixels are evaluated.
+ reduction: specifies the reduction to apply to the output:
+ ``'none'`` | ``'mean'`` | ``'sum'``. ``'mean'``: the error is averaged over the
+ valid pixels, ``'sum'``: the error is summed over the valid pixels, ``'none'``: no
+ reduction will be applied and the per-pixel error map is returned, with masked-out
+ positions set to zero.
+
+ Return:
+ the computed metric as a scalar, or the per-pixel error map if ``reduction='none'``.
+
+ Note:
+ If ``valid_mask`` selects no pixels, ``'mean'`` reduction returns ``nan``.
+
+ Examples:
+ >>> input = torch.tensor([[0.0, 1.0], [2.0, 3.0]])
+ >>> target = torch.tensor([[0.0, 1.0], [2.0, 4.0]])
+ >>> mean_absolute_disparity_error(input, target)
+ tensor(0.2500)
+ >>> valid_mask = torch.tensor([[True, True], [True, False]])
+ >>> mean_absolute_disparity_error(input, target, valid_mask)
+ tensor(0.)
+
+ Reference:
+ D. Scharstein and R. Szeliski. A taxonomy and evaluation of dense two-frame stereo
+ correspondence algorithms. IJCV 2002. https://vision.middlebury.edu/stereo/taxonomy-IJCV.pdf
+
+ """
+ mask = _check_disparity_inputs(input, target, valid_mask)
+ error = (input - target).abs()
+ return _reduce_disparity_error(error, mask, reduction)
+
+
+def root_mean_squared_disparity_error(
+ input: torch.Tensor,
+ target: torch.Tensor,
+ valid_mask: Optional[torch.Tensor] = None,
+ reduction: str = "mean",
+) -> torch.Tensor:
+ r"""Compute the root mean squared error (RMSE) between two disparity maps.
+
+ Given predicted and ground truth disparity maps :math:`D` and :math:`D^{gt}` with
+ valid pixels :math:`\mathcal{V}`, the metric is:
+
+ .. math::
+
+ \text{RMSE}(D, D^{gt}) =
+ \sqrt{\frac{1}{|\mathcal{V}|}\sum_{p \in \mathcal{V}} (D_{p} - D^{gt}_{p})^{2}}
+
+ Args:
+ input: the predicted disparity map with arbitrary shape :math:`(*)`.
+ target: the ground truth disparity map with the same shape as ``input``.
+ valid_mask: optional mask broadcastable to the shape of ``input``, where nonzero
+ (``True``) values mark the pixels to evaluate. Non-boolean masks are converted
+ to boolean. If ``None``, all pixels are evaluated.
+ reduction: specifies the reduction to apply to the squared error before the square
+ root: ``'none'`` | ``'mean'`` | ``'sum'``. ``'mean'``: the squared error is
+ averaged over the valid pixels, ``'sum'``: the squared error is summed over the
+ valid pixels, ``'none'``: no reduction will be applied and the per-pixel absolute
+ error map is returned, with masked-out positions set to zero.
+
+ Return:
+ the computed metric as a scalar, or the per-pixel error map if ``reduction='none'``.
+
+ Note:
+ If ``valid_mask`` selects no pixels, ``'mean'`` reduction returns ``nan``.
+
+ Examples:
+ >>> input = torch.zeros(2, 2)
+ >>> target = torch.tensor([[0.0, 0.0], [0.0, 1.0]])
+ >>> root_mean_squared_disparity_error(input, target)
+ tensor(0.5000)
+
+ Reference:
+ D. Scharstein and R. Szeliski. A taxonomy and evaluation of dense two-frame stereo
+ correspondence algorithms. IJCV 2002. https://vision.middlebury.edu/stereo/taxonomy-IJCV.pdf
+
+ """
+ mask = _check_disparity_inputs(input, target, valid_mask)
+ error = (input - target) ** 2
+ return _reduce_disparity_error(error, mask, reduction).sqrt()
+
+
+def mean_bad_pixel_error(
+ input: torch.Tensor,
+ target: torch.Tensor,
+ threshold: float = 3.0,
+ valid_mask: Optional[torch.Tensor] = None,
+ reduction: str = "mean",
+) -> torch.Tensor:
+ r"""Compute the bad pixel ratio between two disparity maps.
+
+ A pixel is considered bad when its absolute disparity error is strictly greater than
+ ``threshold``. Given predicted and ground truth disparity maps :math:`D` and :math:`D^{gt}`
+ with valid pixels :math:`\mathcal{V}`, the metric is:
+
+ .. math::
+
+ \text{Bad}_{\tau}(D, D^{gt}) =
+ \frac{1}{|\mathcal{V}|}\sum_{p \in \mathcal{V}} [|D_{p} - D^{gt}_{p}| > \tau]
+
+ This corresponds to the bad-pixel percentage reported by the Middlebury and KITTI stereo
+ benchmarks, expressed as a fraction in :math:`[0, 1]` instead of a percentage.
+
+ Args:
+ input: the predicted disparity map with arbitrary shape :math:`(*)`.
+ target: the ground truth disparity map with the same shape as ``input``.
+ threshold: the disparity error above which a pixel is considered bad.
+ valid_mask: optional mask broadcastable to the shape of ``input``, where nonzero
+ (``True``) values mark the pixels to evaluate. Non-boolean masks are converted
+ to boolean. If ``None``, all pixels are evaluated.
+ reduction: specifies the reduction to apply to the output:
+ ``'none'`` | ``'mean'`` | ``'sum'``. ``'mean'``: the fraction of bad pixels among
+ the valid pixels, ``'sum'``: the number of bad pixels among the valid pixels,
+ ``'none'``: no reduction will be applied and the per-pixel bad-pixel map is
+ returned, with masked-out positions set to zero.
+
+ Return:
+ the computed metric as a scalar, or the per-pixel bad-pixel map if ``reduction='none'``.
+
+ Note:
+ If ``valid_mask`` selects no pixels, ``'mean'`` reduction returns ``nan``.
+
+ Examples:
+ >>> input = torch.zeros(2, 2)
+ >>> target = torch.tensor([[0.0, 1.0], [2.0, 4.0]])
+ >>> mean_bad_pixel_error(input, target, threshold=1.5)
+ tensor(0.5000)
+
+ Reference:
+ D. Scharstein and R. Szeliski. A taxonomy and evaluation of dense two-frame stereo
+ correspondence algorithms. IJCV 2002. https://vision.middlebury.edu/stereo/taxonomy-IJCV.pdf
+
+ """
+ mask = _check_disparity_inputs(input, target, valid_mask)
+ bad = ((input - target).abs() > threshold).to(input.dtype)
+ return _reduce_disparity_error(bad, mask, reduction)
diff --git a/tests/metrics/test_disparity.py b/tests/metrics/test_disparity.py
new file mode 100644
index 000000000..2a74baae6
--- /dev/null
+++ b/tests/metrics/test_disparity.py
@@ -0,0 +1,248 @@
+# LICENSE HEADER MANAGED BY add-license-header
+#
+# Copyright 2018 Kornia Team
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+import pytest
+import torch
+
+import kornia
+from kornia.core.exceptions import BaseError, ShapeError, TypeCheckError
+
+from testing.base import BaseTester
+
+
+class TestMeanAbsoluteDisparityError(BaseTester):
+ def test_smoke(self, device, dtype):
+ input = torch.rand(2, 1, 4, 5, device=device, dtype=dtype)
+ target = torch.rand(2, 1, 4, 5, device=device, dtype=dtype)
+ actual = kornia.metrics.mean_absolute_disparity_error(input, target)
+ assert actual.shape == torch.Size([])
+
+ def test_metric_mean_reduction(self, device, dtype):
+ sample = torch.ones(4, 4, device=device, dtype=dtype)
+ expected = torch.tensor(0.5, device=device, dtype=dtype)
+ actual = kornia.metrics.mean_absolute_disparity_error(sample, 1.5 * sample, reduction="mean")
+ self.assert_close(actual, expected)
+
+ def test_metric_sum_reduction(self, device, dtype):
+ sample = torch.ones(4, 4, device=device, dtype=dtype)
+ expected = torch.tensor(8.0, device=device, dtype=dtype)
+ actual = kornia.metrics.mean_absolute_disparity_error(sample, 1.5 * sample, reduction="sum")
+ self.assert_close(actual, expected)
+
+ def test_metric_no_reduction(self, device, dtype):
+ sample = torch.ones(4, 4, device=device, dtype=dtype)
+ expected = torch.full((4, 4), 0.5, device=device, dtype=dtype)
+ actual = kornia.metrics.mean_absolute_disparity_error(sample, 1.5 * sample, reduction="none")
+ self.assert_close(actual, expected)
+
+ def test_perfect_prediction(self, device, dtype):
+ sample = torch.rand(4, 4, device=device, dtype=dtype)
+ expected = torch.tensor(0.0, device=device, dtype=dtype)
+ actual = kornia.metrics.mean_absolute_disparity_error(sample, sample)
+ self.assert_close(actual, expected)
+
+ def test_valid_mask(self, device, dtype):
+ input = torch.zeros(2, 2, device=device, dtype=dtype)
+ target = torch.tensor([[1.0, 2.0], [3.0, 4.0]], device=device, dtype=dtype)
+ mask = torch.tensor([[True, False], [True, True]], device=device)
+
+ actual_mean = kornia.metrics.mean_absolute_disparity_error(input, target, mask, reduction="mean")
+ self.assert_close(actual_mean, torch.tensor(8.0 / 3.0, device=device, dtype=dtype))
+
+ actual_sum = kornia.metrics.mean_absolute_disparity_error(input, target, mask, reduction="sum")
+ self.assert_close(actual_sum, torch.tensor(8.0, device=device, dtype=dtype))
+
+ actual_none = kornia.metrics.mean_absolute_disparity_error(input, target, mask, reduction="none")
+ expected_none = torch.tensor([[1.0, 0.0], [3.0, 4.0]], device=device, dtype=dtype)
+ self.assert_close(actual_none, expected_none)
+
+ def test_valid_mask_numeric(self, device, dtype):
+ input = torch.zeros(2, 2, device=device, dtype=dtype)
+ target = torch.tensor([[1.0, 2.0], [3.0, 4.0]], device=device, dtype=dtype)
+ mask = torch.tensor([[1.0, 0.0], [1.0, 1.0]], device=device, dtype=dtype)
+ actual = kornia.metrics.mean_absolute_disparity_error(input, target, mask)
+ self.assert_close(actual, torch.tensor(8.0 / 3.0, device=device, dtype=dtype))
+
+ def test_valid_mask_broadcast(self, device, dtype):
+ input = torch.zeros(2, 2, 2, device=device, dtype=dtype)
+ target = torch.ones(2, 2, 2, device=device, dtype=dtype)
+ mask = torch.tensor([[True, False], [False, False]], device=device)
+ actual = kornia.metrics.mean_absolute_disparity_error(input, target, mask, reduction="sum")
+ self.assert_close(actual, torch.tensor(2.0, device=device, dtype=dtype))
+
+ def test_empty_valid_mask(self, device, dtype):
+ input = torch.zeros(2, 2, device=device, dtype=dtype)
+ target = torch.ones(2, 2, device=device, dtype=dtype)
+ mask = torch.zeros(2, 2, device=device, dtype=torch.bool)
+
+ actual_mean = kornia.metrics.mean_absolute_disparity_error(input, target, mask, reduction="mean")
+ assert torch.isnan(actual_mean)
+
+ actual_sum = kornia.metrics.mean_absolute_disparity_error(input, target, mask, reduction="sum")
+ self.assert_close(actual_sum, torch.tensor(0.0, device=device, dtype=dtype))
+
+ def test_exception(self, device, dtype):
+ sample = torch.ones(4, 4, device=device, dtype=dtype)
+
+ with pytest.raises(TypeCheckError) as errinfo:
+ kornia.metrics.mean_absolute_disparity_error(None, sample)
+ assert "Type mismatch: expected Tensor" in str(errinfo.value)
+
+ with pytest.raises(ShapeError) as errinfo:
+ kornia.metrics.mean_absolute_disparity_error(sample, sample[..., :2])
+ assert "Shape mismatch" in str(errinfo.value)
+
+ with pytest.raises(BaseError) as errinfo:
+ mask = torch.ones(3, device=device, dtype=torch.bool)
+ kornia.metrics.mean_absolute_disparity_error(sample, sample, mask)
+ assert "broadcastable" in str(errinfo.value)
+
+ with pytest.raises(NotImplementedError) as errinfo:
+ kornia.metrics.mean_absolute_disparity_error(sample, 2.0 * sample, reduction="foo")
+ assert "Invalid reduction option." in str(errinfo.value)
+
+
+class TestRootMeanSquaredDisparityError(BaseTester):
+ def test_smoke(self, device, dtype):
+ input = torch.rand(2, 1, 4, 5, device=device, dtype=dtype)
+ target = torch.rand(2, 1, 4, 5, device=device, dtype=dtype)
+ actual = kornia.metrics.root_mean_squared_disparity_error(input, target)
+ assert actual.shape == torch.Size([])
+
+ def test_metric_mean_reduction(self, device, dtype):
+ sample = torch.ones(4, 4, device=device, dtype=dtype)
+ expected = torch.tensor(0.5, device=device, dtype=dtype)
+ actual = kornia.metrics.root_mean_squared_disparity_error(sample, sample + 0.5, reduction="mean")
+ self.assert_close(actual, expected)
+
+ def test_metric_sum_reduction(self, device, dtype):
+ sample = torch.ones(4, 4, device=device, dtype=dtype)
+ expected = torch.tensor(2.0, device=device, dtype=dtype)
+ actual = kornia.metrics.root_mean_squared_disparity_error(sample, sample + 0.5, reduction="sum")
+ self.assert_close(actual, expected)
+
+ def test_metric_no_reduction(self, device, dtype):
+ sample = torch.ones(4, 4, device=device, dtype=dtype)
+ expected = torch.full((4, 4), 0.5, device=device, dtype=dtype)
+ actual = kornia.metrics.root_mean_squared_disparity_error(sample, sample + 0.5, reduction="none")
+ self.assert_close(actual, expected)
+
+ def test_perfect_prediction(self, device, dtype):
+ sample = torch.rand(4, 4, device=device, dtype=dtype)
+ expected = torch.tensor(0.0, device=device, dtype=dtype)
+ actual = kornia.metrics.root_mean_squared_disparity_error(sample, sample)
+ self.assert_close(actual, expected)
+
+ def test_valid_mask(self, device, dtype):
+ input = torch.zeros(2, 2, device=device, dtype=dtype)
+ target = torch.tensor([[1.0, 2.0], [3.0, 4.0]], device=device, dtype=dtype)
+ mask = torch.tensor([[True, True], [True, False]], device=device)
+
+ # sqrt((1 + 4 + 9) / 3)
+ actual_mean = kornia.metrics.root_mean_squared_disparity_error(input, target, mask, reduction="mean")
+ self.assert_close(actual_mean, torch.tensor(2.1602468994, device=device, dtype=dtype))
+
+ # sqrt(1 + 4 + 9)
+ actual_sum = kornia.metrics.root_mean_squared_disparity_error(input, target, mask, reduction="sum")
+ self.assert_close(actual_sum, torch.tensor(3.7416573867, device=device, dtype=dtype))
+
+ actual_none = kornia.metrics.root_mean_squared_disparity_error(input, target, mask, reduction="none")
+ expected_none = torch.tensor([[1.0, 2.0], [3.0, 0.0]], device=device, dtype=dtype)
+ self.assert_close(actual_none, expected_none)
+
+ def test_exception(self, device, dtype):
+ sample = torch.ones(4, 4, device=device, dtype=dtype)
+
+ with pytest.raises(TypeCheckError) as errinfo:
+ kornia.metrics.root_mean_squared_disparity_error(None, sample)
+ assert "Type mismatch: expected Tensor" in str(errinfo.value)
+
+ with pytest.raises(NotImplementedError) as errinfo:
+ kornia.metrics.root_mean_squared_disparity_error(sample, 2.0 * sample, reduction="foo")
+ assert "Invalid reduction option." in str(errinfo.value)
+
+
+class TestMeanBadPixelError(BaseTester):
+ def test_smoke(self, device, dtype):
+ input = torch.rand(2, 1, 4, 5, device=device, dtype=dtype)
+ target = torch.rand(2, 1, 4, 5, device=device, dtype=dtype)
+ actual = kornia.metrics.mean_bad_pixel_error(input, target)
+ assert actual.shape == torch.Size([])
+
+ def test_metric_mean_reduction(self, device, dtype):
+ input = torch.zeros(1, 6, device=device, dtype=dtype)
+ target = torch.tensor([[0.0, 1.0, 2.0, 3.0, 4.0, 5.0]], device=device, dtype=dtype)
+ expected = torch.tensor(2.0 / 6.0, device=device, dtype=dtype)
+ actual = kornia.metrics.mean_bad_pixel_error(input, target, reduction="mean")
+ self.assert_close(actual, expected)
+
+ def test_metric_sum_reduction(self, device, dtype):
+ input = torch.zeros(1, 6, device=device, dtype=dtype)
+ target = torch.tensor([[0.0, 1.0, 2.0, 3.0, 4.0, 5.0]], device=device, dtype=dtype)
+ expected = torch.tensor(2.0, device=device, dtype=dtype)
+ actual = kornia.metrics.mean_bad_pixel_error(input, target, reduction="sum")
+ self.assert_close(actual, expected)
+
+ def test_metric_no_reduction(self, device, dtype):
+ input = torch.zeros(1, 6, device=device, dtype=dtype)
+ target = torch.tensor([[0.0, 1.0, 2.0, 3.0, 4.0, 5.0]], device=device, dtype=dtype)
+ expected = torch.tensor([[0.0, 0.0, 0.0, 0.0, 1.0, 1.0]], device=device, dtype=dtype)
+ actual = kornia.metrics.mean_bad_pixel_error(input, target, reduction="none")
+ self.assert_close(actual, expected)
+
+ def test_perfect_prediction(self, device, dtype):
+ sample = torch.rand(4, 4, device=device, dtype=dtype)
+ expected = torch.tensor(0.0, device=device, dtype=dtype)
+ actual = kornia.metrics.mean_bad_pixel_error(sample, sample)
+ self.assert_close(actual, expected)
+
+ def test_threshold(self, device, dtype):
+ input = torch.zeros(1, 6, device=device, dtype=dtype)
+ target = torch.tensor([[0.0, 1.0, 2.0, 3.0, 4.0, 5.0]], device=device, dtype=dtype)
+
+ actual = kornia.metrics.mean_bad_pixel_error(input, target, threshold=1.0)
+ self.assert_close(actual, torch.tensor(4.0 / 6.0, device=device, dtype=dtype))
+
+ actual = kornia.metrics.mean_bad_pixel_error(input, target, threshold=4.5)
+ self.assert_close(actual, torch.tensor(1.0 / 6.0, device=device, dtype=dtype))
+
+ # an error exactly equal to the threshold is not a bad pixel
+ actual = kornia.metrics.mean_bad_pixel_error(input, target, threshold=5.0)
+ self.assert_close(actual, torch.tensor(0.0, device=device, dtype=dtype))
+
+ def test_valid_mask(self, device, dtype):
+ input = torch.zeros(1, 6, device=device, dtype=dtype)
+ target = torch.tensor([[0.0, 1.0, 2.0, 3.0, 4.0, 5.0]], device=device, dtype=dtype)
+ mask = torch.tensor([[True, True, True, True, False, True]], device=device)
+
+ actual_mean = kornia.metrics.mean_bad_pixel_error(input, target, valid_mask=mask, reduction="mean")
+ self.assert_close(actual_mean, torch.tensor(1.0 / 5.0, device=device, dtype=dtype))
+
+ actual_none = kornia.metrics.mean_bad_pixel_error(input, target, valid_mask=mask, reduction="none")
+ expected_none = torch.tensor([[0.0, 0.0, 0.0, 0.0, 0.0, 1.0]], device=device, dtype=dtype)
+ self.assert_close(actual_none, expected_none)
+
+ def test_exception(self, device, dtype):
+ sample = torch.ones(4, 4, device=device, dtype=dtype)
+
+ with pytest.raises(TypeCheckError) as errinfo:
+ kornia.metrics.mean_bad_pixel_error(None, sample)
+ assert "Type mismatch: expected Tensor" in str(errinfo.value)
+
+ with pytest.raises(NotImplementedError) as errinfo:
+ kornia.metrics.mean_bad_pixel_error(sample, 2.0 * sample, reduction="foo")
+ assert "Invalid reduction option." in str(errinfo.value)