π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(geometry): reject the 1-D and 3-D interpolation modes in resize (#6013)
Saksham Sharma5aa3578ed957
diff --git a/changelog.d/6013.fixed.md b/changelog.d/6013.fixed.mdnew file mode 100644index 000000000..4b400dc9a--- /dev/null+++ b/changelog.d/6013.fixed.md@@ -0,0 +1 @@+`resize`, `Resize`, `rescale` and `Rescale` raise `ValueError` for `interpolation="linear"` and `"trilinear"`, with a message that names the supported modes, and so do `resize_to_be_divisible`, and `crop_by_indices` when a crop has to be resized. Their docstrings no longer list these two modes. Every input is resampled as a 4-D `(B, C, H, W)` batch, which `torch.nn.functional.interpolate` rejects for them, so these modes previously raised its raw `NotImplementedError` ("Got 4D input") for every input; only a target size with a zero side returned an empty tensor, and it now raises too. The other modes are unchanged.diff --git a/kornia/geometry/transform/affwarp.py b/kornia/geometry/transform/affwarp.pyindex 60410578f..e8661397c 100644--- a/kornia/geometry/transform/affwarp.py+++ b/kornia/geometry/transform/affwarp.py@@ -648,8 +648,8 @@ def resize(output size will be matched to this. If size is an int, smaller edge of the image willbe matched to this number. i.e, if height > width, then image will be rescaledto (size * height / width, size)- interpolation: algorithm used for upsampling: ``'nearest'`` | ``'nearest-exact'`` | ``'linear'`` |- ``'bilinear'`` | 'bicubic' | 'trilinear' | 'area'.+ interpolation: algorithm used for upsampling: ``'nearest'`` | ``'nearest-exact'`` | ``'bilinear'`` |+ ``'bicubic'`` | ``'area'``.align_corners: interpolation flag.side: Corresponding side if ``size`` is an integer. Can be one of ``'short'``, ``'long'``, ``'vert'``,or ``'horz'``.@@ -671,6 +671,12 @@ def resize(if len(input.shape) < 2:raise ValueError(f"Input tensor must have at least two dimensions. Got {len(input.shape)}")+ # Every input is resampled as a 4-D (B, C, H, W) batch, for which F.interpolate rejects the 1-D and 3-D modes.+ if interpolation in ("linear", "trilinear"):+ raise ValueError(+ f"interpolation={interpolation!r} is not supported: resize resamples (H, W), so use 'nearest', "+ "'nearest-exact', 'bilinear', 'bicubic' or 'area'."+ )original_shape = input.shapeh, w = input.shape[-2:]@@ -812,8 +818,8 @@ def rescale(input: The image tensor to be scale with shape of :math:`(B, C, H, W)`.factor: Desired scaling factor as ``(factor_h, factor_w)`` β height first. If a singlefloat, the value is used for both height and width (an ``int`` raises ``TypeError``).- interpolation: algorithm used for upsampling: ``'nearest'`` | ``'nearest-exact'`` | ``'linear'`` |- ``'bilinear'`` | ``'bicubic'`` | ``'trilinear'`` | ``'area'``.+ interpolation: algorithm used for upsampling: ``'nearest'`` | ``'nearest-exact'`` | ``'bilinear'`` |+ ``'bicubic'`` | ``'area'``.align_corners: interpolation flag.antialias: if True, then image will be filtered with Gaussian before downscaling.No effect for upscaling.@@ -872,8 +878,8 @@ class Resize(nn.Module):output size will be matched to this. If size is an int, smaller edge of the image willbe matched to this number. i.e, if height > width, then image will be rescaledto (size * height / width, size)- interpolation: algorithm used for upsampling: ``'nearest'`` | ``'linear'`` | ``'bilinear'`` |- 'bicubic' | 'trilinear' | 'area'.+ interpolation: algorithm used for upsampling: ``'nearest'`` | ``'nearest-exact'`` | ``'bilinear'`` |+ ``'bicubic'`` | ``'area'``.align_corners: interpolation flag.side: Corresponding side if ``size`` is an integer. Can be one of ``'short'``, ``'long'``, ``'vert'``,or ``'horz'``.@@ -1065,8 +1071,8 @@ class Rescale(nn.Module):Args:factor: Desired scaling factor as ``(factor_h, factor_w)`` β height first. If a singlefloat, the value is used for both height and width (an ``int`` raises ``TypeError``).- interpolation: algorithm used for upsampling: ``'nearest'`` | ``'nearest-exact'`` | ``'linear'`` |- ``'bilinear'`` | ``'bicubic'`` | ``'trilinear'`` | ``'area'``.+ interpolation: algorithm used for upsampling: ``'nearest'`` | ``'nearest-exact'`` | ``'bilinear'`` |+ ``'bicubic'`` | ``'area'``.align_corners: interpolation flag.antialias: if True, then image will be filtered with Gaussian before downscaling.No effect for upscaling.diff --git a/kornia/geometry/transform/crop2d.py b/kornia/geometry/transform/crop2d.pyindex b018e2e2e..f19d15822 100644--- a/kornia/geometry/transform/crop2d.py+++ b/kornia/geometry/transform/crop2d.py@@ -485,8 +485,8 @@ def crop_by_indices(size: output size. An auto resize or F.pad will be performed according to ``shape_compensation``if the cropped slice sizes are not exactly align `size`.If None, will auto-infer from src_box.- interpolation: algorithm used for upsampling: ``'nearest'`` | ``'linear'`` | ``'bilinear'`` |- 'bicubic' | 'trilinear' | 'area'.+ interpolation: algorithm used for upsampling: ``'nearest'`` | ``'nearest-exact'`` | ``'bilinear'`` |+ ``'bicubic'`` | ``'area'``.align_corners: interpolation flag.antialias: if True, then image will be filtered with Gaussian before downscaling.No effect for upscaling.diff --git a/tests/geometry/transform/test_affine.py b/tests/geometry/transform/test_affine.pyindex 554e98d85..ef7272c20 100644--- a/tests/geometry/transform/test_affine.py+++ b/tests/geometry/transform/test_affine.py@@ -419,6 +419,50 @@ class TestResize(BaseTester):expected = op(inp, new_size, align_corners=False, antialias=anti_alias)self.assert_close(out, expected)+ @pytest.mark.parametrize("interpolation", ["linear", "trilinear"])+ @pytest.mark.parametrize("shape", [(3, 16, 20), (2, 3, 16, 20), (2, 3, 4, 16, 20)])+ @pytest.mark.parametrize("api", ["resize", "Resize", "rescale", "Rescale"])+ def test_one_and_three_dimensional_modes_raise_6012(self, interpolation, shape, api, device, dtype):+ # Every input is resampled as a 4-D batch, which F.interpolate rejects for these modes; this used to+ # surface as its raw "Got 4D input" NotImplementedError although the docstrings listed both modes.+ image = torch.rand(shape, device=device, dtype=dtype)+ T = kornia.geometry.transform+ calls = {+ "resize": lambda: T.resize(image, (8, 10), interpolation=interpolation),+ "Resize": lambda: T.Resize((8, 10), interpolation=interpolation)(image),+ "rescale": lambda: T.rescale(image, 0.5, interpolation=interpolation),+ "Rescale": lambda: T.Rescale(0.5, interpolation=interpolation, align_corners=None)(image),+ }++ with pytest.raises(ValueError, match=f"interpolation='{interpolation}' is not supported: resize resamples"):+ calls[api]()++ @pytest.mark.parametrize("interpolation", ["nearest", "nearest-exact", "bilinear", "bicubic", "area"])+ def test_documented_modes_resize_6012(self, interpolation, device, dtype):+ # Each mode the docstrings list resamples a (B, C, H, W) batch.+ image = torch.rand(2, 3, 16, 20, device=device, dtype=dtype)++ out = kornia.geometry.transform.resize(image, (8, 10), interpolation=interpolation)++ assert out.shape == (2, 3, 8, 10)++ @pytest.mark.parametrize("interpolation", ["linear", "trilinear"])+ @pytest.mark.parametrize("api", ["resize_empty_output", "resize_to_be_divisible", "crop_by_indices"])+ def test_one_and_three_dimensional_modes_raise_in_resize_callers_6012(self, interpolation, api, device, dtype):+ # An empty output side used to skip interpolate and return an empty tensor; resize_to_be_divisible, and+ # crop_by_indices when a crop has to be resized, reach these modes through resize.+ image = torch.zeros(2, 3, 16, 20, device=device, dtype=dtype)+ box = torch.tensor([[[1, 1], [10, 1], [10, 8], [1, 8]]], device=device, dtype=dtype).repeat(2, 1, 1)+ T = kornia.geometry.transform+ calls = {+ "resize_empty_output": lambda: T.resize(image, (0, 10), interpolation=interpolation),+ "resize_to_be_divisible": lambda: T.resize_to_be_divisible(image, 7, interpolation=interpolation),+ "crop_by_indices": lambda: T.crop_by_indices(image, box, size=(5, 6), interpolation=interpolation),+ }++ with pytest.raises(ValueError, match=f"interpolation='{interpolation}' is not supported: resize resamples"):+ calls[api]()+class TestRescale(BaseTester):def test_smoke(self, device, dtype):