π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(metrics): validate the padding mode of ssim and ssim3d case-insensitively (#5553)
εΊζ’ηcd6ecd469c03
diff --git a/changelog.d/5553.breaking.md b/changelog.d/5553.breaking.mdnew file mode 100644index 000000000..f02d2fa58--- /dev/null+++ b/changelog.d/5553.breaking.md@@ -0,0 +1,7 @@+`ssim`, `ssim3d`, `SSIM`, `SSIM3D`, `ssim_loss`, `SSIMLoss`, `ssim3d_loss` and `SSIM3DLoss` now read `padding`+case-insensitively and reject any other value, as the filters do (#5537). Previously every value other than `'valid'`+silently took the `'same'` branch. `padding='VALID'` or `'Valid'` returned the uncropped map, so a 5-pixel window on+a 13Γ17 image gave 13Γ17 and now gives 9Γ13, the output of `padding='valid'`, and the losses now use that cropped+map. A misspelling such as `'full'` or `'bogus'` returned the `'same'` map and now raises kornia's+`Invalid padding mode` error, which names the accepted options. `'same'`, `'valid'` and the case variants of `'same'`+are unchanged.diff --git a/kornia/metrics/ssim.py b/kornia/metrics/ssim.pyindex ccab73279..83126eb3c 100644--- a/kornia/metrics/ssim.py+++ b/kornia/metrics/ssim.py@@ -20,8 +20,9 @@ from typing import Listimport torchfrom torch import nn+from kornia.core.check import KORNIA_CHECKfrom kornia.filters import filter2d_separable, get_gaussian_kernel1d-from kornia.filters.filter import _compute_padding+from kornia.filters.filter import _VALID_PADDING, _compute_paddingdef _crop(img: torch.Tensor, cropping_shape: List[int]) -> torch.Tensor:@@ -97,6 +98,13 @@ def ssim(if not img1.shape == img2.shape:raise ValueError(f"img1 and img2 shapes must be the same. Got: {img1.shape} and {img2.shape}")+ KORNIA_CHECK(+ str(padding).lower() in _VALID_PADDING,+ f"Invalid padding mode, {padding}. Expected one of {_VALID_PADDING}",+ )+ # the check is case-insensitive, so dispatch on the lower-case spelling as well+ padding = str(padding).lower()+# Preserve fractional Gaussian weights and avoid integer moment overflow.if not img1.is_floating_point() and not img1.is_complex():img1 = img1.to(torch.float32)diff --git a/kornia/metrics/ssim3d.py b/kornia/metrics/ssim3d.pyindex 13a6f0d8d..73615713d 100644--- a/kornia/metrics/ssim3d.py+++ b/kornia/metrics/ssim3d.py@@ -23,7 +23,7 @@ from torch import nnfrom kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SHAPEfrom kornia.filters import filter3d, get_gaussian_kernel3d-from kornia.filters.filter import _compute_padding+from kornia.filters.filter import _VALID_PADDING, _compute_paddingdef _crop(img: torch.Tensor, cropping_shape: List[int]) -> torch.Tensor:@@ -98,6 +98,13 @@ def ssim3d(if not isinstance(max_val, float):raise TypeError(f"Input max_val type is not a float. Got {type(max_val)}")+ KORNIA_CHECK(+ str(padding).lower() in _VALID_PADDING,+ f"Invalid padding mode, {padding}. Expected one of {_VALID_PADDING}",+ )+ # the check is case-insensitive, so dispatch on the lower-case spelling as well+ padding = str(padding).lower()+# Preserve fractional Gaussian weights and avoid integer moment overflow.if not img1.is_floating_point() and not img1.is_complex():img1 = img1.to(torch.float32)diff --git a/tests/metrics/test_ssim3d.py b/tests/metrics/test_ssim3d.pyindex f04ae2c4e..e317837d3 100644--- a/tests/metrics/test_ssim3d.py+++ b/tests/metrics/test_ssim3d.py@@ -148,6 +148,28 @@ class TestSSIM3d(BaseTester):assert actual.shape == expected+ @pytest.mark.parametrize("padding", ["VALID", "Valid"])+ def test_padding_case_insensitive(self, device, dtype, padding):+ # Case variants select their branch as the filters do since #5156 (#5537).+ img1 = torch.rand(1, 1, 9, 11, 13, device=device, dtype=dtype)+ img2 = torch.rand(1, 1, 9, 11, 13, device=device, dtype=dtype)+ expected = kornia.metrics.ssim3d(img1, img2, 5, padding="valid")+ actual = kornia.metrics.ssim3d(img1, img2, 5, padding=padding)+ assert actual.shape == (1, 1, 5, 7, 9)+ self.assert_close(actual, expected, rtol=0, atol=0)+ self.assert_close(kornia.metrics.SSIM3D(5, padding=padding)(img1, img2), expected, rtol=0, atol=0)++ @pytest.mark.parametrize("padding", ["full", "bogus"])+ def test_exception_invalid_padding(self, device, dtype, padding):+ # Any other value raises instead of silently returning the 'same' map (#5537).+ from kornia.core.exceptions import BaseError++ img = torch.rand(1, 1, 3, 3, 3, device=device, dtype=dtype)+ with pytest.raises(BaseError, match="Invalid padding mode"):+ kornia.metrics.ssim3d(img, img, 3, padding=padding)+ with pytest.raises(BaseError, match="Invalid padding mode"):+ kornia.metrics.SSIM3D(3, padding=padding)(img, img)+def test_exception(self, device, dtype):img = torch.rand(1, 1, 3, 3, 3, device=device, dtype=dtype)diff --git a/tests/metrics/test_ssim_metric.py b/tests/metrics/test_ssim_metric.pyindex ef7b8dc35..d2ffd41cb 100644--- a/tests/metrics/test_ssim_metric.py+++ b/tests/metrics/test_ssim_metric.py@@ -20,6 +20,7 @@ from __future__ import annotationsimport pytestimport torch+from kornia.core.exceptions import BaseErrorfrom kornia.metrics.ssim import SSIM, ssimfrom testing.base import BaseTester@@ -127,6 +128,26 @@ class TestSsim(BaseTester):assert out_valid.shape[2] < out_same.shape[2]assert out_valid.shape[3] < out_same.shape[3]+ @pytest.mark.parametrize("padding", ["VALID", "Valid"])+ def test_padding_case_insensitive(self, device, dtype, padding):+ # Case variants select their branch as the filters do since #5156 (#5537).+ img1 = torch.rand(1, 1, 13, 17, device=device, dtype=dtype)+ img2 = torch.rand(1, 1, 13, 17, device=device, dtype=dtype)+ expected = ssim(img1, img2, window_size=5, padding="valid")+ actual = ssim(img1, img2, window_size=5, padding=padding)+ assert actual.shape == (1, 1, 9, 13)+ self.assert_close(actual, expected, rtol=0, atol=0)+ self.assert_close(SSIM(5, padding=padding)(img1, img2), expected, rtol=0, atol=0)++ @pytest.mark.parametrize("padding", ["full", "bogus"])+ def test_exception_invalid_padding(self, device, dtype, padding):+ # Any other value raises instead of silently returning the 'same' map (#5537).+ img = torch.rand(1, 1, 8, 8, device=device, dtype=dtype)+ with pytest.raises(BaseError, match="Invalid padding mode"):+ ssim(img, img, window_size=3, padding=padding)+ with pytest.raises(BaseError, match="Invalid padding mode"):+ SSIM(3, padding=padding)(img, img)+def test_exception_non_tensor_img1(self, device, dtype):img2 = torch.rand(1, 1, 8, 8, device=device, dtype=dtype)with pytest.raises(TypeError, match=r"Input img1 type is not a torch\.Tensor"):