π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(geometry): deprecate ignored resize_to_be_divisible side argument (#6408)
Muhammad Talha6d61cc9530e2
diff --git a/changelog.d/6408.added.md b/changelog.d/6408.added.mdnew file mode 100644index 000000000..31a517016--- /dev/null+++ b/changelog.d/6408.added.md@@ -0,0 +1 @@+`resize_to_be_divisible` emits a `DeprecationWarning` when `side` is passed; the argument will be removed in a future release. It never had an effect, because both sides are rounded to a multiple of `divisible_factor`, and results do not change. `get_sample_images` passes its `side` keyword only to `resize` when `resize` is given.diff --git a/kornia/geometry/transform/affwarp.py b/kornia/geometry/transform/affwarp.pyindex a2fedc5f0..d3ebda6bb 100644--- a/kornia/geometry/transform/affwarp.py+++ b/kornia/geometry/transform/affwarp.py@@ -45,6 +45,7 @@ from typing import Optional, Tuple, Unionimport torchfrom torch import nn+from kornia.core._compat import _emit_deprecation_warningfrom kornia.core.ops import _device_literal, eye_likefrom kornia.core.utils import _extract_device_dtypefrom kornia.filters import gaussian_blur2d@@ -893,7 +894,7 @@ def resize_to_be_divisible(divisible_factor: int,interpolation: str = "bilinear",align_corners: Optional[bool] = None,- side: str = "short",+ side: Optional[str] = None,antialias: bool = False,) -> torch.Tensor:"""Resize an image so that its height and width are multiples of a factor.@@ -901,9 +902,8 @@ def resize_to_be_divisible(``out = resize_to_be_divisible(input, divisible_factor)`` resizes ``(*, H, W)`` tensors with :func:`resize` to thenearest multiples of ``divisible_factor``, at least ``divisible_factor`` for a positive side, and returns``(*, h, w)``; an empty side stays empty. A side halfway between two multiples rounds as Python's :func:`round`- does, to an even quotient, so with a factor of 4 both 6 and 10 become 8. ``side`` is passed to :func:`resize` but- has no effect there, because the size is a pair (`#6397 <https://github.com/kornia/kornia/issues/6397>`_). For a- given size, use :func:`resize`.+ does, to an even quotient, so with a factor of 4 both 6 and 10 become 8. ``side`` is deprecated and has no effect.+ For a given size, use :func:`resize`.Convention:- see the convention block of :func:`resize`@@ -917,8 +917,9 @@ def resize_to_be_divisible(interpolation (str, optional): Interpolation flag. Defaults to "bilinear".align_corners (Optional[bool], optional):whether to align the corners of the input and output. Defaults to None.- side (str, optional): passed to :func:`resize`, where it has no effect because the size is a pair.- Defaults to "short".+ side (str, optional): Deprecated and ignored. Both sides are rounded independently to a multiple of+ ``divisible_factor``. In eager mode, any explicit non-None value emits a :class:`DeprecationWarning`.+ Defaults to None. This argument will be removed in a future release.antialias (bool, optional):If True, then image will be filtered with Gaussian before downscaling. Defaults to False.@@ -934,6 +935,14 @@ def resize_to_be_divisible(- :func:`rescale`: resize by a factor."""+ if not torch.jit.is_scripting(): # noqa: SIM102 - TorchScript needs a standalone guard.+ if side is not None:+ _emit_deprecation_warning(+ "resize_to_be_divisible(..., side=...)",+ None,+ "0.9.1",+ "The `side` argument has no effect. Both sides are rounded to a multiple of `divisible_factor`.",+ )if not isinstance(input, torch.Tensor):raise TypeError(f"Input tensor type is not a torch.Tensor. Got {type(input)}")if input.ndim < 2:@@ -944,7 +953,7 @@ def resize_to_be_divisible(height, width = input.shape[-2:]height = max(1, round(height / divisible_factor)) * divisible_factor if height > 0 else 0width = max(1, round(width / divisible_factor)) * divisible_factor if width > 0 else 0- return resize(input, (height, width), interpolation, align_corners, side, antialias)+ return resize(input, (height, width), interpolation=interpolation, align_corners=align_corners, antialias=antialias)def rescale(diff --git a/kornia/io/sample.py b/kornia/io/sample.pyindex 830ac802e..16c399561 100644--- a/kornia/io/sample.py+++ b/kornia/io/sample.py@@ -185,7 +185,8 @@ def get_sample_images(if resize is not None:img_tensor = kornia.geometry.resize(img_tensor, resize, **kwargs)if divisible_factor is not None:- img_tensor = kornia.geometry.transform.resize_to_be_divisible(img_tensor, divisible_factor, **kwargs)+ div_kwargs = kwargs if resize is None else {key: value for key, value in kwargs.items() if key != "side"}+ img_tensor = kornia.geometry.transform.resize_to_be_divisible(img_tensor, divisible_factor, **div_kwargs)tensors.append(img_tensor)if not as_list and resize is not None:diff --git a/tests/geometry/transform/test_affine.py b/tests/geometry/transform/test_affine.pyindex c9294a5cc..2119ca686 100644--- a/tests/geometry/transform/test_affine.py+++ b/tests/geometry/transform/test_affine.py@@ -17,6 +17,7 @@import itertoolsimport math+import warningsimport numpy as npimport pytest@@ -46,6 +47,38 @@ class TestResize(BaseTester):out = kornia.geometry.transform.resize_to_be_divisible(inp, divisible_factor)assert out.shape == expected+ @pytest.mark.parametrize("kwargs", [{}, {"side": None}])+ def test_resize_to_be_divisible_default_side(self, kwargs, device, dtype):+ inp = torch.rand(1, 1, 6, 12, device=device, dtype=dtype)+ with warnings.catch_warnings():+ warnings.simplefilter("error", DeprecationWarning)+ out = kornia.geometry.transform.resize_to_be_divisible(inp, 5, **kwargs)+ assert out.shape == (1, 1, 5, 10)++ @pytest.mark.parametrize("shape", [(1, 1, 6, 12), (2, 3, 17, 9), (1, 1, 5, 10), (1, 1, 0, 12)])+ @pytest.mark.parametrize("side", ["short", "long", "vert", "horz", "bogus"])+ def test_resize_to_be_divisible_deprecated_side(self, shape, side, device, dtype):+ inp = torch.rand(*shape, device=device, dtype=dtype)+ expected = kornia.geometry.transform.resize_to_be_divisible(inp, 5)+ with pytest.warns(DeprecationWarning, match="side.*has no effect") as records:+ out = kornia.geometry.transform.resize_to_be_divisible(inp, 5, side=side)+ assert len(records) == 1+ assert records[0].filename == __file__+ self.assert_close(out, expected, rtol=0, atol=0)++ @pytest.mark.parametrize("side", ["short", "long", "vert", "horz", "bogus"])+ @pytest.mark.skipif(not dynamo_is_available(), reason=DYNAMO_UNAVAILABLE_REASON)+ def test_resize_to_be_divisible_compile_fullgraph(self, side, device, dtype, torch_optimizer, optimizer_backend):+ if not optimizer_backend or optimizer_backend == "jit":+ pytest.skip("Fullgraph requires a torch.compile backend, not TorchScript or the no-op optimizer.")+ inp = torch.rand(1, 1, 6, 12, device=device, dtype=dtype)+ expected = kornia.geometry.transform.resize_to_be_divisible(inp, 5)+ op = torch_optimizer(kornia.geometry.transform.resize_to_be_divisible, fullgraph=True)+ with warnings.catch_warnings():+ warnings.filterwarnings("error", message=r".*resize_to_be_divisible.*side", category=DeprecationWarning)+ out = op(inp, 5, side=side)+ self.assert_close(out, expected)+def test_resize_to_be_divisible_numpy_factor_and_empty_side(self, device, dtype):resize_to_be_divisible = kornia.geometry.transform.resize_to_be_divisibleinp = torch.rand(1, 3, 10, 14, device=device, dtype=dtype)diff --git a/tests/io/test_io_image.py b/tests/io/test_io_image.pyindex ec1b38dbe..de6def54b 100644--- a/tests/io/test_io_image.py+++ b/tests/io/test_io_image.py@@ -18,6 +18,7 @@import ioimport reimport struct+import warningsimport zlibfrom pathlib import Path@@ -1291,3 +1292,29 @@ class TestConventionsIo:path = tmp_path / "thin.png"write_image(path, torch.zeros(*shape, dtype=torch.uint8))assert path.stat().st_size > 0++[email protected]("side, expected", [("long", (1, 3, 24, 40)), ("short", (1, 3, 40, 56))])+def test_sample_images_resize_side_with_divisible_factor(tmp_path, side, expected):+ from kornia.io import get_sample_images++ path = tmp_path / "non_square.png"+ write_image(path, torch.zeros(3, 22, 32, dtype=torch.uint8))+ with warnings.catch_warnings():+ warnings.filterwarnings("error", message=r".*side", category=DeprecationWarning)+ out = get_sample_images(40, paths=[str(path)], divisible_factor=8, as_list=False, side=side)+ assert out.shape == expected++[email protected]("side", ["short", "long"])+def test_sample_images_divisible_only_warns_for_side(tmp_path, side):+ from kornia.io import get_sample_images++ path = tmp_path / "non_square.png"+ write_image(path, torch.zeros(3, 22, 32, dtype=torch.uint8))+ expected = get_sample_images(paths=[str(path)], divisible_factor=8)+ with pytest.warns(DeprecationWarning, match="side"):+ out = get_sample_images(paths=[str(path)], divisible_factor=8, side=side)+ assert len(out) == len(expected) == 1+ assert out[0].shape == expected[0].shape+ torch.testing.assert_close(out[0], expected[0], rtol=0, atol=0)