π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(geometry): keep divisible resize dimensions positive (#5802)
Karnajeet Gosavi690fd6076214
diff --git a/changelog.d/5802.breaking.md b/changelog.d/5802.breaking.mdnew file mode 100644index 000000000..f099b0f3b--- /dev/null+++ b/changelog.d/5802.breaking.md@@ -0,0 +1 @@+`resize_to_be_divisible` rounds a side of at most half of `divisible_factor` up to `divisible_factor` instead of down to 0: a `(1, 3, 10, 14)` image with factor 24 now gives `(1, 3, 24, 24)` where it gave an empty `(1, 3, 0, 24)` image. An empty side still stays empty. It reads height and width from the last two axes, so `(H, W)` inputs and inputs with more than one leading axis are resized like in `resize`; they used to raise `UnboundLocalError`. A `divisible_factor` that is not a positive integer raises `ValueError`: a negative factor used to give the size of its absolute value, 0 raised `ZeroDivisionError` and a float raised `TypeError`.diff --git a/kornia/geometry/transform/affwarp.py b/kornia/geometry/transform/affwarp.pyindex eb1d1ec5e..1bb414d5a 100644--- a/kornia/geometry/transform/affwarp.py+++ b/kornia/geometry/transform/affwarp.py@@ -15,6 +15,7 @@# limitations under the License.#+import numbersfrom typing import Optional, Tuple, Unionimport torch@@ -738,7 +739,8 @@ def resize_to_be_divisible(Convention:- see the convention block of :func:`resize`- rounds ``height``/``width`` to the nearest multiple of ``divisible_factor`` before- delegating to :func:`resize`+ delegating to :func:`resize`; a positive side becomes at least ``divisible_factor``, and an empty side+ stays emptyArgs:input (torch.Tensor): Input tensor to be resized.@@ -754,13 +756,16 @@ def resize_to_be_divisible(torch.Tensor: The resized tensor."""- if isinstance(input, torch.Tensor) and len(input.shape) == 4:- height, width = input.shape[2], input.shape[3]- if isinstance(input, torch.Tensor) and len(input.shape) == 3:- height, width = input.shape[1], input.shape[2]-- height = round(height / divisible_factor) * divisible_factor- width = round(width / divisible_factor) * 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:+ raise ValueError(f"Input tensor must have at least two dimensions. Got {input.ndim}")+ if not isinstance(divisible_factor, numbers.Integral) or divisible_factor <= 0:+ raise ValueError(f"divisible_factor must be a positive integer. Got {divisible_factor}")++ height, width = input.shape[-2:]+ height = max(1, round(height / divisible_factor)) * divisible_factor if height > 0 else 0+ width = max(1, round(width / divisible_factor)) * divisible_factor if width > 0 else 0return resize(input, (height, width), interpolation, align_corners, side, antialias)diff --git a/tests/geometry/transform/test_affine.py b/tests/geometry/transform/test_affine.pyindex f9e26727c..e2c41e73d 100644--- a/tests/geometry/transform/test_affine.py+++ b/tests/geometry/transform/test_affine.py@@ -17,6 +17,7 @@import math+import numpy as npimport pytestimport torch@@ -27,6 +28,43 @@ from testing.base import BaseTesterclass TestResize(BaseTester):+ @pytest.mark.parametrize(+ "shape, divisible_factor, expected",+ [+ ((10, 14), 24, (24, 24)),+ ((1, 3, 10, 14), 32, (1, 3, 32, 32)),+ ((3, 10, 14), 4, (3, 8, 16)),+ ((3, 14, 10), 4, (3, 16, 8)),+ ((3, 10, 14), 24, (3, 24, 24)),+ ((1, 3, 10, 14), 24, (1, 3, 24, 24)),+ ((2, 1, 3, 10, 14), 24, (2, 1, 3, 24, 24)),+ ],+ )+ def test_resize_to_be_divisible_short_sides(self, shape, divisible_factor, expected, device, dtype):+ inp = torch.rand(*shape, device=device, dtype=dtype)+ out = kornia.geometry.transform.resize_to_be_divisible(inp, divisible_factor)+ assert out.shape == 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_divisible+ inp = torch.rand(1, 3, 10, 14, device=device, dtype=dtype)+ assert resize_to_be_divisible(inp, np.int64(4)).shape == (1, 3, 8, 16)+ # An empty side is already divisible and stays empty, as in resize.+ empty = torch.zeros(1, 3, 0, 14, device=device, dtype=dtype)+ assert resize_to_be_divisible(empty, 4).shape == (1, 3, 0, 16)+ assert resize_to_be_divisible(empty.transpose(-1, -2), 4).shape == (1, 3, 16, 0)++ def test_resize_to_be_divisible_rejects_invalid_inputs(self, device, dtype):+ resize_to_be_divisible = kornia.geometry.transform.resize_to_be_divisible+ with pytest.raises(TypeError, match="is not a torch"):+ resize_to_be_divisible([[0.0, 1.0]], 4)+ with pytest.raises(ValueError, match="at least two dimensions"):+ resize_to_be_divisible(torch.rand(4, device=device, dtype=dtype), 4)+ inp = torch.rand(4, 4, device=device, dtype=dtype)+ for divisible_factor in (0, -1, 2.5):+ with pytest.raises(ValueError, match="positive integer"):+ resize_to_be_divisible(inp, divisible_factor)+def test_smoke(self, device, dtype):inp = torch.rand(1, 3, 3, 4, device=device, dtype=dtype)out = kornia.geometry.transform.resize(inp, (3, 4), align_corners=False)