Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

Resize regardless of number of dims, considering the last two dims as image (#1047)

Duc Nguyene8aa48ce5d9b
diff --git a/kornia/geometry/transform/affwarp.py b/kornia/geometry/transform/affwarp.py
index 3554a82bc..cf759c11f 100644
--- a/kornia/geometry/transform/affwarp.py
+++ b/kornia/geometry/transform/affwarp.py
@@ -5,11 +5,13 @@ import torch.nn as nn
from math import ceil
+from functools import wraps
+
import kornia
from kornia.geometry.transform.imgwarp import warp_affine, get_rotation_matrix2d, get_affine_matrix2d
from kornia.geometry.transform.projwarp import warp_affine3d, get_projective_transform
from kornia.utils import _extract_device_dtype
-from kornia.utils.image import _to_bchw
+from kornia.utils.image import perform_keep_shape
__all__ = [
"affine",
@@ -512,6 +514,7 @@ def _side_to_image_size(side_size: int, aspect_ratio: float, side: str = "short"
return int(side_size / aspect_ratio), side_size
+@perform_keep_shape
def resize(
input: torch.Tensor,
size: Union[int, Tuple[int, int]],
@@ -523,7 +526,8 @@ def resize(
r"""Resize the input torch.Tensor to the given size.
Args:
- tensor (torch.Tensor): The image tensor to be skewed with shape of :math:`(B, C, H, W)`.
+ tensor (torch.Tensor): The image tensor to be skewed with shape of :math:`(..., H, W)`.
+ `...` means there can be any number of dimensions.
size (int, tuple(int, int)): Desired output size. If size is a sequence like (h, w),
output size will be matched to this. If size is an int, smaller edge of the image will
be matched to this number. i.e, if height > width, then image will be rescaled
@@ -550,6 +554,9 @@ def resize(
if not isinstance(input, torch.Tensor):
raise TypeError("Input tensor type is not a torch.Tensor. Got {}".format(type(input)))
+ if len(input.shape) < 2:
+ raise ValueError('Input tensor must have at least two dimensions. Got {}'.format(len(input.shape)))
+
input_size = h, w = input.shape[-2:]
if isinstance(size, int):
aspect_ratio = w / h
@@ -558,9 +565,6 @@ def resize(
if size == input_size:
return input
- # TODO: find a proper way to handle this cases in the future
- input_tmp = _to_bchw(input)
-
factors = (h / size[0], w / size[1])
# We do bluring only for downscaling
@@ -574,13 +578,9 @@ def resize(
# https://github.com/python-pillow/Pillow/blob/master/src/libImaging/Resample.c#L206
# But they do it in the 2 passes, which gives better results. Let's try 2 sigmas for now
ks = int(2.0 * 2 * sigmas[0] + 1), int(2.0 * 2 * sigmas[1] + 1)
- input_tmp = kornia.filters.gaussian_blur2d(input_tmp, ks, sigmas)
-
- output = torch.nn.functional.interpolate(input_tmp, size=size, mode=interpolation, align_corners=align_corners)
-
- if len(input.shape) != len(output.shape):
- output = output.squeeze()
+ input = kornia.filters.gaussian_blur2d(input, ks, sigmas)
+ output = torch.nn.functional.interpolate(input, size=size, mode=interpolation, align_corners=align_corners)
return output
diff --git a/kornia/utils/image.py b/kornia/utils/image.py
index 3d8dad49d..7986edeac 100644
--- a/kornia/utils/image.py
+++ b/kornia/utils/image.py
@@ -3,6 +3,7 @@ from typing import Optional
import numpy as np
import torch
import torch.nn as nn
+from functools import wraps
def image_to_tensor(image: np.ndarray, keepdim: bool = True) -> torch.Tensor:
@@ -152,3 +153,24 @@ class ImageToTensor(nn.Module):
def forward(self, x: np.ndarray) -> torch.Tensor:
return image_to_tensor(x, keepdim=self.keepdim)
+
+
+def perform_keep_shape(f):
+ """TODO: where can we put this?"""
+
+ @wraps(f)
+ def _wrapper(input, *args, **kwargs):
+ input_shape = input.shape
+ if len(input_shape) == 2:
+ input = input[None]
+
+ dont_care_shape = input.shape[:-3]
+ input = input.view(-1, input.shape[-3], input.shape[-2], input.shape[-1])
+
+ output = f(input, *args, **kwargs)
+ output = output.view(*(dont_care_shape + output.shape[-3:]))
+ if len(input_shape) == 2:
+ output = output[0]
+ return output
+
+ return _wrapper
diff --git a/test/geometry/transform/test_affine.py b/test/geometry/transform/test_affine.py
index c8d4d1ff4..65bb7ef22 100644
--- a/test/geometry/transform/test_affine.py
+++ b/test/geometry/transform/test_affine.py
@@ -13,46 +13,161 @@ class TestResize:
out = kornia.resize(inp, (3, 4))
assert_allclose(inp, out, atol=1e-4, rtol=1e-4)
- def test_no_batch(self, device, dtype):
+ # 2D
+ inp = torch.rand(3, 4, device=device, dtype=dtype)
+ out = kornia.resize(inp, (3, 4))
+ assert_allclose(inp, out, atol=1e-4, rtol=1e-4)
+
+ # 3D
inp = torch.rand(3, 3, 4, device=device, dtype=dtype)
- out = kornia.resize(inp, (2, 5))
- assert out.shape == (3, 2, 5)
+ out = kornia.resize(inp, (3, 4))
+ assert_allclose(inp, out, atol=1e-4, rtol=1e-4)
+
+ # arbitrary dim
+ inp = torch.rand(1, 2, 3, 2, 1, 3, 3, 4, device=device, dtype=dtype)
+ out = kornia.resize(inp, (3, 4))
+ assert_allclose(inp, out, atol=1e-4, rtol=1e-4)
def test_upsize(self, device, dtype):
inp = torch.rand(1, 3, 3, 4, device=device, dtype=dtype)
out = kornia.resize(inp, (6, 8))
assert out.shape == (1, 3, 6, 8)
+ # 2D
+ inp = torch.rand(3, 4, device=device, dtype=dtype)
+ out = kornia.resize(inp, (6, 8))
+ assert out.shape == (6, 8)
+
+ # 3D
+ inp = torch.rand(3, 3, 4, device=device, dtype=dtype)
+ out = kornia.resize(inp, (6, 8))
+ assert out.shape == (3, 6, 8)
+
+ # arbitrary dim
+ inp = torch.rand(1, 2, 3, 2, 1, 3, 3, 4, device=device, dtype=dtype)
+ out = kornia.resize(inp, (6, 8))
+ assert out.shape == (1, 2, 3, 2, 1, 3, 6, 8)
+
def test_downsize(self, device, dtype):
inp = torch.rand(1, 3, 5, 2, device=device, dtype=dtype)
out = kornia.resize(inp, (3, 1))
assert out.shape == (1, 3, 3, 1)
+ # 2D
+ inp = torch.rand(5, 2, device=device, dtype=dtype)
+ out = kornia.resize(inp, (3, 1))
+ assert out.shape == (3, 1)
+
+ # 3D
+ inp = torch.rand(3, 5, 2, device=device, dtype=dtype)
+ out = kornia.resize(inp, (3, 1))
+ assert out.shape == (3, 3, 1)
+
+ # arbitrary dim
+ inp = torch.rand(1, 2, 3, 2, 1, 3, 5, 2, device=device, dtype=dtype)
+ out = kornia.resize(inp, (3, 1))
+ assert out.shape == (1, 2, 3, 2, 1, 3, 3, 1)
+
def test_downsizeAA(self, device, dtype):
inp = torch.rand(1, 3, 10, 8, device=device, dtype=dtype)
out = kornia.resize(inp, (5, 3), antialias=True)
assert out.shape == (1, 3, 5, 3)
+ # 2D
+ inp = torch.rand(10, 8, device=device, dtype=dtype)
+ out = kornia.resize(inp, (5, 3), antialias=True)
+ assert out.shape == (5, 3)
+
+ # 3D
+ inp = torch.rand(3, 10, 8, device=device, dtype=dtype)
+ out = kornia.resize(inp, (5, 3), antialias=True)
+ assert out.shape == (3, 5, 3)
+
+ # arbitrary dim
+ inp = torch.rand(1, 2, 3, 2, 1, 3, 10, 8, device=device, dtype=dtype)
+ out = kornia.resize(inp, (5, 3), antialias=True)
+ assert out.shape == (1, 2, 3, 2, 1, 3, 5, 3)
+
def test_one_param(self, device, dtype):
inp = torch.rand(1, 3, 5, 2, device=device, dtype=dtype)
out = kornia.resize(inp, 10)
assert out.shape == (1, 3, 25, 10)
+ # 2D
+ inp = torch.rand(5, 2, device=device, dtype=dtype)
+ out = kornia.resize(inp, 10)
+ assert out.shape == (25, 10)
+
+ # 3D
+ inp = torch.rand(3, 5, 2, device=device, dtype=dtype)
+ out = kornia.resize(inp, 10)
+ assert out.shape == (3, 25, 10)
+
+ # arbitrary dim
+ inp = torch.rand(1, 2, 3, 2, 1, 3, 5, 2, device=device, dtype=dtype)
+ out = kornia.resize(inp, 10)
+ assert out.shape == (1, 2, 3, 2, 1, 3, 25, 10)
+
def test_one_param_long(self, device, dtype):
inp = torch.rand(1, 3, 5, 2, device=device, dtype=dtype)
out = kornia.resize(inp, 10, side="long")
assert out.shape == (1, 3, 10, 4)
+ # 2D
+ inp = torch.rand(5, 2, device=device, dtype=dtype)
+ out = kornia.resize(inp, 10, side="long")
+ assert out.shape == (10, 4)
+
+ # 3D
+ inp = torch.rand(3, 5, 2, device=device, dtype=dtype)
+ out = kornia.resize(inp, 10, side="long")
+ assert out.shape == (3, 10, 4)
+
+ # arbitrary dim
+ inp = torch.rand(1, 2, 3, 2, 1, 3, 5, 2, device=device, dtype=dtype)
+ out = kornia.resize(inp, 10, side="long")
+ assert out.shape == (1, 2, 3, 2, 1, 3, 10, 4)
+
def test_one_param_vert(self, device, dtype):
inp = torch.rand(1, 3, 5, 2, device=device, dtype=dtype)
out = kornia.resize(inp, 10, side="vert")
assert out.shape == (1, 3, 10, 4)
+ # 2D
+ inp = torch.rand(5, 2, device=device, dtype=dtype)
+ out = kornia.resize(inp, 10, side="vert")
+ assert out.shape == (10, 4)
+
+ # 3D
+ inp = torch.rand(3, 5, 2, device=device, dtype=dtype)
+ out = kornia.resize(inp, 10, side="vert")
+ assert out.shape == (3, 10, 4)
+
+ # arbitrary dim
+ inp = torch.rand(1, 2, 3, 2, 1, 3, 5, 2, device=device, dtype=dtype)
+ out = kornia.resize(inp, 10, side="vert")
+ assert out.shape == (1, 2, 3, 2, 1, 3, 10, 4)
+
def test_one_param_horz(self, device, dtype):
inp = torch.rand(1, 3, 2, 5, device=device, dtype=dtype)
out = kornia.resize(inp, 10, side="horz")
assert out.shape == (1, 3, 4, 10)
+ # 2D
+ inp = torch.rand(1, 3, 2, 5, device=device, dtype=dtype)
+ out = kornia.resize(inp, 10, side="horz")
+ assert out.shape == (1, 3, 4, 10)
+
+ # 3D
+ inp = torch.rand(1, 3, 2, 5, device=device, dtype=dtype)
+ out = kornia.resize(inp, 10, side="horz")
+ assert out.shape == (1, 3, 4, 10)
+
+ # arbitrary dim
+ inp = torch.rand(1, 3, 2, 5, device=device, dtype=dtype)
+ out = kornia.resize(inp, 10, side="horz")
+ assert out.shape == (1, 3, 4, 10)
+
def test_gradcheck(self, device, dtype):
# test parameters
new_size = 4