Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(image): support non-contiguous tensors in shape decorators (#4615)

msparsh1366063729e8dc
diff --git a/changelog.d/4615.fixed.md b/changelog.d/4615.fixed.md
new file mode 100644
index 000000000..395364048
--- /dev/null
+++ b/changelog.d/4615.fixed.md
@@ -0,0 +1,4 @@
+`in_range`, `normalize_min_max`, `posterize`, `sharpness`, `equalize`,
+`equalize_clahe`, `jpeg_codec_differentiable` and `equalize3d` now accept
+non-contiguous inputs of more than 4 (resp. 5) dimensions instead of raising a raw
+`view size is not compatible` error.
diff --git a/kornia/image/utils.py b/kornia/image/utils.py
index fc38a88b1..9e06eb993 100644
--- a/kornia/image/utils.py
+++ b/kornia/image/utils.py
@@ -131,7 +131,7 @@ def _to_bchw(tensor: torch.Tensor) -> torch.Tensor:
tensor = tensor.unsqueeze(0)
if len(tensor.shape) > 4:
- tensor = tensor.view(-1, tensor.shape[-3], tensor.shape[-2], tensor.shape[-1])
+ tensor = tensor.reshape(-1, tensor.shape[-3], tensor.shape[-2], tensor.shape[-1])
return tensor
@@ -159,7 +159,7 @@ def _to_bcdhw(tensor: torch.Tensor) -> torch.Tensor:
tensor = tensor.unsqueeze(0)
if len(tensor.shape) > 5:
- tensor = tensor.view(-1, tensor.shape[-4], tensor.shape[-3], tensor.shape[-2], tensor.shape[-1])
+ tensor = tensor.reshape(-1, tensor.shape[-4], tensor.shape[-3], tensor.shape[-2], tensor.shape[-1])
return tensor
@@ -306,7 +306,7 @@ def make_grid(tensor: torch.Tensor, n_row: Optional[int] = None, padding: int =
def perform_keep_shape_image(f: Callable[..., torch.Tensor]) -> Callable[..., torch.Tensor]:
"""Apply `f` to an image of arbitrary leading dimensions `(*, C, H, W)`.
- It works by first viewing the image as `(B, C, H, W)`, applying the function and re-viewing the image as original
+ The input is reshaped to `(B, C, H, W)`, the function is applied, and the output is reshaped back to the original
shape.
"""
@@ -319,7 +319,7 @@ def perform_keep_shape_image(f: Callable[..., torch.Tensor]) -> Callable[..., to
raise ValueError("Invalid input tensor, it is empty.")
input_shape = input.shape
- input = _to_bchw(input) # view input as (B, C, H, W)
+ input = _to_bchw(input) # reshape input as (B, C, H, W)
output = f(input, *args, **kwargs)
if len(input_shape) == 3:
output = output[0]
@@ -328,7 +328,7 @@ def perform_keep_shape_image(f: Callable[..., torch.Tensor]) -> Callable[..., to
output = output[0, 0]
if len(input_shape) > 4:
- output = output.view(*(input_shape[:-3] + output.shape[-3:]))
+ output = output.reshape(*(input_shape[:-3] + output.shape[-3:]))
return output
@@ -338,7 +338,7 @@ def perform_keep_shape_image(f: Callable[..., torch.Tensor]) -> Callable[..., to
def perform_keep_shape_video(f: Callable[..., torch.Tensor]) -> Callable[..., torch.Tensor]:
"""Apply `f` to an image of arbitrary leading dimensions `(*, C, D, H, W)`.
- It works by first viewing the image as `(B, C, D, H, W)`, applying the function and re-viewing the image as original
+ The input is reshaped to `(B, C, D, H, W)`, the function is applied, and the output is reshaped back to the original
shape.
"""
@@ -351,7 +351,7 @@ def perform_keep_shape_video(f: Callable[..., torch.Tensor]) -> Callable[..., to
raise ValueError("Invalid input tensor, it is empty.")
input_shape = input.shape
- input = _to_bcdhw(input) # view input as (B, C, D, H, W)
+ input = _to_bcdhw(input) # reshape input as (B, C, D, H, W)
output = f(input, *args, **kwargs)
if len(input_shape) == 4:
output = output[0]
@@ -360,7 +360,7 @@ def perform_keep_shape_video(f: Callable[..., torch.Tensor]) -> Callable[..., to
output = output[0, 0]
if len(input_shape) > 5:
- output = output.view(*(input_shape[:-4] + output.shape[-4:]))
+ output = output.reshape(*(input_shape[:-4] + output.shape[-4:]))
return output
diff --git a/tests/image/test_image_utils.py b/tests/image/test_image_utils.py
index f61b71996..340c877f6 100644
--- a/tests/image/test_image_utils.py
+++ b/tests/image/test_image_utils.py
@@ -135,3 +135,67 @@ def test_tensor_to_image_contiguous(device, dtype):
image = kornia.image.tensor_to_image(tensor, force_contiguous=True)
assert image.flags["C_CONTIGUOUS"]
+
+
+ "op, kwargs",
+ [
+ (kornia.filters.in_range, {"lower": (0.2, 0.3, 0.4), "upper": (0.8, 0.7, 0.9)}),
+ (kornia.enhance.normalize_min_max, {}),
+ (kornia.enhance.posterize, {"bits": 4}),
+ (kornia.enhance.sharpness, {"factor": 1.0}),
+ (kornia.enhance.equalize, {}),
+ (kornia.enhance.equalize_clahe, {"clip_limit": 40.0, "grid_size": (8, 8)}),
+ (kornia.enhance.jpeg_codec_differentiable, {}),
+ ],
+)
+def test_perform_keep_shape_image_non_contiguous(device, dtype, op, kwargs):
+ tensor = torch.rand(2, 3, 3, 16, 24, device=device, dtype=dtype).transpose(0, 1)
+ assert not tensor.is_contiguous()
+
+ if op is kornia.enhance.jpeg_codec_differentiable:
+ batch_size = tensor.shape[0] * tensor.shape[1]
+ jpeg_quality = torch.linspace(30.0, 90.0, batch_size, device=device, dtype=dtype)
+
+ result = op(tensor, jpeg_quality)
+
+ expected = torch.stack(
+ [
+ torch.stack(
+ [
+ op(
+ tensor[i, j],
+ jpeg_quality[i * tensor.shape[1] + j : i * tensor.shape[1] + j + 1],
+ )
+ for j in range(tensor.shape[1])
+ ]
+ )
+ for i in range(tensor.shape[0])
+ ]
+ )
+ else:
+ result = op(tensor, **kwargs)
+
+ expected = torch.stack(
+ [torch.stack([op(tensor[i, j], **kwargs) for j in range(tensor.shape[1])]) for i in range(tensor.shape[0])]
+ )
+
+ assert result.shape == expected.shape
+ assert_close(result, expected)
+
+
+def test_perform_keep_shape_video_non_contiguous(device, dtype):
+ tensor = torch.rand(2, 2, 3, 4, 32, 32, device=device, dtype=dtype).transpose(0, 1)
+ assert not tensor.is_contiguous()
+
+ result = kornia.enhance.equalize3d(tensor)
+
+ expected = torch.stack(
+ [
+ torch.stack([kornia.enhance.equalize3d(tensor[i, j]) for j in range(tensor.shape[1])])
+ for i in range(tensor.shape[0])
+ ]
+ )
+
+ assert result.shape == expected.shape
+ assert_close(result, expected)