Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

Fixes warp_affine and warp_perspective (#896)

Edgar Ribad261b98154e1
diff --git a/kornia/augmentation/augmentation.py b/kornia/augmentation/augmentation.py
index 2dd20d91a..9203b3988 100644
--- a/kornia/augmentation/augmentation.py
+++ b/kornia/augmentation/augmentation.py
@@ -838,9 +838,9 @@ class RandomResizedCrop(AugmentationBase2D):
... [6., 7., 8.]]])
>>> aug = RandomResizedCrop(size=(3, 3), scale=(3., 3.), ratio=(2., 2.), p=1.)
>>> aug(inputs)
- tensor([[[[1.2500, 1.7500, 1.5000],
- [4.2500, 4.7500, 3.7500],
- [7.2500, 7.7500, 6.0000]]]])
+ tensor([[[[1.0000, 1.5000, 2.0000],
+ [4.0000, 4.5000, 5.0000],
+ [7.0000, 7.5000, 8.0000]]]])
"""
def __init__(
@@ -848,7 +848,7 @@ class RandomResizedCrop(AugmentationBase2D):
ratio: Union[torch.Tensor, Tuple[float, float]] = (3. / 4., 4. / 3.),
resample: Union[str, int, Resample] = Resample.BILINEAR.name,
return_transform: bool = False, same_on_batch: bool = False,
- align_corners: bool = False, p: float = 1., keepdim: bool = False
+ align_corners: bool = True, p: float = 1., keepdim: bool = False
) -> None:
# Since PyTorch does not support ragged tensor. So cropping function happens all the time.
super(RandomResizedCrop, self).__init__(
diff --git a/kornia/augmentation/functional/functional.py b/kornia/augmentation/functional/functional.py
index 956f33bf2..9827a41df 100644
--- a/kornia/augmentation/functional/functional.py
+++ b/kornia/augmentation/functional/functional.py
@@ -429,7 +429,7 @@ def apply_perspective(
out_data = warp_perspective(
input, transform, (height, width),
- flags=resample_name, align_corners=align_corners)
+ mode=resample_name, align_corners=align_corners)
return out_data.view_as(input)
diff --git a/kornia/geometry/transform/crop/crop2d.py b/kornia/geometry/transform/crop/crop2d.py
index e579605e5..ce95b3e73 100644
--- a/kornia/geometry/transform/crop/crop2d.py
+++ b/kornia/geometry/transform/crop/crop2d.py
@@ -1,4 +1,4 @@
-from typing import Tuple, Union
+from typing import Tuple, Union, Optional
import torch
@@ -18,8 +18,9 @@ __all__ = [
def crop_and_resize(tensor: torch.Tensor, boxes: torch.Tensor, size: Tuple[int, int],
- interpolation: str = 'bilinear', align_corners: bool = False) -> torch.Tensor:
- r"""Extract crops from 2D images (4D tensor) and resize them.
+ mode: str = 'bilinear', padding_mode: str = 'zeros',
+ align_corners: Optional[bool] = None) -> torch.Tensor:
+ r"""Extract crops from 2D images (4D tensor) and resize given a bounding box.
Args:
tensor (torch.Tensor): the 2D image tensor with shape (B, C, H, W).
@@ -29,9 +30,11 @@ def crop_and_resize(tensor: torch.Tensor, boxes: torch.Tensor, size: Tuple[int,
The coordinates would compose a rectangle with a shape of (N1, N2).
size (Tuple[int, int]): a tuple with the height and width that will be
used to resize the extracted patches.
- interpolation (str): Interpolation flag. Default: 'bilinear'.
- align_corners (bool): mode for grid_generation. Default: False. See
- https://pytorch.org/docs/stable/nn.functional.html#torch.nn.functional.interpolate for details.
+ mode (str): interpolation mode to calculate output values
+ 'bilinear' | 'nearest'. Default: 'bilinear'.
+ padding_mode (str): padding mode for outside grid values
+ 'zeros' | 'border' | 'reflection'. Default: 'zeros'.
+ align_corners (bool, optional): mode for grid_generation. Default: None.
Returns:
torch.Tensor: tensor containing the patches with shape BxCxN1xN2.
@@ -49,26 +52,30 @@ def crop_and_resize(tensor: torch.Tensor, boxes: torch.Tensor, size: Tuple[int,
... [2., 2.],
... [1., 2.],
... ]]) # 1x4x2
- >>> crop_and_resize(input, boxes, (2, 2), interpolation='nearest', align_corners=True)
+ >>> crop_and_resize(input, boxes, (2, 2), mode='nearest')
tensor([[[[ 6., 7.],
[10., 11.]]]])
"""
if not isinstance(tensor, torch.Tensor):
raise TypeError("Input tensor type is not a torch.Tensor. Got {}"
.format(type(tensor)))
+
if not isinstance(boxes, torch.Tensor):
raise TypeError("Input boxes type is not a torch.Tensor. Got {}"
.format(type(boxes)))
+
if not isinstance(size, (tuple, list,)) and len(size) == 2:
raise ValueError("Input size must be a tuple/list of length 2. Got {}"
.format(size))
+
assert len(tensor.shape) == 4, f"Only tensor with shape (B, C, H, W) supported. Got {tensor.shape}."
+
# unpack input data
dst_h, dst_w = size
# [x, y] origin
# top-left, top-right, bottom-right, bottom-left
- points_src: torch.Tensor = boxes
+ points_src: torch.Tensor = boxes.to(tensor)
# [x, y] destination
# top-left, top-right, bottom-right, bottom-left
@@ -77,23 +84,26 @@ def crop_and_resize(tensor: torch.Tensor, boxes: torch.Tensor, size: Tuple[int,
[dst_w - 1, 0],
[dst_w - 1, dst_h - 1],
[0, dst_h - 1],
- ]], device=tensor.device).expand(points_src.shape[0], -1, -1)
+ ]], device=tensor.device, dtype=tensor.dtype).expand(points_src.shape[0], -1, -1)
- return crop_by_boxes(tensor, points_src, points_dst, interpolation, align_corners)
+ return crop_by_boxes(tensor, points_src, points_dst, mode, padding_mode, align_corners)
def center_crop(tensor: torch.Tensor, size: Tuple[int, int],
- interpolation: str = 'bilinear',
- align_corners: bool = True) -> torch.Tensor:
- r"""Crop the 2D images (4D tensor) at the center.
+ mode: str = 'bilinear', padding_mode: str = 'zeros',
+ align_corners: Optional[bool] = None) -> torch.Tensor:
+ r"""Crop the 2D images (4D tensor) from the center.
Args:
tensor (torch.Tensor): the 2D image tensor with shape (B, C, H, W).
size (Tuple[int, int]): a tuple with the expected height and width
of the output patch.
- interpolation (str): Interpolation flag. Default: 'bilinear'.
- align_corners (bool): mode for grid_generation. Default: False. See
- https://pytorch.org/docs/stable/nn.functional.html#torch.nn.functional.interpolate for details
+ mode (str): interpolation mode to calculate output values
+ 'bilinear' | 'nearest'. Default: 'bilinear'.
+ padding_mode (str): padding mode for outside grid values
+ 'zeros' | 'border' | 'reflection'. Default: 'zeros'.
+ align_corners (bool, optional): mode for grid_generation. Default: None.
+
Returns:
torch.Tensor: the output tensor with patches.
@@ -104,16 +114,18 @@ def center_crop(tensor: torch.Tensor, size: Tuple[int, int],
... [9., 10., 11., 12.],
... [13., 14., 15., 16.],
... ]]])
- >>> center_crop(input, (2, 4), interpolation='nearest', align_corners=True)
+ >>> center_crop(input, (2, 4), mode='nearest')
tensor([[[[ 5., 6., 7., 8.],
[ 9., 10., 11., 12.]]]])
"""
if not isinstance(tensor, torch.Tensor):
raise TypeError("Input tensor type is not a torch.Tensor. Got {}"
.format(type(tensor)))
+
if not isinstance(size, (tuple, list,)) and len(size) == 2:
raise ValueError("Input size must be a tuple/list of length 2. Got {}"
.format(size))
+
assert len(tensor.shape) == 4, f"Only tensor with shape (B, C, H, W) supported. Got {tensor.shape}."
# unpack input sizes
@@ -121,16 +133,17 @@ def center_crop(tensor: torch.Tensor, size: Tuple[int, int],
src_h, src_w = tensor.shape[-2:]
# compute start/end offsets
- dst_h_half = dst_h / 2
- dst_w_half = dst_w / 2
- src_h_half = src_h / 2
- src_w_half = src_w / 2
+ dst_h_half: float = dst_h / 2
+ dst_w_half: float = dst_w / 2
+ src_h_half: float = src_h / 2
+ src_w_half: float = src_w / 2
+
+ start_x: float = src_w_half - dst_w_half
+ start_y: float = src_h_half - dst_h_half
- start_x = src_w_half - dst_w_half
- start_y = src_h_half - dst_h_half
+ end_x: float = start_x + dst_w - 1
+ end_y: float = start_y + dst_h - 1
- end_x = start_x + dst_w - 1
- end_y = start_y + dst_h - 1
# [y, x] origin
# top-left, top-right, bottom-right, bottom-left
points_src: torch.Tensor = torch.tensor([[
@@ -138,7 +151,7 @@ def center_crop(tensor: torch.Tensor, size: Tuple[int, int],
[end_x, start_y],
[end_x, end_y],
[start_x, end_y],
- ]], device=tensor.device)
+ ]], device=tensor.device, dtype=tensor.dtype)
# [y, x] destination
# top-left, top-right, bottom-right, bottom-left
@@ -147,17 +160,16 @@ def center_crop(tensor: torch.Tensor, size: Tuple[int, int],
[dst_w - 1, 0],
[dst_w - 1, dst_h - 1],
[0, dst_h - 1],
- ]], device=tensor.device).expand(points_src.shape[0], -1, -1)
- return crop_by_boxes(tensor,
- points_src.to(tensor.dtype),
- points_dst.to(tensor.dtype),
- interpolation,
- align_corners)
+ ]], device=tensor.device, dtype=tensor.dtype).expand(points_src.shape[0], -1, -1)
+
+ return crop_by_boxes(tensor, points_src, points_dst,
+ mode, padding_mode, align_corners)
def crop_by_boxes(tensor: torch.Tensor, src_box: torch.Tensor, dst_box: torch.Tensor,
- interpolation: str = 'bilinear', align_corners: bool = False) -> torch.Tensor:
- """Perform crop transform on 2D images (4D tensor) by bounding boxes.
+ mode: str = 'bilinear', padding_mode: str = 'zeros',
+ align_corners: Optional[bool] = None) -> torch.Tensor:
+ """Perform crop transform on 2D images (4D tensor) given two bounding boxes.
Given an input tensor, this function selected the interested areas by the provided bounding boxes (src_box).
Then the selected areas would be fitted into the targeted bounding boxes (dst_box) by a perspective transformation.
@@ -172,9 +184,11 @@ def crop_by_boxes(tensor: torch.Tensor, src_box: torch.Tensor, dst_box: torch.Te
dst_box (torch.Tensor): a tensor with shape (B, 4, 2) containing the coordinates of the bounding boxes
to be placed. The tensor must have the shape of Bx4x2, where each box is defined in the clockwise
order: top-left, top-right, bottom-right and bottom-left. The coordinates must be in x, y order.
- interpolation (str): Interpolation flag. Default: 'bilinear'.
- align_corners (bool): mode for grid_generation. Default: False. See
- https://pytorch.org/docs/stable/nn.functional.html#torch.nn.functional.interpolate for details
+ mode (str): interpolation mode to calculate output values
+ 'bilinear' | 'nearest'. Default: 'bilinear'.
+ padding_mode (str): padding mode for outside grid values
+ 'zeros' | 'border' | 'reflection'. Default: 'zeros'.
+ align_corners (bool, optional): mode for grid_generation. Default: None.
Returns:
torch.Tensor: the output tensor with patches.
@@ -201,6 +215,7 @@ def crop_by_boxes(tensor: torch.Tensor, src_box: torch.Tensor, dst_box: torch.Te
If the src_box is smaller than dst_box, the following error will be thrown.
RuntimeError: solve_cpu: For batch 0: U(2,2) is zero, singular U.
"""
+ # TODO: improve this since might slow down the function
validate_bboxes(src_box)
validate_bboxes(dst_box)
@@ -208,16 +223,23 @@ def crop_by_boxes(tensor: torch.Tensor, src_box: torch.Tensor, dst_box: torch.Te
# compute transformation between points and warp
# Note: Tensor.dtype must be float. "solve_cpu" not implemented for 'Long'
- dst_trans_src: torch.Tensor = get_perspective_transform(src_box.to(tensor.dtype), dst_box.to(tensor.dtype))
+ dst_trans_src: torch.Tensor = get_perspective_transform(
+ src_box.to(tensor), dst_box.to(tensor))
+
# simulate broadcasting
- dst_trans_src = dst_trans_src.expand(tensor.shape[0], -1, -1).type_as(tensor)
+ dst_trans_src = dst_trans_src.expand(tensor.shape[0], -1, -1)
- bbox = infer_box_shape(dst_box)
+ bbox: Tuple[torch.Tensor, torch.Tensor] = infer_box_shape(dst_box)
assert (bbox[0] == bbox[0][0]).all() and (bbox[1] == bbox[1][0]).all(), (
- f"Cropping height, width and depth must be exact same in a batch. Got height {bbox[0]} and width {bbox[1]}.")
+ f"Cropping height, width and depth must be exact same in a batch. "
+ f"Got height {bbox[0]} and width {bbox[1]}.")
+
+ h_out: int = int(bbox[0][0].item())
+ w_out: int = int(bbox[1][0].item())
+
patches: torch.Tensor = warp_affine(
- tensor, dst_trans_src[:, :2, :], (int(bbox[0][0].item()), int(bbox[1][0].item())),
- flags=interpolation, align_corners=align_corners)
+ tensor, dst_trans_src[:, :2, :], (h_out, w_out),
+ mode=mode, padding_mode=padding_mode, align_corners=align_corners)
return patches
diff --git a/kornia/geometry/transform/imgwarp.py b/kornia/geometry/transform/imgwarp.py
index abcea11b7..05556764c 100644
--- a/kornia/geometry/transform/imgwarp.py
+++ b/kornia/geometry/transform/imgwarp.py
@@ -1,4 +1,5 @@
from typing import Tuple, Optional
+import warnings
import torch
import torch.nn.functional as F
@@ -12,7 +13,9 @@ from kornia.geometry.conversions import (
from kornia.geometry.transform.projwarp import (
get_projective_transform
)
-from kornia.testing import check_is_tensor
+from kornia.utils import create_meshgrid
+from kornia.geometry.linalg import transform_points
+
__all__ = [
"warp_perspective",
@@ -29,23 +32,9 @@ __all__ = [
]
-def transform_warp_impl(src: torch.Tensor, dst_pix_trans_src_pix: torch.Tensor,
- dsize_src: Tuple[int, int], dsize_dst: Tuple[int, int],
- grid_mode: str, padding_mode: str,
- align_corners: bool) -> torch.Tensor:
- """Compute the transform in normalized coordinates and perform the warping.
- """
- dst_norm_trans_src_norm: torch.Tensor = normalize_homography(
- dst_pix_trans_src_pix, dsize_src, dsize_dst)
-
- src_norm_trans_dst_norm = torch.inverse(dst_norm_trans_src_norm)
- return homography_warp(src, src_norm_trans_dst_norm, dsize_dst, grid_mode, padding_mode,
- align_corners, True)
-
-
def warp_perspective(src: torch.Tensor, M: torch.Tensor, dsize: Tuple[int, int],
- flags: str = 'bilinear', border_mode: str = 'zeros',
- align_corners: bool = False) -> torch.Tensor:
+ mode: str = 'bilinear', padding_mode: str = 'zeros',
+ align_corners: Optional[bool] = None) -> torch.Tensor:
r"""Applies a perspective transformation to an image.
The function warp_perspective transforms the source image using
@@ -61,21 +50,33 @@ def warp_perspective(src: torch.Tensor, M: torch.Tensor, dsize: Tuple[int, int],
src (torch.Tensor): input image with shape :math:`(B, C, H, W)`.
M (torch.Tensor): transformation matrix with shape :math:`(B, 3, 3)`.
dsize (tuple): size of the output image (height, width).
- flags (str): interpolation mode to calculate output values
+ mode (str): interpolation mode to calculate output values
'bilinear' | 'nearest'. Default: 'bilinear'.
- border_mode (str): padding mode for outside grid values
+ padding_mode (str): padding mode for outside grid values
'zeros' | 'border' | 'reflection'. Default: 'zeros'.
- align_corners(bool): interpolation flag. Default: False.
+ align_corners(bool, optional): interpolation flag. Default: None.
Returns:
torch.Tensor: the warped input image :math:`(B, C, H, W)`.
+ Example:
+ >>> img = torch.rand(1, 4, 5, 6)
+ >>> H = torch.eye(3)[None]
+ >>> out = warp_perspective(img, H, (4, 2))
+ >>> print(out.shape)
+ torch.Size([1, 4, 4, 2])
+
.. note::
See a working example `here <https://kornia.readthedocs.io/en/latest/
tutorials/warp_perspective.html>`_.
"""
- check_is_tensor(src)
- check_is_tensor(M)
+ if not isinstance(src, torch.Tensor):
+ raise TypeError("Input src type is not a torch.Tensor. Got {}"
+ .format(type(src)))
+
+ if not isinstance(M, torch.Tensor):
+ raise TypeError("Input M type is not a torch.Tensor. Got {}"
+ .format(type(M)))
if not len(src.shape) == 4:
raise ValueError("Input src must be a BxCxHxW tensor. Got {}"
@@ -85,15 +86,40 @@ def warp_perspective(src: torch.Tensor, M: torch.Tensor, dsize: Tuple[int, int],
raise ValueError("Input M must be a Bx3x3 tensor. Got {}"
.format(M.shape))
- # launches the warper
- h, w = src.shape[-2:]
- return transform_warp_impl(src, M, (h, w), dsize, flags, border_mode, align_corners)
+ # TODO: remove the statement below in kornia v0.6
+ if align_corners is None:
+ message: str = (
+ "The align_corners default value has been changed. By default now is set True "
+ "in order to match cv2.warpPerspective. In case you want to keep your previous "
+ "behaviour set it to False. This warning will disappear in kornia > v0.6.")
+ warnings.warn(message)
+ # set default value for align corners
+ align_corners = True
+
+ B, C, H, W = src.size()
+ h_out, w_out = dsize
+
+ # we normalize the 3x3 transformation matrix and convert to 3x4
+ dst_norm_trans_src_norm: torch.Tensor = normalize_homography(
+ M, (H, W), (h_out, w_out)) # Bx3x3
+
+ src_norm_trans_dst_norm = torch.inverse(dst_norm_trans_src_norm) # Bx3x3
+
+ # this piece of code substitutes F.affine_grid since it does not support 3x3
+ grid = create_meshgrid(h_out, w_out, normalized_coordinates=True,
+ device=src.device).to(src.dtype).repeat(B, 1, 1, 1)
+ grid = transform_points(src_norm_trans_dst_norm[:, None, None], grid)
+
+ return F.grid_sample(src, grid,
+ align_corners=align_corners,
+ mode=mode,
+ padding_mode=padding_mode)
def warp_affine(src: torch.Tensor, M: torch.Tensor,
- dsize: Tuple[int, int], flags: str = 'bilinear',
+ dsize: Tuple[int, int], mode: str = 'bilinear',
padding_mode: str = 'zeros',
- align_corners: bool = False) -> torch.Tensor:
+ align_corners: Optional[bool] = None) -> torch.Tensor:
r"""Applies an affine transformation to a tensor.
The function warp_affine transforms the source tensor using
@@ -111,11 +137,18 @@ def warp_affine(src: torch.Tensor, M: torch.Tensor,
'bilinear' | 'nearest'. Default: 'bilinear'.
padding_mode (str): padding mode for outside grid values
'zeros' | 'border' | 'reflection'. Default: 'zeros'.
- align_corners (bool): mode for grid_generation. Default: False.
+ align_corners (bool, optional): mode for grid_generation. Default: None.
Returns:
torch.Tensor: the warped tensor with shape :math:`(B, C, H, W)`.
+ Example:
+ >>> img = torch.rand(1, 4, 5, 6)
+ >>> A = torch.eye(2, 3)[None]
+ >>> out = warp_affine(img, A, (4, 2))
+ >>> print(out.shape)
+ torch.Size([1, 4, 4, 2])
+
.. note::
See a working example `here <https://kornia.readthedocs.io/en/latest/
tutorials/warp_affine.html>`__.
@@ -135,20 +168,33 @@ def warp_affine(src: torch.Tensor, M: torch.Tensor,
if not (len(M.shape) == 3 or M.shape[-2:] == (2, 3)):
raise ValueError("Input M must be a Bx2x3 tensor. Got {}"
.format(M.shape))
+
+ # TODO: remove the statement below in kornia v0.6
+ if align_corners is None:
+ message: str = (
+ "The align_corners default value has been changed. By default now is set True "
+ "in order to match cv2.warpAffine. In case you want to keep your previous "
+ "behaviour set it to False. This warning will disappear in kornia > v0.6.")
+ warnings.warn(message)
+ # set default value for align corners
+ align_corners = True
+
B, C, H, W = src.size()
- dsize_src = (H, W)
- out_size = dsize
+
# we generate a 3x3 transformation matrix from 2x3 affine
M_3x3: torch.Tensor = convert_affinematrix_to_homography(M)
dst_norm_trans_src_norm: torch.Tensor = normalize_homography(
- M_3x3, dsize_src, out_size)
+ M_3x3, (H, W), dsize)
+
src_norm_trans_dst_norm = torch.inverse(dst_norm_trans_src_norm)
+
grid = F.affine_grid(src_norm_trans_dst_norm[:, :2, :],
- [B, C, out_size[0], out_size[1]],
+ [B, C, dsize[0], dsize[1]],
align_corners=align_corners)
+
return F.grid_sample(src, grid,
align_corners=align_corners,
- mode=flags,
+ mode=mode,
padding_mode=padding_mode)
diff --git a/test/augmentation/test_augmentation.py b/test/augmentation/test_augmentation.py
index 18e78cdc7..7b0bab2b0 100644
--- a/test/augmentation/test_augmentation.py
+++ b/test/augmentation/test_augmentation.py
@@ -2123,11 +2123,12 @@ class TestRandomResizedCrop:
]], device=device, dtype=dtype)
expected = torch.tensor(
- [[[[5.3750, 5.8750, 4.5938],
- [6.3437, 6.7812, 5.2500]]]], device=device, dtype=dtype)
+ [[[[4.0000, 4.5000, 5.0000],
+ [7.0000, 7.5000, 8.0000]]]], device=device, dtype=dtype)
+
rrc = RandomResizedCrop(
size=(2, 3), scale=(1., 1.), ratio=(1.0, 1.0))
- # It will crop a size of (2, 2) from the aspect ratio implementation of torch
+ # It will crop a size of (2, 3) from the aspect ratio implementation of torch
out = rrc(inp)
assert_allclose(out, expected, rtol=1e-4, atol=1e-4)
@@ -2152,11 +2153,11 @@ class TestRandomResizedCrop:
]], device=device, dtype=dtype)
expected = torch.tensor(
- [[[[1.2500, 1.7500, 1.5000],
- [4.2500, 4.7500, 3.7500],
- [7.2500, 7.7500, 6.0000]]]], device=device, dtype=dtype)
+ [[[[1.0000, 1.5000, 2.0000],
+ [4.0000, 4.5000, 5.0000],
+ [7.0000, 7.5000, 8.0000]]]], device=device, dtype=dtype)
rrc = RandomResizedCrop(size=(3, 3), scale=(3., 3.), ratio=(2., 2.))
- # It will crop a size of (2, 2) from the aspect ratio implementation of torch
+ # It will crop a size of (3, 3) from the aspect ratio implementation of torch
out = rrc(inp)
assert_allclose(out, expected, atol=1e-4, rtol=1e-4)
@@ -2170,12 +2171,12 @@ class TestRandomResizedCrop:
]], device=device, dtype=dtype).repeat(batch_size, 1, 1, 1)
expected = torch. tensor([
- [[[1.2500, 1.7500, 1.5000],
- [4.2500, 4.7500, 3.7500],
- [7.2500, 7.7500, 6.0000]]],
- [[[0.0000, 0.2500, 0.7500],
- [2.2500, 3.2500, 3.7500],
- [4.5000, 6.2500, 6.7500]]]], device=device, dtype=dtype)
+ [[[1.0000, 1.5000, 2.0000],
+ [4.0000, 4.5000, 5.0000],
+ [7.0000, 7.5000, 8.0000]]],
+ [[[0.0000, 0.5000, 1.0000],
+ [3.0000, 3.5000, 4.0000],
+ [6.0000, 6.5000, 7.0000]]]], device=device, dtype=dtype)
rrc = RandomResizedCrop(size=(3, 3), scale=(3., 3.), ratio=(2., 2.))
# It will crop a size of (2, 2) from the aspect ratio implementation of torch
out = rrc(inp)
diff --git a/test/geometry/transform/crop/test_crop2d.py b/test/geometry/transform/crop/test_crop2d.py
index 4dc70e87e..80524c3c3 100644
--- a/test/geometry/transform/crop/test_crop2d.py
+++ b/test/geometry/transform/crop/test_crop2d.py
@@ -66,7 +66,32 @@ class TestBoundingBoxInferring:
class TestCropAndResize:
- def test_crop(self, device, dtype):
+ def test_align_corners_true(self, device, dtype):
+ inp = torch.tensor([[[
+ [1., 2., 3., 4.],
+ [5., 6., 7., 8.],
+ [9., 10., 11., 12.],
+ [13., 14., 15., 16.],
+ ]]], device=device, dtype=dtype)
+
+ height, width = 2, 3
+
+ expected = torch.tensor(
+ [[[[6.0000, 6.5000, 7.0000],
+ [10.0000, 10.5000, 11.0000]]]], device=device, dtype=dtype)
+
+ boxes = torch.tensor([[
+ [1., 1.],
+ [2., 1.],
+ [2., 2.],
+ [1., 2.],
+ ]], device=device, dtype=dtype) # 1x4x2
+
+ # default should use align_coners True
+ patches = kornia.crop_and_resize(inp, boxes, (height, width))
+ assert_allclose(patches, expected, rtol=1e-4, atol=1e-4)
+
+ def test_align_corners_false(self, device, dtype):
inp = torch.tensor([[[
[1., 2., 3., 4.],
[5., 6., 7., 8.],
@@ -86,7 +111,7 @@ class TestCropAndResize:
[1., 2.],
]], device=device, dtype=dtype) # 1x4x2
- patches = kornia.crop_and_resize(inp, boxes, (height, width))
+ patches = kornia.crop_and_resize(inp, boxes, (height, width), align_corners=False)
assert_allclose(patches, expected, rtol=1e-4, atol=1e-4)
def test_crop_batch(self, device, dtype):
@@ -122,7 +147,7 @@ class TestCropAndResize:
[1., 3.],
]], device=device, dtype=dtype) # 2x4x2
- patches = kornia.crop_and_resize(inp, boxes, (2, 2), align_corners=True)
+ patches = kornia.crop_and_resize(inp, boxes, (2, 2))
assert_allclose(patches, expected, rtol=1e-4, atol=1e-4)
def test_crop_batch_broadcast(self, device, dtype):
@@ -153,7 +178,7 @@ class TestCropAndResize:
[1., 2.],
]], device=device, dtype=dtype) # 1x4x2
- patches = kornia.crop_and_resize(inp, boxes, (2, 2), align_corners=True)
+ patches = kornia.crop_and_resize(inp, boxes, (2, 2))
assert_allclose(patches, expected, rtol=1e-4, atol=1e-4)
def test_gradcheck(self, device, dtype):
@@ -318,7 +343,7 @@ class TestCropByBoxes:
[10., 11.],
]]], device=device, dtype=dtype)
- patches = kornia.geometry.transform.crop.crop_by_boxes(inp, src, dst, align_corners=True)
+ patches = kornia.geometry.transform.crop.crop_by_boxes(inp, src, dst)
assert_allclose(patches, expected)
def test_crop_by_boxes_resizing(self, device, dtype):
@@ -348,7 +373,7 @@ class TestCropByBoxes:
[10., 10.5, 11.],
]]], device=device, dtype=dtype)
- patches = kornia.geometry.transform.crop.crop_by_boxes(inp, src, dst, align_corners=True)
+ patches = kornia.geometry.transform.crop.crop_by_boxes(inp, src, dst)
assert_allclose(patches, expected, rtol=1e-4, atol=1e-4)
def test_gradcheck(self, device, dtype):
diff --git a/test/geometry/transform/test_imgwarp.py b/test/geometry/transform/test_imgwarp.py
index 9a4b2f6bc..f8b53d4d9 100644
--- a/test/geometry/transform/test_imgwarp.py
+++ b/test/geometry/transform/test_imgwarp.py
@@ -8,46 +8,6 @@ from torch.autograd import gradcheck
from torch.testing import assert_allclose
[email protected]("batch_shape", [(1, 1, 7, 32), (2, 3, 16, 31)])
-def test_warp_perspective_rotation(batch_shape, device, dtype):
- # generate input data
- batch_size, channels, height, width = batch_shape
- alpha = 0.5 * kornia.pi * torch.ones(batch_size, device=device, dtype=dtype) # 90 deg rotation
-
- # create data patch
- patch = torch.rand(batch_shape, device=device, dtype=dtype)
-
- # create transformation (rotation)
- M = torch.eye(3, device=device, dtype=dtype).repeat(batch_size, 1, 1) # Bx3x3
- M[:, 0, 0] = torch.cos(alpha)
- M[:, 0, 1] = -torch.sin(alpha)
- M[:, 1, 0] = torch.sin(alpha)
- M[:, 1, 1] = torch.cos(alpha)
-
- # apply transformation and inverse
- _, _, h, w = patch.shape
- patch_warped = kornia.warp_perspective(patch, M, dsize=(height, width), align_corners=True)
- patch_warped_inv = kornia.warp_perspective(
- patch_warped, torch.inverse(M), dsize=(height, width), align_corners=True)
-
- # generate mask to compute error
- mask = torch.ones_like(patch)
- mask_warped_inv = kornia.warp_perspective(
- kornia.warp_perspective(patch, M, dsize=(height, width), align_corners=True),
- torch.inverse(M),
- dsize=(height, width), align_corners=True)
-
- assert_allclose(mask_warped_inv * patch,
- mask_warped_inv * patch_warped_inv, rtol=1e-4, atol=1e-4)
-
-
-def test_warp_perspective_gradcheck(device, dtype):
- H, W = 5, 5
- patch = torch.rand(1, 1, 5, 5, device=device, dtype=torch.float64, requires_grad=True)
- M = kornia.eye_like(3, patch)
- assert gradcheck(kornia.warp_perspective, (patch, M, (H, W),), raise_exception=True)
-
-
@pytest.mark.parametrize("batch_size", [1, 2, 5])
def test_get_perspective_transform(batch_size, device, dtype):
# generate input data
@@ -132,7 +92,178 @@ def test_rotation_matrix2d(batch_size, device, dtype):
raise_exception=True)
+class TestWarpAffine:
+ def test_smoke(self, device, dtype):
+ batch_size, channels, height, width = 1, 2, 3, 4
+ aff_ab = torch.eye(2, 3, device=device, dtype=dtype)[None] # 1x2x3
+ img_b = torch.rand(batch_size, channels, height, width, device=device, dtype=dtype)
+ img_a = kornia.warp_affine(img_b, aff_ab, (height, width))
+ assert_allclose(img_b, img_a)
+
+ @pytest.mark.parametrize("batch_shape", (
+ [1, 3, 2, 5], [2, 4, 3, 4], [3, 5, 6, 2]
+ ))
+ @pytest.mark.parametrize("out_shape", (
+ [2, 5], [3, 4], [6, 2]
+ ))
+ def test_cardinality(self, device, dtype, batch_shape, out_shape):
+ batch_size, channels, height, width = batch_shape
+ h_out, w_out = out_shape
+ aff_ab = torch.eye(2, 3, device=device, dtype=dtype).repeat(batch_size, 1, 1) # Bx2x3
+ img_b = torch.rand(batch_size, channels, height, width, device=device, dtype=dtype)
+ img_a = kornia.warp_affine(img_b, aff_ab, (h_out, w_out))
+ assert img_a.shape == (batch_size, channels, h_out, w_out)
+
+ def test_exception(self, device, dtype):
+ img = torch.rand(1, 2, 3, 4, device=device, dtype=dtype)
+ aff = torch.eye(2, 3, device=device, dtype=dtype)[None]
+ size = (4, 5)
+
+ with pytest.raises(TypeError):
+ assert kornia.warp_affine(0., aff, size)
+
+ with pytest.raises(TypeError):
+ assert kornia.warp_affine(img, 0., size)
+
+ with pytest.raises(ValueError):
+ img = torch.rand(2, 3, 4, device=device, dtype=dtype)
+ assert kornia.warp_affine(img, aff, size)
+
+ with pytest.raises(ValueError):
+ aff = torch.eye(2, 2, device=device, dtype=dtype)[None]
+ assert kornia.warp_affine(img, aff, size)
+
+ def test_translation(self, device, dtype):
+ offset = 1.
+ h, w = 3, 4
+ aff_ab = torch.eye(2, 3, device=device, dtype=dtype)[None]
+ aff_ab[..., -1] += offset
+
+ img_b = torch.arange(float(h * w), device=device, dtype=dtype).view(1, 1, h, w)
+
+ expected = torch.zeros_like(img_b)
+ expected[..., 1:, 1:] = img_b[..., :2, :3]
+
+ # Same as opencv: cv2.warpAffine(kornia.tensor_to_image(img_b), aff_ab[0].numpy(), (w, h))
+ img_a = kornia.warp_affine(img_b, aff_ab, (h, w))
+ assert_allclose(img_a, expected)
+
+ def test_rotation_inverse(self, device, dtype):
+ h, w = 4, 4
+ img_b = torch.rand(1, 1, h, w, device=device, dtype=dtype)
+
+ # create rotation matrix of 90deg (anti-clockwise)
+ center = torch.tensor([[w - 1, h - 1]], device=device, dtype=dtype) / 2
+ scale = torch.ones((1, 2), device=device, dtype=dtype)
+ angle = 90. * torch.ones(1, device=device, dtype=dtype)
+ aff_ab = kornia.get_rotation_matrix2d(center, angle, scale)
+ # Same as opencv: cv2.getRotationMatrix2D(((w-1)/2,(h-1)/2), 90., 1.)
+
+ # warp the tensor
+ # Same as opencv: cv2.warpAffine(kornia.tensor_to_image(img_b), aff_ab[0].numpy(), (w, h))
+ img_a = kornia.warp_affine(img_b, aff_ab, (h, w))
+
+ # invert the transform
+ aff_ba = kornia.convert_affinematrix_to_homography(aff_ab).inverse()[..., :2, :]
+ img_b_hat = kornia.warp_affine(img_a, aff_ba, (h, w))
+ assert_allclose(img_b_hat, img_b)
+
+ def test_jit(self, device, dtype):
+ aff_ab = torch.eye(2, 3, device=device, dtype=dtype)[None]
+ img = torch.rand(1, 2, 3, 4, device=device, dtype=dtype)
+ args = (img, aff_ab, (4, 5))
+ op = kornia.warp_affine
+ op_jit = torch.jit.script(op)
+ assert_allclose(op(*args), op_jit(*args))
+
+ def test_gradcheck(self, device, dtype):
+ batch_size, channels, height, width = 1, 2, 3, 4
+ aff_ab = torch.eye(2, 3, device=device, dtype=dtype)[None] + 1e-6 # 1x2x3
+ img_b = torch.rand(batch_size, channels, height, width, device=device, dtype=dtype)
+ aff_ab = utils.tensor_to_gradcheck_var(aff_ab) # to var
+ img_b = utils.tensor_to_gradcheck_var(img_b) # to var
+ assert gradcheck(kornia.warp_affine, (img_b, aff_ab, (height, width),),
+ raise_exception=True)
+
+
class TestWarpPerspective:
+ def test_smoke(self, device, dtype):
+ batch_size, channels, height, width = 1, 2, 3, 4
+ img_b = torch.rand(batch_size, channels, height, width, device=device, dtype=dtype)
+ H_ab = kornia.eye_like(3, img_b)
+ img_a = kornia.warp_perspective(img_b, H_ab, (height, width))
+ assert_allclose(img_b, img_a)
+
+ @pytest.mark.parametrize("batch_shape", (
+ [1, 3, 2, 5], [2, 4, 3, 4], [3, 5, 6, 2]
+ ))
+ @pytest.mark.parametrize("out_shape", (
+ [2, 5], [3, 4], [6, 2]
+ ))
+ def test_cardinality(self, device, dtype, batch_shape, out_shape):
+ batch_size, channels, height, width = batch_shape
+ h_out, w_out = out_shape
+ img_b = torch.rand(batch_size, channels, height, width, device=device, dtype=dtype)
+ H_ab = kornia.eye_like(3, img_b)
+ img_a = kornia.warp_perspective(img_b, H_ab, (h_out, w_out))
+ assert img_a.shape == (batch_size, channels, h_out, w_out)
+
+ def test_exception(self, device, dtype):
+ img = torch.rand(1, 2, 3, 4, device=device, dtype=dtype)
+ homo = torch.eye(3, device=device, dtype=dtype)[None]
+ size = (4, 5)
+
+ with pytest.raises(TypeError):
+ assert kornia.warp_perspective(0., homo, size)
+
+ with pytest.raises(TypeError):
+ assert kornia.warp_perspective(img, 0., size)
+
+ with pytest.raises(ValueError):
+ img = torch.rand(2, 3, 4, device=device, dtype=dtype)
+ assert kornia.warp_perspective(img, homo, size)
+
+ with pytest.raises(ValueError):
+ homo = torch.eye(2, 2, device=device, dtype=dtype)[None]
+ assert kornia.warp_perspective(img, homo, size)
+
+ def test_translation(self, device, dtype):
+ offset = 1.
+ h, w = 3, 4
+
+ img_b = torch.arange(float(h * w), device=device, dtype=dtype).view(1, 1, h, w)
+ homo_ab = kornia.eye_like(3, img_b)
+ homo_ab[..., :2, -1] += offset
+
+ expected = torch.zeros_like(img_b)
+ expected[..., 1:, 1:] = img_b[..., :2, :3]
+
+ # Same as opencv: cv2.warpPerspective(kornia.tensor_to_image(img_b), homo_ab[0].numpy(), (w, h))
+ img_a = kornia.warp_perspective(img_b, homo_ab, (h, w))
+ assert_allclose(img_a, expected, atol=1e-4, rtol=1e-4)
+
+ def test_rotation_inverse(self, device, dtype):
+ h, w = 4, 4
+ img_b = torch.rand(1, 1, h, w, device=device, dtype=dtype)
+
+ # create rotation matrix of 90deg (anti-clockwise)
+ center = torch.tensor([[w - 1, h - 1]], device=device, dtype=dtype) / 2
+ scale = torch.ones((1, 2), device=device, dtype=dtype)
+ angle = 90. * torch.ones(1, device=device, dtype=dtype)
+ aff_ab = kornia.get_rotation_matrix2d(center, angle, scale)
+ # Same as opencv: cv2.getRotationMatrix2D(((w-1)/2,(h-1)/2), 90., 1.)
+
+ H_ab = kornia.convert_affinematrix_to_homography(aff_ab) # Bx3x3
+
+ # warp the tensor
+ # Same as opencv: cv2.warpPerspecive(kornia.tensor_to_image(img_b), H_ab[0].numpy(), (w, h))
+ img_a = kornia.warp_perspective(img_b, H_ab, (h, w))
+
+ # invert the transform
+ H_ba = torch.inverse(H_ab)
+ img_b_hat = kornia.warp_perspective(img_a, H_ba, (h, w))
+ assert_allclose(img_b_hat, img_b, rtol=1e-4, atol=1e-4)
+
@pytest.mark.parametrize("batch_size", [1, 5])
@pytest.mark.parametrize("channels", [1, 5])
def test_crop(self, batch_size, channels, device, dtype):
@@ -171,20 +302,12 @@ class TestWarpPerspective:
[13, 14, 15, 16],
]]], device=device, dtype=dtype).expand(batch_size, channels, -1, -1)
- expected = torch.tensor(
- [[[[0.2500, 0.9167, 1.5833],
- [2.1667, 5.1667, 6.5000],
- [4.8333, 10.5000, 11.8333]]]], device=device, dtype=dtype).repeat(batch_size, channels, 1, 1)
+ expected = patch[..., :3, :3]
# warp and assert
- patch_warped = kornia.warp_perspective(patch, dst_trans_src,
- (dst_h, dst_w))
- assert_allclose(patch_warped, expected, rtol=1e-4, atol=1e-4)
-
- # check jit
- patch_warped_jit = kornia.jit.warp_perspective(patch, dst_trans_src,
- (dst_h, dst_w))
- assert_allclose(patch_warped, patch_warped_jit, rtol=1e-4, atol=1e-4)
+ patch_warped = kornia.warp_perspective(
+ patch, dst_trans_src, (dst_h, dst_w))
+ assert_allclose(patch_warped, expected)
def test_crop_center_resize(self, device, dtype):
# generate input data
@@ -219,56 +342,34 @@ class TestWarpPerspective:
[13, 14, 15, 16],
]]], device=device, dtype=dtype)
- expected = torch.tensor(
- [[[[5.1667, 5.6111, 6.0556, 6.5000],
- [6.9444, 7.3889, 7.8333, 8.2778],
- [8.7222, 9.1667, 9.6111, 10.0556],
- [10.5000, 10.9444, 11.3889, 11.8333]]]], device=device, dtype=dtype)
+ expected = torch.tensor([[[
+ [6.0000, 6.3333, 6.6667, 7.0000],
+ [7.3333, 7.6667, 8.0000, 8.3333],
+ [8.6667, 9.0000, 9.3333, 9.6667],
+ [10.0000, 10.3333, 10.6667, 11.0000]]]], device=device, dtype=dtype)
# warp and assert
- patch_warped = kornia.warp_perspective(patch, dst_trans_src,
- (dst_h, dst_w))
- assert_allclose(patch_warped, expected, rtol=1e-4, atol=1e-4)
-
- # check jit
- patch_warped_jit = kornia.jit.warp_perspective(patch, dst_trans_src,
- (dst_h, dst_w))
- assert_allclose(patch_warped, patch_warped_jit, rtol=1e-4, atol=1e-4)
-
-
-class TestWarpAffine:
- def test_smoke(self, device, dtype):
- batch_size, channels, height, width = 1, 2, 3, 4
- aff_ab = torch.eye(2, 3, device=device, dtype=dtype)[None] # 1x2x3
- img_b = torch.rand(batch_size, channels, height, width, device=device, dtype=dtype)
- img_a = kornia.warp_affine(img_b, aff_ab, (height, width))
- assert img_b.shape == img_a.shape
+ patch_warped = kornia.warp_perspective(
+ patch, dst_trans_src, (dst_h, dst_w))
+ assert_allclose(patch_warped, expected)
- @pytest.mark.parametrize("batch_size", [1, 2, 5])
- def test_translation(self, batch_size, device, dtype):
- offset = 1.
- channels, height, width = 1, 3, 4
- aff_ab = torch.eye(2, 3, device=device, dtype=dtype).repeat(batch_size, 1, 1) # Bx2x3
- aff_ab[..., -1] += offset
- img_b = torch.arange(float(height * width), device=device, dtype=dtype).view(
- 1, channels, height, width).repeat(batch_size, 1, 1, 1)
- img_a = kornia.warp_affine(img_b, aff_ab, (height, width), align_corners=True)
- assert_allclose(img_b[..., :2, :3], img_a[..., 1:, 1:], rtol=1e-4, atol=1e-4)
+ def test_jit(self, device, dtype):
+ img = torch.rand(1, 2, 3, 4, device=device, dtype=dtype)
+ H_ab = kornia.eye_like(3, img)
+ args = (img, H_ab, (4, 5))
+ op = kornia.warp_perspective
+ op_jit = torch.jit.script(op)
+ assert_allclose(op(*args), op_jit(*args))
def test_gradcheck(self, device, dtype):
batch_size, channels, height, width = 1, 2, 3, 4
- aff_ab = torch.eye(2, 3, device=device, dtype=dtype)[None] # 1x2x3
img_b = torch.rand(batch_size, channels, height, width, device=device, dtype=dtype)
- aff_ab = utils.tensor_to_gradcheck_var(
- aff_ab, requires_grad=False) # to var
+ H_ab = kornia.eye_like(3, img_b)
img_b = utils.tensor_to_gradcheck_var(img_b) # to var
- assert gradcheck(
- kornia.warp_affine, (
- img_b,
- aff_ab,
- (height, width),
- ),
- raise_exception=True)
+ # TODO(dmytro/edgar): firgure out why gradient don't propagate for the tranaform
+ H_ab = utils.tensor_to_gradcheck_var(H_ab, requires_grad=False) # to var
+ assert gradcheck(kornia.warp_perspective, (img_b, H_ab, (height, width),),
+ raise_exception=True)
class TestRemap: