Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(image): accept an empty batch in the keep-shape decorators (#6293)

Prateekshit Jaiswalc0a03bc5a4c1
diff --git a/changelog.d/6293.fixed.md b/changelog.d/6293.fixed.md
new file mode 100644
index 000000000..74facd303
--- /dev/null
+++ b/changelog.d/6293.fixed.md
@@ -0,0 +1 @@
+The functions `equalize_clahe`, `in_range`, `jpeg_codec_differentiable`, the modules `InRange` and `JPEGCodecDifferentiable`, and the decorators `perform_keep_shape_image` and `perform_keep_shape_video` now accept an empty batch. In 0.9.0, an empty batch or any zero leading dimension raised `ValueError: Invalid input tensor, it is empty.`. Now an empty batch or any zero leading dimension returns an empty result. For example, an input image of shape `(0, 3, H, W)` gives an output of `(0, 3, H, W)`; for a mask returned by `in_range(..., return_mask=True)` or `InRange(..., return_mask=True)` the output shape is `(0, 1, H, W)`. An image with a zero channel, height or width still raises `ValueError`, and for video a zero depth does too. The JPEG codec now also accepts an empty quality tensor for an empty batch. A non-empty batch with an empty quality now raises `ShapeError` instead of the `RuntimeError` from `amin()`.
diff --git a/kornia/enhance/jpeg.py b/kornia/enhance/jpeg.py
index c31e9339c..b225cb903 100644
--- a/kornia/enhance/jpeg.py
+++ b/kornia/enhance/jpeg.py
@@ -175,8 +175,8 @@ def _patchify_8x8(input: torch.Tensor) -> torch.Tensor:
"""
# Get input shape
B, H, W = input.shape
- # Patchify to shape [B, N, H // 8, W // 8]
- output: torch.Tensor = input.view(B, H // 8, 8, W // 8, 8).permute(0, 1, 3, 2, 4).reshape(B, -1, 8, 8)
+ # Patchify to shape [B, N, 8, 8] by first reshaping to [B, H // 8, 8, W // 8, 8] and then permuting and flattening.
+ output: torch.Tensor = input.view(B, H // 8, 8, W // 8, 8).permute(0, 1, 3, 2, 4).flatten(1, 2)
return output
@@ -645,7 +645,8 @@ def jpeg_codec_differentiable(
# capture (torch.compile, torch.export).
if not is_compiling():
KORNIA_CHECK(
- (jpeg_quality.amin().item() >= 0.0) and (jpeg_quality.amax().item() <= 100.0),
+ jpeg_quality.numel() == 0
+ or ((jpeg_quality.amin().item() >= 0.0) and (jpeg_quality.amax().item() <= 100.0)),
lambda: (
"JPEG quality is out of range. Expected range is [0, 100], "
f"got [{jpeg_quality.amin().item()}, {jpeg_quality.amax().item()}]. Consider clipping jpeg_quality."
diff --git a/kornia/image/utils.py b/kornia/image/utils.py
index e9a3312fc..e8f83d4a9 100644
--- a/kornia/image/utils.py
+++ b/kornia/image/utils.py
@@ -364,7 +364,8 @@ def perform_keep_shape_image(f: Callable[..., torch.Tensor]) -> Callable[..., to
``(C, H, W)`` input ``(1, C, H, W)``, and the leading dimensions of a longer input are flattened into ``B``.
The output gets the input's leading dimensions back around ``f``'s own ``C``, ``H`` and ``W``, except that an
``(H, W)`` input gets ``f``'s first channel only; ``f`` must keep the batch size.
- - An empty input raises ``ValueError`` before ``f`` is called.
+ - A zero channel, height or width raises ``ValueError`` before ``f`` is called. Zero leading dimensions, such
+ as an empty batch, are passed to ``f``, so an empty batch gives an empty output.
"""
@wraps(f)
@@ -372,7 +373,7 @@ def perform_keep_shape_image(f: Callable[..., torch.Tensor]) -> Callable[..., to
if not isinstance(input, torch.Tensor):
raise TypeError(f"Input input type is not a torch.Tensor. Got {type(input)}")
- if input.shape.numel() == 0:
+ if 0 in input.shape[-3:]:
raise ValueError("Invalid input tensor, it is empty.")
input_shape = input.shape
@@ -399,6 +400,7 @@ def perform_keep_shape_video(f: Callable[..., torch.Tensor]) -> Callable[..., to
See the Convention block of :func:`~kornia.image.perform_keep_shape_image`, with ``f`` receiving
``(B, C, D, H, W)``: a ``(D, H, W)`` input becomes ``(1, 1, D, H, W)`` and a ``(C, D, H, W)`` input
``(1, C, D, H, W)``.
+ A zero channel, depth, height or width raises ``ValueError``; an empty batch gives an empty output.
"""
@wraps(f)
@@ -406,7 +408,7 @@ def perform_keep_shape_video(f: Callable[..., torch.Tensor]) -> Callable[..., to
if not isinstance(input, torch.Tensor):
raise TypeError(f"Input input type is not a torch.Tensor. Got {type(input)}")
- if input.numel() == 0:
+ if 0 in input.shape[-4:]:
raise ValueError("Invalid input tensor, it is empty.")
input_shape = input.shape
diff --git a/tests/augmentation/test_augmentation.py b/tests/augmentation/test_augmentation.py
index aa400e3f1..4b68d22cf 100644
--- a/tests/augmentation/test_augmentation.py
+++ b/tests/augmentation/test_augmentation.py
@@ -83,7 +83,7 @@ from kornia.augmentation import (
from kornia.augmentation._2d.base import AugmentationBase2D
from kornia.constants import Resample, pi
from kornia.core._compat import torch_version
-from kornia.core.exceptions import BaseError
+from kornia.core.exceptions import BaseError, ShapeError
from kornia.core.utils import _torch_inverse_cast
from kornia.geometry import create_meshgrid, transform_points
@@ -6534,8 +6534,9 @@ class TestRandomJPEGEmptyBatch(BaseTester):
@pytest.mark.parametrize("p", [1.0, 0.5])
@pytest.mark.parametrize("same_on_batch", [False, True])
def test_empty_batch(self, p, same_on_batch, device, dtype):
- # #4429: the differentiable JPEG codec rejects an empty batch, so the augmentation short-circuits it and
- # keeps the shape like the other classes in the empty-batch convention.
+ # #4429: for an empty batch, no JPEG quality is drawn and there are no pixels to code, so the
+ # augmentation bypasses the codec entirely and keeps the input's shape, matching the other
+ # classes' empty-batch convention.
image = torch.rand(0, 3, 8, 10, device=device, dtype=dtype, requires_grad=True)
output = RandomJPEG(p=p, same_on_batch=same_on_batch)(image)
assert output.shape == image.shape
@@ -6546,21 +6547,31 @@ class TestRandomJPEGEmptyBatch(BaseTester):
@pytest.mark.parametrize(
("params_batch", "batch", "error", "match"),
- [(0, 2, RuntimeError, r"amin\(\)"), (2, 0, ValueError, r"Invalid input tensor, it is empty\.")],
+ [
+ (0, 2, ShapeError, r"jpeg_quality needs one quality per image"),
+ (2, 0, ShapeError, r"jpeg_quality needs one quality per image"),
+ ],
)
def test_empty_batch_shortcut_needs_an_empty_batch(self, params_batch, batch, error, match, device, dtype):
- # Replaying parameters drawn for another batch size raises as it did before the empty-batch shortcut; a
+ # Replaying parameters drawn for another batch size still raises, now at the codec's batch-size check; a
# non-empty batch with no drawn quality must not come back uncoded.
aug = RandomJPEG(p=1.0)
params = aug.forward_parameters(torch.Size((params_batch, 3, 8, 10)))
with pytest.raises(error, match=match):
aug(torch.rand(batch, 3, 8, 10, device=device, dtype=dtype), params=params)
- @pytest.mark.parametrize("shape", [(0, 1, 8, 10), (0, 3, 0, 10), (0, 3, 8, 0)])
- def test_empty_batch_keeps_the_input_checks(self, shape, device, dtype):
- # The codec needs three channels and a non-empty image at every batch size, so these empty batches still
- # raise as they did before the empty-batch shortcut.
- with pytest.raises(ValueError, match=r"it is empty|expected 3"):
+ @pytest.mark.parametrize(
+ ("shape", "match"),
+ [
+ ((0, 1, 8, 10), r"expected 3"),
+ ((0, 3, 0, 10), r"it is empty"),
+ ((0, 3, 8, 0), r"it is empty"),
+ ],
+ )
+ def test_empty_batch_keeps_the_input_checks(self, shape, match, device, dtype):
+ # The codec checks for three channels (for (0, 1, 8, 10)) and for non-empty images
+ # (for (0, 3, 0, 10) and (0, 3, 8, 0)).
+ with pytest.raises(ValueError, match=match):
RandomJPEG(p=1.0)(torch.rand(*shape, device=device, dtype=dtype))
diff --git a/tests/enhance/test_equalization.py b/tests/enhance/test_equalization.py
index 3e9279741..8e91dd3be 100644
--- a/tests/enhance/test_equalization.py
+++ b/tests/enhance/test_equalization.py
@@ -165,7 +165,6 @@ class TestEqualization(BaseTester):
@pytest.mark.parametrize(
"B, clip, grid, exception_type, expected_error_msg",
[
- (0, 1.0, (2, 2), ValueError, "Invalid input tensor, it is empty."), # from perform_keep_shape_image
(1, 1, (2, 2), TypeError, "Input clip_limit type is not float. Got"),
(1, 2.0, 2, TypeError, "Input grid_size type is not Tuple. Got"),
(1, 2.0, (2, 2, 2), TypeError, "Input grid_size is not a Tuple with 2 elements. Got 3"),
@@ -668,3 +667,14 @@ class TestEqualization(BaseTester):
).transpose(-2, -1)
self.assert_close(output, output_transposed, low_tolerance=True)
+
+ @pytest.mark.parametrize("shape", [(0, 3, 16, 24), (0, 3, 16, 16), (2, 0, 3, 16, 24)])
+ def test_clahe_empty_batch(self, shape, device, dtype):
+ # An empty batch reaches the function and comes back empty, with the same shape (#6266).
+ x = torch.rand(*shape, device=device, dtype=dtype)
+ out = enhance.equalize_clahe(x, slow_and_differentiable=True)
+ assert out.shape == x.shape
+ assert out.dtype == x.dtype
+ out = enhance.equalize_clahe(x, slow_and_differentiable=False)
+ assert out.shape == x.shape
+ assert out.dtype == x.dtype
diff --git a/tests/enhance/test_jpeg.py b/tests/enhance/test_jpeg.py
index 6af3bd89f..fbc6afc1b 100644
--- a/tests/enhance/test_jpeg.py
+++ b/tests/enhance/test_jpeg.py
@@ -283,6 +283,25 @@ class TestDiffJPEG(BaseTester):
assert "expected 16 or 1, got 8" in str(errinfo.value)
assert "jpeg_quality needs one quality per image" in str(errinfo.value)
+ def test_empty_batch(self, device, dtype):
+ # An empty batch reaches the function and comes back empty, with the same shape (#6266).
+ x = torch.rand(0, 3, 16, 24, device=device, dtype=dtype)
+ no_quality = torch.zeros(0, device=device, dtype=dtype)
+ one_quality = torch.tensor([50.0], device=device, dtype=dtype)
+ out = kornia.enhance.jpeg_codec_differentiable(x, one_quality)
+ assert out.shape == (0, 3, 16, 24)
+ assert out.dtype == dtype
+ out = kornia.enhance.jpeg_codec_differentiable(x, no_quality)
+ assert out.shape == (0, 3, 16, 24)
+ assert out.dtype == dtype
+ module = kornia.enhance.JPEGCodecDifferentiable()
+ out = module(x, no_quality)
+ assert out.shape == (0, 3, 16, 24)
+ assert out.dtype == dtype
+ out = module(x, one_quality)
+ assert out.shape == (0, 3, 16, 24)
+ assert out.dtype == dtype
+
def test_cardinality(self, device, dtype) -> None:
B, H, W = 1, 16, 16
img = torch.zeros(B, 3, H, W, device=device, dtype=dtype)
diff --git a/tests/filters/test_in_range.py b/tests/filters/test_in_range.py
index 6f92a5e1c..6b7b85866 100644
--- a/tests/filters/test_in_range.py
+++ b/tests/filters/test_in_range.py
@@ -490,6 +490,19 @@ class TestInRange(BaseTester):
op_optimized = torch_optimizer(op, fullgraph=True)
self.assert_close(op(data), op_optimized(data))
+ def test_empty_batch(self, device, dtype):
+ # An empty batch reaches the function and comes back empty (#6266).
+ x = torch.rand(0, 3, 16, 24, device=device, dtype=dtype)
+ out = in_range(x, (0.2, 0.2, 0.2), (0.6, 0.6, 0.6), return_mask=True)
+ assert out.shape == (0, 1, 16, 24)
+ assert out.dtype == dtype
+ out = in_range(x, (0.2, 0.2, 0.2), (0.6, 0.6, 0.6), return_mask=False)
+ assert out.shape == (0, 3, 16, 24)
+ assert out.dtype == dtype
+ op = InRange((0.2, 0.2, 0.2), (0.6, 0.6, 0.6), return_mask=True)
+ assert op(x).shape == (0, 1, 16, 24)
+ assert op(x).dtype == dtype
+
class TestConventionsInRange(BaseTester):
def test_convention_in_range_bounds_inclusive_and_all_channels_must_pass(self, device, dtype):
diff --git a/tests/image/test_image_utils.py b/tests/image/test_image_utils.py
index 567a9cc26..d182363d5 100644
--- a/tests/image/test_image_utils.py
+++ b/tests/image/test_image_utils.py
@@ -207,6 +207,38 @@ def test_perform_keep_shape_video_non_contiguous(device, dtype):
assert_close(result, expected)
[email protected]("shape", [(0, 3, 16, 24), (2, 0, 3, 16, 24), (0, 2, 3, 16, 24)])
+def test_perform_keep_shape_image_empty_batch(device, dtype, shape):
+ # An empty batch reaches the function and comes back empty, with the same shape (#6266).
+ op = kornia.image.perform_keep_shape_image(lambda x: x * 2)
+ assert op(torch.rand(*shape, device=device, dtype=dtype)).shape == shape
+
+
+ "shape", [(2, 0, 16, 24), (2, 3, 0, 24), (2, 3, 16, 0), (16, 0), (0, 16, 24), (2, 2, 0, 16, 24)]
+)
+def test_perform_keep_shape_image_rejects_a_zero_image_size(device, dtype, shape):
+ # A zero channel, height or width raises `ValueError` before `f` is called.
+ op = kornia.image.perform_keep_shape_image(lambda x: x * 2)
+ with pytest.raises(ValueError, match="it is empty"): # should raise ValueError before calling the function
+ op(torch.rand(*shape, device=device, dtype=dtype))
+
+
[email protected]("shape", [(0, 3, 4, 16, 24), (2, 0, 3, 4, 16, 24)])
+def test_perform_keep_shape_video_empty_batch(device, dtype, shape):
+ # An empty batch reaches the function and comes back empty, with the same shape (#6266).
+ op = kornia.image.perform_keep_shape_video(lambda x: x * 2)
+ assert op(torch.rand(*shape, device=device, dtype=dtype)).shape == shape
+
+
[email protected]("shape", [(2, 0, 4, 16, 24), (2, 3, 0, 16, 24), (2, 3, 4, 0, 24), (2, 3, 4, 16, 0)])
+def test_perform_keep_shape_video_rejects_a_zero_image_size(device, dtype, shape):
+ # A zero channel, depth, height or width raises `ValueError` before `f` is called.
+ op = kornia.image.perform_keep_shape_video(lambda x: x * 2)
+ with pytest.raises(ValueError, match="it is empty"): # should raise ValueError before calling the function
+ op(torch.rand(*shape, device=device, dtype=dtype))
+
+
class TestMakeGrid(BaseTester):
@pytest.mark.parametrize(
"batch_size,n_row,rows,columns",