Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(geometry): return an empty image for a zero-sized resize output (#4140)

Chen Yufan29e05314fd29
diff --git a/CHANGELOG.md b/CHANGELOG.md
index ee5db9b9a..6b14b32ed 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -671,6 +671,22 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
The export resolver includes implicit submodule bindings and rejects unsupported dynamic binding expressions
as evidence of removal. Deprecation windows and release notes still apply. (#4190, #4230)
+* `resize` and `rescale` return an empty image for a zero-sized output instead of raising
+ `ZeroDivisionError` out of the scale-factor computation (#4115). `resize(x, (0, 4))`, `resize(x, 0)`,
+ `Resize((0, 4))`, and any `rescale` factor that takes a side to zero (`rescale(x, 0.0)`) previously died
+ in `h / size[0]`; they now return an empty tensor of the requested shape, which is the answer
+ `warp_affine`, `warp_perspective` and `center_crop` already gave for the same request. The empty result
+ stays connected to the autograd graph, the way `_empty_warp_output_2d` builds it for the warping ops, so
+ a batch element that degenerates to a zero-sized output still contributes a zero gradient rather than
+ detaching.
+
+ A degenerate *input* is a different question and is now rejected rather than divided by: resizing a
+ `(1, 3, 0, 4)` image to a positive size, or with an `int` size at all -- an `int` names one side and takes
+ the other from an aspect ratio a degenerate input does not have -- raises
+ `ValueError("Input image size must be positive. Got height=0, width=4.")`, the message the warping ops
+ already use, instead of the same bare `ZeroDivisionError`. Empty in and empty out is well defined and
+ still comes back empty. (#4140)
+
* `validate_bbox` and `validate_bbox3d` flatten rank-4 `(B, N, 4, 2)` / `(B, N, 8, 3)` input with `reshape`
instead of `view`, so a non-contiguous leading-dimension stride (a transpose, a slice that drops boxes, an
`expand`) returns a boolean as documented instead of raising `RuntimeError`. (#4174)
diff --git a/kornia/geometry/transform/affwarp.py b/kornia/geometry/transform/affwarp.py
index 96be01e32..064089a37 100644
--- a/kornia/geometry/transform/affwarp.py
+++ b/kornia/geometry/transform/affwarp.py
@@ -636,7 +636,13 @@ def resize(
original_shape = input.shape
h, w = input.shape[-2:]
+
if isinstance(size, int):
+ if h <= 0 or w <= 0:
+ # An int size names one side and takes the other from the aspect ratio, which a
+ # degenerate input does not have. Reject it with the message the warping ops use,
+ # rather than letting the division below fail with a bare ZeroDivisionError.
+ raise ValueError(f"Input image size must be positive. Got height={h}, width={w}.")
aspect_ratio = w / h
size = _side_to_image_size(size, aspect_ratio, side)
if len(original_shape) == 2:
@@ -652,19 +658,34 @@ def resize(
batch_size *= d
input = input.reshape(batch_size, *original_shape[-3:])
- factors = (h / size[0], w / size[1])
- antialias = antialias and (max(factors) > 1)
+ if size[0] == 0 or size[1] == 0:
+ # An output side of zero gives an empty image, matching warp_affine,
+ # warp_perspective and center_crop -- including when the input is empty as well,
+ # which is why this runs ahead of the positive-size check below. The result is
+ # built directly: the scale factors would divide by zero, and
+ # torch.nn.functional.interpolate rejects a zero-sized output outright.
+ #
+ # It is routed through the input so the empty result keeps its autograd link, the
+ # way _empty_warp_output_2d does for the warping ops. sum() promotes an integer
+ # input to int64, so the accumulation dtype is pinned to the input's.
+ zero = input.reshape(-1)[:1].sum(dtype=input.dtype) * 0
+ output = zero.reshape(*([1] * input.dim())).expand(*input.shape[:-2], size[0], size[1])
+ elif h <= 0 or w <= 0:
+ raise ValueError(f"Input image size must be positive. Got height={h}, width={w}.")
+ else:
+ factors = (h / size[0], w / size[1])
+ antialias = antialias and (max(factors) > 1)
- if antialias:
- sigmas = (max((factors[0] - 1.0) / 2.0, 0.001), max((factors[1] - 1.0) / 2.0, 0.001))
+ if antialias:
+ sigmas = (max((factors[0] - 1.0) / 2.0, 0.001), max((factors[1] - 1.0) / 2.0, 0.001))
- ks = int(max(2.0 * 2 * sigmas[0], 3)), int(max(2.0 * 2 * sigmas[1], 3))
+ ks = int(max(2.0 * 2 * sigmas[0], 3)), int(max(2.0 * 2 * sigmas[1], 3))
- ks = (ks[0] if ks[0] % 2 else ks[0] + 1, ks[1] if ks[1] % 2 else ks[1] + 1)
+ ks = (ks[0] if ks[0] % 2 else ks[0] + 1, ks[1] if ks[1] % 2 else ks[1] + 1)
- input = gaussian_blur2d(input, ks, sigmas)
+ input = gaussian_blur2d(input, ks, sigmas)
- output = torch.nn.functional.interpolate(input, size=size, mode=interpolation, align_corners=align_corners)
+ output = torch.nn.functional.interpolate(input, size=size, mode=interpolation, align_corners=align_corners)
if len(original_shape) == 2:
output = output[0, 0]
diff --git a/tests/geometry/transform/test_affine.py b/tests/geometry/transform/test_affine.py
index 53c4d5bff..10b954de5 100644
--- a/tests/geometry/transform/test_affine.py
+++ b/tests/geometry/transform/test_affine.py
@@ -84,6 +84,63 @@ class TestResize(BaseTester):
out = kornia.geometry.transform.resize(inp, (3, 1), align_corners=False)
assert out.shape == (1, 2, 3, 2, 1, 3, 3, 1)
+ def test_zero_output_size(self, device, dtype):
+ # A zero output side gives an empty image, matching warp_affine,
+ # warp_perspective and center_crop on the same argument.
+ inp = torch.rand(1, 3, 4, 4, device=device, dtype=dtype)
+
+ assert kornia.geometry.transform.resize(inp, (0, 4)).shape == (1, 3, 0, 4)
+ assert kornia.geometry.transform.resize(inp, (4, 0)).shape == (1, 3, 4, 0)
+ assert kornia.geometry.transform.resize(inp, (0, 0)).shape == (1, 3, 0, 0)
+ assert kornia.geometry.transform.resize(inp, 0).shape == (1, 3, 0, 0)
+ assert kornia.geometry.transform.Resize((0, 4))(inp).shape == (1, 3, 0, 4)
+ assert kornia.geometry.transform.resize(inp, (0, 4), antialias=True).shape == (1, 3, 0, 4)
+
+ eye = torch.eye(2, 3, device=device, dtype=dtype)[None]
+ assert kornia.geometry.transform.warp_affine(inp, eye, (0, 4)).shape == (1, 3, 0, 4)
+
+ # The empty result stays attached to the graph, as it does for the warping ops:
+ # _empty_warp_output_2d builds a connected tensor precisely so a batch that
+ # degenerates to a zero-sized output still contributes a zero gradient.
+ grad_inp = torch.rand(1, 3, 4, 4, device=device, dtype=dtype, requires_grad=True)
+ empty = kornia.geometry.transform.resize(grad_inp, (0, 4))
+ assert empty.requires_grad
+ assert empty.dtype == grad_inp.dtype
+ empty.sum().backward()
+ assert grad_inp.grad is not None
+
+ # 2D
+ inp_2d = torch.rand(4, 4, device=device, dtype=dtype)
+ assert kornia.geometry.transform.resize(inp_2d, (0, 4)).shape == (0, 4)
+
+ # 3D
+ inp_3d = torch.rand(3, 4, 4, device=device, dtype=dtype)
+ assert kornia.geometry.transform.resize(inp_3d, (0, 4)).shape == (3, 0, 4)
+
+ # arbitrary dim
+ inp_nd = torch.rand(2, 1, 3, 4, 4, device=device, dtype=dtype)
+ assert kornia.geometry.transform.resize(inp_nd, (0, 4)).shape == (2, 1, 3, 0, 4)
+
+ def test_zero_input_size(self, device, dtype):
+ # A degenerate input is rejected with the message the warping ops already
+ # use, instead of a bare ZeroDivisionError out of the aspect-ratio division.
+ inp = torch.rand(1, 3, 0, 4, device=device, dtype=dtype)
+
+ with pytest.raises(ValueError, match="Input image size must be positive"):
+ kornia.geometry.transform.resize(inp, (2, 2))
+
+ with pytest.raises(ValueError, match="Input image size must be positive"):
+ kornia.geometry.transform.resize(inp, 2)
+
+ # Empty in and empty out is not undefined, so it comes back empty rather than
+ # raising -- the same answer warp_affine and center_crop give.
+ assert kornia.geometry.transform.resize(inp, (0, 4)).shape == (1, 3, 0, 4)
+ assert kornia.geometry.transform.resize(inp, (0, 2)).shape == (1, 3, 0, 2)
+
+ eye = torch.eye(2, 3, device=device, dtype=dtype)[None]
+ assert kornia.geometry.transform.warp_affine(inp, eye, (0, 4)).shape == (1, 3, 0, 4)
+ assert kornia.geometry.transform.center_crop(inp, (0, 4)).shape == (1, 3, 0, 4)
+
def test_downsizeAA(self, device, dtype):
inp = torch.rand(1, 3, 10, 8, device=device, dtype=dtype)
out = kornia.geometry.transform.resize(inp, (5, 3), align_corners=False, antialias=True)
@@ -257,6 +314,15 @@ class TestRescale(BaseTester):
output = kornia.geometry.transform.rescale(input, (1.0 / 3.0, 1.0 / 2.0), align_corners=False)
assert output.shape == (1, 3, 3, 4)
+ def test_zero_factor(self, device, dtype):
+ # A zero factor asks for a zero-sized output, which gives an empty image
+ # rather than a ZeroDivisionError.
+ inp = torch.rand(1, 3, 4, 4, device=device, dtype=dtype)
+
+ assert kornia.geometry.transform.rescale(inp, 0.0).shape == (1, 3, 0, 0)
+ assert kornia.geometry.transform.rescale(inp, (0.0, 1.0)).shape == (1, 3, 0, 4)
+ assert kornia.geometry.transform.Rescale(0.0)(inp).shape == (1, 3, 0, 0)
+
def test_downscale_values(self, device, dtype):
inp_x = torch.arange(20, device=device, dtype=dtype) / 20.0
inp = inp_x[None].T @ inp_x[None]