Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

Refactor and add tests in `get_perspective_transform` (#1767)

Edgar Ribaa1ef89fc9a81
diff --git a/.github/workflows/format.yml b/.github/workflows/format.yml
index 1c02339ca..0e5a063de 100644
--- a/.github/workflows/format.yml
+++ b/.github/workflows/format.yml
@@ -22,19 +22,6 @@ jobs:
- name: Run linter
run: make lint
- static-check:
- runs-on: [ubuntu-latest]
- steps:
- - uses: actions/checkout@v2
- - name: Install dependencies
- run: |
- pip install torch --find-links https://download.pytorch.org/whl/cpu/torch_stable.html
- pip install -r requirements/dev.txt
- python setup.py develop --user
-
- - name: Run mypy
- run: make mypy
-
doctest:
runs-on: [ubuntu-latest]
steps:
diff --git a/conftest.py b/conftest.py
index 7d84642eb..ec05b0fa0 100644
--- a/conftest.py
+++ b/conftest.py
@@ -33,6 +33,7 @@ def get_test_dtypes() -> Dict[str, torch.dtype]:
dict(str, torch.dtype): list with dtype names.
"""
dtypes: Dict[str, torch.dtype] = {}
+ dtypes["bfloat16"] = torch.bfloat16
dtypes["float16"] = torch.float16
dtypes["float32"] = torch.float32
dtypes["float64"] = torch.float64
@@ -45,7 +46,8 @@ TEST_DEVICES: Dict[str, torch.device] = get_test_devices()
TEST_DTYPES: Dict[str, torch.dtype] = get_test_dtypes()
# Combinations of device and dtype to be excluded from testing.
-DEVICE_DTYPE_BLACKLIST = {('cpu', 'float16')}
+# DEVICE_DTYPE_BLACKLIST = {('cpu', 'float16')}
+DEVICE_DTYPE_BLACKLIST = {}
@pytest.fixture()
diff --git a/kornia/core/__init__.py b/kornia/core/__init__.py
index 4976385c5..490c999e6 100644
--- a/kornia/core/__init__.py
+++ b/kornia/core/__init__.py
@@ -1,3 +1,3 @@
-from ._backend import Module, Tensor, concatenate
+from ._backend import Module, Tensor, concatenate, stack
-__all__ = ["concatenate", "Module", "Tensor"]
+__all__ = ["concatenate", "stack", "Module", "Tensor"]
diff --git a/kornia/core/_backend.py b/kornia/core/_backend.py
index f84421041..36d40305a 100644
--- a/kornia/core/_backend.py
+++ b/kornia/core/_backend.py
@@ -7,3 +7,4 @@ Module = torch.nn.Module
# functions
concatenate = torch.cat
+stack = torch.stack
diff --git a/kornia/enhance/adjust.py b/kornia/enhance/adjust.py
index 3a1d8df13..72d35b99e 100644
--- a/kornia/enhance/adjust.py
+++ b/kornia/enhance/adjust.py
@@ -342,7 +342,7 @@ def adjust_contrast(image: Tensor, factor: Union[float, Tensor], clip_output: bo
while len(factor.shape) != len(image.shape):
factor = factor[..., None]
- KORNIA_CHECK((factor >= 0).any(), f"Contrast factor must be positive. Got {factor}")
+ KORNIA_CHECK(any(factor >= 0), f"Contrast factor must be positive. Got {factor}")
# Apply contrast factor to each channel
img_adjust: Tensor = image * factor
@@ -396,7 +396,7 @@ def adjust_contrast_with_mean_subtraction(image: Tensor, factor: Union[float, Te
while len(factor.shape) != len(image.shape):
factor = factor[..., None]
- KORNIA_CHECK((factor >= 0).any(), f"Contrast factor must be positive. Got {factor}")
+ KORNIA_CHECK(any(factor >= 0), f"Contrast factor must be positive. Got {factor}")
if image.shape[-3] == 3:
img_mean = rgb_to_grayscale(image).mean((-2, -1), True)
diff --git a/kornia/geometry/transform/imgwarp.py b/kornia/geometry/transform/imgwarp.py
index b9cfff0a7..f2d8ce578 100644
--- a/kornia/geometry/transform/imgwarp.py
+++ b/kornia/geometry/transform/imgwarp.py
@@ -2,9 +2,9 @@ from typing import List, Optional, Tuple
import torch
import torch.nn.functional as F
-from torch import Tensor, stack
from torch.nn.functional import grid_sample
+from kornia.core import Tensor, stack
from kornia.geometry.conversions import (
angle_axis_to_rotation_matrix,
angle_to_rotation_matrix,
@@ -16,7 +16,7 @@ from kornia.geometry.conversions import (
normalize_pixel_coordinates,
)
from kornia.geometry.linalg import transform_points
-from kornia.testing import KORNIA_CHECK_IS_TENSOR
+from kornia.testing import KORNIA_CHECK, KORNIA_CHECK_SHAPE
from kornia.utils import create_meshgrid, create_meshgrid3d, eye_like
from kornia.utils.helpers import _torch_inverse_cast, _torch_solve_cast
@@ -277,35 +277,44 @@ def warp_grid3d(grid: torch.Tensor, src_homo_dst: torch.Tensor) -> torch.Tensor:
return flow.view(batch_size, depth, height, width, 3) # NxDxHxWx3
-def get_perspective_transform(src, dst):
- r"""Calculate a perspective transform from four pairs of the corresponding
- points.
+# TODO: move to kornia.geometry.projective
+# TODO: create the nn.Module -- TBD what inputs/outputs etc
+# class PerspectiveTransform(nn.Module):
+# def __init__(self) -> None:
+# super().__init__()
- The function calculates the matrix of a perspective transform so that:
+def get_perspective_transform(points_src: Tensor, points_dst: Tensor) -> Tensor:
+ r"""Calculate a perspective transform from four pairs of the corresponding points.
+
+ The algorithm is a vanilla implementation of the Direct Linear transform (DLT).
+ See more: https://www.cs.cmu.edu/~16385/s17/Slides/10.2_2D_Alignment__DLT.pdf
+
+ The function calculates the matrix of a perspective transform that maps from
+ the source to destination points:
.. math ::
\begin{bmatrix}
- t_{i}x_{i}^{'} \\
- t_{i}y_{i}^{'} \\
- t_{i} \\
+ x^{'} \\
+ y^{'} \\
+ 1 \\
\end{bmatrix}
=
- \textbf{map_matrix} \cdot
\begin{bmatrix}
- x_{i} \\
- y_{i} \\
+ h_1 & h_2 & h_3 \\
+ h_4 & h_5 & h_6 \\
+ h_7 & h_8 & h_9 \\
+ \end{bmatrix}
+ \cdot
+ \begin{bmatrix}
+ x \\
+ y \\
1 \\
\end{bmatrix}
- where
-
- .. math ::
- dst(i) = (x_{i}^{'},y_{i}^{'}), src(i) = (x_{i}, y_{i}), i = 0,1,2,3
-
Args:
- src: coordinates of quadrangle vertices in the source image with shape :math:`(B, 4, 2)`.
- dst: coordinates of the corresponding quadrangle vertices in
+ points_src: coordinates of quadrangle vertices in the source image with shape :math:`(B, 4, 2)`.
+ points_dst: coordinates of the corresponding quadrangle vertices in
the destination image with shape :math:`(B, 4, 2)`.
Returns:
@@ -313,78 +322,52 @@ def get_perspective_transform(src, dst):
.. note::
This function is often used in conjunction with :func:`warp_perspective`.
- """
- if not isinstance(src, torch.Tensor):
- raise TypeError(f"Input type is not a torch.Tensor. Got {type(src)}")
-
- if not isinstance(dst, torch.Tensor):
- raise TypeError(f"Input type is not a torch.Tensor. Got {type(dst)}")
-
- if not src.dtype == dst.dtype:
- raise TypeError(f"Source data type {src.dtype} must match Destination data type {dst.dtype}")
- if not src.shape[-2:] == (4, 2):
- raise ValueError(f"Inputs must be a Bx4x2 tensor. Got {src.shape}")
-
- if not src.shape == dst.shape:
- raise ValueError(f"Inputs must have the same shape. Got {dst.shape}")
-
- if not (src.shape[0] == dst.shape[0]):
- raise ValueError(f"Inputs must have same batch size dimension. Expect {src.shape} but got {dst.shape}")
+ Example:
+ >>> x1 = torch.tensor([[[0., 0.], [1., 0.], [1., 1.], [0., 1.]]])
+ >>> x2 = torch.tensor([[[1., 0.], [0., 0.], [0., 1.], [1., 1.]]])
+ >>> x2_trans_x1 = get_perspective_transform(x1, x2)
+ """
+ KORNIA_CHECK_SHAPE(points_src, ["B", "4", "2"])
+ KORNIA_CHECK_SHAPE(points_dst, ["B", "4", "2"])
+ KORNIA_CHECK(points_src.shape == points_dst.shape, "Source data shape must match Destination data shape.")
+ KORNIA_CHECK(points_src.dtype == points_dst.dtype, "Source data type must match Destination data type.")
# we build matrix A by using only 4 point correspondence. The linear
# system is solved with the least square method, so here
# we could even pass more correspondence
- p = []
- for i in [0, 1, 2, 3]:
- p.append(_build_perspective_param(src[:, i], dst[:, i], 'x'))
- p.append(_build_perspective_param(src[:, i], dst[:, i], 'y'))
- # A is Bx8x8
- A = torch.stack(p, dim=1)
+ # create the lhs tensor with shape # Bx8x8
+ B: int = points_src.shape[0] # batch_size
- # b is a Bx8x1
- b = torch.stack(
- [
- dst[:, 0:1, 0],
- dst[:, 0:1, 1],
- dst[:, 1:2, 0],
- dst[:, 1:2, 1],
- dst[:, 2:3, 0],
- dst[:, 2:3, 1],
- dst[:, 3:4, 0],
- dst[:, 3:4, 1],
- ],
- dim=1,
- )
+ A = torch.empty(B, 8, 8, device=points_src.device, dtype=points_src.dtype)
- # solve the system Ax = b
- X, _ = _torch_solve_cast(b, A)
+ # we need to perform in batch
+ zeros = torch.zeros(B, device=points_src.device, dtype=points_src.dtype)
+ ones = torch.ones(B, device=points_src.device, dtype=points_src.dtype)
- # create variable to return
- batch_size = src.shape[0]
- M = torch.ones(batch_size, 9, device=src.device, dtype=src.dtype)
- M[..., :8] = torch.squeeze(X, dim=-1)
+ for i in range(4):
+ x1, y1 = points_src[..., i, 0], points_src[..., i, 1] # Bx4
+ x2, y2 = points_dst[..., i, 0], points_dst[..., i, 1] # Bx4
- return M.view(-1, 3, 3) # Bx3x3
+ A[:, 2 * i] = stack([x1, y1, ones, zeros, zeros, zeros, -x1 * x2, -y1 * x2], -1)
+ A[:, 2 * i + 1] = stack([zeros, zeros, zeros, x1, y1, ones, -x1 * y2, -y1 * y2], -1)
+ # the rhs tensor
+ b = points_dst.view(-1, 8, 1)
-def _build_perspective_param(p: torch.Tensor, q: torch.Tensor, axis: str) -> torch.Tensor:
- ones = torch.ones_like(p)[..., 0:1]
- zeros = torch.zeros_like(p)[..., 0:1]
- if axis == 'x':
- return torch.cat(
- [p[:, 0:1], p[:, 1:2], ones, zeros, zeros, zeros, -p[:, 0:1] * q[:, 0:1], -p[:, 1:2] * q[:, 0:1]], dim=1
- )
+ # solve the system Ax = b
+ X: Tensor = _torch_solve_cast(A, b)
- if axis == 'y':
- return torch.cat(
- [zeros, zeros, zeros, p[:, 0:1], p[:, 1:2], ones, -p[:, 0:1] * q[:, 1:2], -p[:, 1:2] * q[:, 1:2]], dim=1
- )
+ # create variable to return the Bx3x3 transform
+ M = torch.empty(B, 9, device=points_src.device, dtype=points_src.dtype)
+ M[..., :8] = X[..., 0] # Bx8
+ M[..., -1].fill_(1)
- raise NotImplementedError(f"perspective params for axis `{axis}` is not implemented.")
+ return M.view(-1, 3, 3) # Bx3x3
+# TODO: move to kornia.geometry.affine
def get_rotation_matrix2d(center: torch.Tensor, angle: torch.Tensor, scale: torch.Tensor) -> torch.Tensor:
r"""Calculate an affine matrix of 2D rotation.
@@ -526,9 +509,9 @@ def remap(
.. note::
This function is often used in conjunction with :func:`kornia.utils.create_meshgrid`.
"""
- KORNIA_CHECK_IS_TENSOR(image, "Expected shape BxCxHxW")
- KORNIA_CHECK_IS_TENSOR(map_x, "Expected shape BxHxW")
- KORNIA_CHECK_IS_TENSOR(map_y, "Expected shape BxHxW")
+ KORNIA_CHECK_SHAPE(image, ["B", "C", "H", "W"])
+ KORNIA_CHECK_SHAPE(map_x, ["B", "H", "W"])
+ KORNIA_CHECK_SHAPE(map_y, ["B", "H", "W"])
batch_size, _, height, width = image.shape
@@ -543,8 +526,7 @@ def remap(
map_xy = map_xy.expand(batch_size, -1, -1, -1)
# warp the image tensor and return
- warped = grid_sample(image, map_xy, mode=mode, padding_mode=padding_mode, align_corners=align_corners)
- return warped
+ return grid_sample(image, map_xy, mode=mode, padding_mode=padding_mode, align_corners=align_corners)
def invert_affine_transform(matrix: torch.Tensor) -> torch.Tensor:
@@ -1085,12 +1067,14 @@ def get_perspective_transform3d(src: torch.Tensor, dst: torch.Tensor) -> torch.T
)
# solve the system Ax = b
- X, _ = _torch_solve_cast(b, A)
+ X: Tensor = _torch_solve_cast(A, b)
# create variable to return
- batch_size = src.shape[0]
- M = torch.ones(batch_size, 16, device=src.device, dtype=src.dtype)
- M[..., :15] = torch.squeeze(X, dim=-1)
+ batch_size: int = src.shape[0]
+ M = torch.empty(batch_size, 16, device=src.device, dtype=src.dtype)
+ M[..., :15] = X[..., 0]
+ M[..., -1].fill_(1)
+
return M.view(-1, 4, 4) # Bx4x4
diff --git a/kornia/geometry/transform/thin_plate_spline.py b/kornia/geometry/transform/thin_plate_spline.py
index b90537bb8..ef9af3211 100644
--- a/kornia/geometry/transform/thin_plate_spline.py
+++ b/kornia/geometry/transform/thin_plate_spline.py
@@ -83,7 +83,7 @@ def get_tps_transform(points_src: torch.Tensor, points_dst: torch.Tensor) -> Tup
l_matrix: torch.Tensor = torch.cat((k_matrix, p_matrix), -1)
l_matrix = torch.cat((l_matrix, p_matrix_t), 1)
- weights, _ = _torch_solve_cast(dest_with_zeros, l_matrix)
+ weights = _torch_solve_cast(l_matrix, dest_with_zeros)
kernel_weights: torch.Tensor = weights[:, :-3]
affine_weights: torch.Tensor = weights[:, -3:]
diff --git a/kornia/testing/__init__.py b/kornia/testing/__init__.py
index 490c6698e..97950d18a 100644
--- a/kornia/testing/__init__.py
+++ b/kornia/testing/__init__.py
@@ -205,7 +205,7 @@ def KORNIA_CHECK_SHAPE(x, shape: List[str]) -> None:
raise TypeError(f"{x} shape should be must be [{shape}]. Got {x.shape}")
-def KORNIA_CHECK(condition, msg: Optional[str] = None):
+def KORNIA_CHECK(condition: bool, msg: Optional[str] = None):
if not condition:
raise Exception(f"{condition} not true.\n{msg}")
diff --git a/kornia/utils/_compat.py b/kornia/utils/_compat.py
index 4c2b85896..4a7f84e12 100644
--- a/kornia/utils/_compat.py
+++ b/kornia/utils/_compat.py
@@ -11,11 +11,22 @@ def torch_version() -> str:
return torch.__version__.split('+')[0]
+# TODO: replace by torch_version_ge``
def torch_version_geq(major, minor) -> bool:
_version = version.parse(torch_version())
return _version >= version.parse(f"{major}.{minor}")
+def torch_version_lt(major: int, minor: int, patch: int) -> bool:
+ _version = version.parse(torch_version())
+ return _version < version.parse(f"{major}.{minor}.{patch}")
+
+
+def torch_version_ge(major: int, minor: int, patch: int) -> bool:
+ _version = version.parse(torch_version())
+ return _version >= version.parse(f"{major}.{minor}.{patch}")
+
+
if version.parse(torch_version()) > version.parse("1.7.1"):
# TODO: remove the type: ignore once Python 3.6 is deprecated.
# It turns out that Pytorch has no attribute `torch.linalg` for
@@ -25,8 +36,7 @@ else:
from torch import qr as linalg_qr # type: ignore # noqa: F401
-# TODO: remove after deprecating < 1.9.1
-if version.parse(torch_version()) > version.parse("1.9.1"):
+if torch_version_ge(1, 10, 0):
if not TYPE_CHECKING:
diff --git a/kornia/utils/helpers.py b/kornia/utils/helpers.py
index 51d505365..87985f60d 100644
--- a/kornia/utils/helpers.py
+++ b/kornia/utils/helpers.py
@@ -5,6 +5,7 @@ from typing import Any, Callable, List, Optional, Tuple
import torch
+from kornia.core import Tensor
from kornia.utils._compat import torch_version_geq
@@ -128,30 +129,28 @@ def _torch_svd_cast(input: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor, to
# TODO: return only `torch.Tensor` and review all the calls to adjust
-def _torch_solve_cast(input: torch.Tensor, A: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
+def _torch_solve_cast(A: Tensor, B: Tensor) -> Tensor:
"""Helper function to make torch.solve work with other than fp32/64.
The function torch.solve is only implemented for fp32/64 which makes impossible to be used by fp16 or others. What
this function does, is cast input data type to fp32, apply torch.svd, and cast back to the input dtype.
"""
- if not isinstance(input, torch.Tensor):
- raise AssertionError(f"Input must be torch.Tensor. Got: {type(input)}.")
- dtype: torch.dtype = input.dtype
+ dtype: torch.dtype = A.dtype
if dtype not in (torch.float32, torch.float64):
dtype = torch.float32
- out = torch.linalg.solve(A.to(dtype), input.to(dtype))
+ out = torch.linalg.solve(A.to(dtype), B.to(dtype))
- return (out.to(input.dtype), out)
+ return out.to(A.dtype)
def safe_solve_with_mask(B: torch.Tensor, A: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
r"""Helper function, which avoids crashing because of singular matrix input and outputs the
mask of valid solution"""
if not torch_version_geq(1, 10):
- sol, lu = _torch_solve_cast(B, A)
+ sol = _torch_solve_cast(A, B)
warnings.warn('PyTorch version < 1.10, solve validness mask maybe not correct', RuntimeWarning)
- return sol, lu, torch.ones(len(A), dtype=torch.bool, device=A.device)
+ return sol, sol, torch.ones(len(A), dtype=torch.bool, device=A.device)
# Based on https://github.com/pytorch/pytorch/issues/31546#issuecomment-694135622
if not isinstance(B, torch.Tensor):
raise AssertionError(f"B must be torch.Tensor. Got: {type(B)}.")
diff --git a/test/augmentation/test_augmentation.py b/test/augmentation/test_augmentation.py
index 28bd7771a..6a17292fb 100644
--- a/test/augmentation/test_augmentation.py
+++ b/test/augmentation/test_augmentation.py
@@ -2333,7 +2333,7 @@ class TestRandomResizedCrop:
2, 1, 1, 1
)
res = f(input)
- assert (res[0] == res[1]).all()
+ assert_close(res[0], res[1])
torch.manual_seed(0)
aug = RandomResizedCrop(
@@ -2341,7 +2341,7 @@ class TestRandomResizedCrop:
)
out = aug(input)
inversed = aug.inverse(out)
- assert (inversed[0] == inversed[1]).all()
+ assert_close(inversed[0], inversed[1])
def test_crop_scale_ratio(self, device, dtype):
# This is included in doctest
diff --git a/test/benchmark.py b/test/benchmark.py
new file mode 100644
index 000000000..97c1f8db8
--- /dev/null
+++ b/test/benchmark.py
@@ -0,0 +1,28 @@
+from itertools import product
+
+import torch
+import torch.utils.benchmark as benchmark
+
+# Compare takes a list of measurements which we'll save in results.
+results = []
+
+sizes = [1, 64, 1024]
+for b, n in product(sizes, sizes):
+ # label and sub_label are the rows
+ # description is the column
+ label = 'get_perspective_transform'
+ sub_label = f'[{b}, {4}, {2}]'
+ x = torch.rand((b, 4, 2))
+ for num_threads in [1, 4, 16, 32]:
+ results.append(benchmark.Timer(
+ stmt='get_perspective_transform(x, x)',
+ setup='from kornia.geometry import get_perspective_transform',
+ globals={'x': x},
+ num_threads=num_threads,
+ label=label,
+ sub_label=sub_label,
+ description='get_perspective_transform',
+ ).blocked_autorange(min_run_time=1))
+
+compare = benchmark.Compare(results)
+compare.print()
diff --git a/test/feature/test_affine_shape_estimator.py b/test/feature/test_affine_shape_estimator.py
index 8a3df45b3..e74abf422 100644
--- a/test/feature/test_affine_shape_estimator.py
+++ b/test/feature/test_affine_shape_estimator.py
@@ -146,13 +146,13 @@ class TestLAFAffNetShapeEstimator:
sift = LAFAffNetShapeEstimator()
sift.__repr__()
- def test_toy(self, device):
- aff = LAFAffNetShapeEstimator(True).to(device).eval()
- inp = torch.zeros(1, 1, 32, 32, device=device)
+ def test_toy(self, device, dtype):
+ aff = LAFAffNetShapeEstimator(True).to(device, dtype).eval()
+ inp = torch.zeros(1, 1, 32, 32, device=device, dtype=dtype)
inp[:, :, 15:-15, 9:-9] = 1
- laf = torch.tensor([[[[20.0, 0.0, 16.0], [0.0, 20.0, 16.0]]]], device=device)
+ laf = torch.tensor([[[[20.0, 0.0, 16.0], [0.0, 20.0, 16.0]]]], device=device, dtype=dtype)
new_laf = aff(laf, inp)
- expected = torch.tensor([[[[40.8758, 0.0, 16.0], [-0.3824, 9.7857, 16.0]]]], device=device)
+ expected = torch.tensor([[[[40.8758, 0.0, 16.0], [-0.3824, 9.7857, 16.0]]]], device=device, dtype=dtype)
assert_close(new_laf, expected, atol=1e-4, rtol=1e-4)
@pytest.mark.skip("jacobian not well computed")
diff --git a/test/geometry/transform/test_imgwarp.py b/test/geometry/transform/test_imgwarp.py
index 33a122b73..208be9606 100644
--- a/test/geometry/transform/test_imgwarp.py
+++ b/test/geometry/transform/test_imgwarp.py
@@ -5,33 +5,96 @@ from torch.autograd import gradcheck
import kornia
import kornia.testing as utils # test utils
from kornia.testing import assert_close
+from kornia.utils._compat import torch_version_lt
from kornia.utils.helpers import _torch_inverse_cast
[email protected]("batch_size", [1, 2, 5])
-def test_get_perspective_transform(batch_size, device, dtype):
- # generate input data
- h_max, w_max = 64, 32 # height, width
- h = torch.ceil(h_max * torch.rand(batch_size, device=device, dtype=dtype))
- w = torch.ceil(w_max * torch.rand(batch_size, device=device, dtype=dtype))
+class TestGetPerspectiveTransform:
+ @pytest.mark.parametrize("batch_size", [1, 2, 5])
+ def test_smoke(self, device, dtype, batch_size):
+ points_src = torch.rand(batch_size, 4, 2, device=device, dtype=dtype)
+ points_dst = torch.rand(batch_size, 4, 2, device=device, dtype=dtype)
+
+ dst_trans_src = kornia.geometry.get_perspective_transform(
+ points_src, points_dst)
+
+ assert dst_trans_src.shape == (batch_size, 3, 3)
- norm = torch.rand(batch_size, 4, 2, device=device, dtype=dtype)
- points_src = torch.zeros_like(norm, device=device, dtype=dtype)
- points_src[:, 1, 0] = h
- points_src[:, 2, 1] = w
- points_src[:, 3, 0] = h
- points_src[:, 3, 1] = w
- points_dst = points_src + norm
+ @pytest.mark.parametrize("batch_size", [1, 5])
+ def test_crop_src_dst_type_mismatch(self, device, dtype, batch_size):
+ # generate input data
+ src_h, src_w = 3, 3
+ dst_h, dst_w = 3, 3
+
+ # [x, y] origin
+ # top-left, top-right, bottom-right, bottom-left
+ points_src = torch.tensor(
+ [[[0, 0], [0, src_w - 1], [src_h - 1, src_w - 1], [src_h - 1, 0]]], device=device, dtype=torch.int64
+ )
- # compute transform from source to target
- dst_homo_src = kornia.geometry.get_perspective_transform(points_src, points_dst)
+ # [x, y] destination
+ # top-left, top-right, bottom-right, bottom-left
+ points_dst = torch.tensor(
+ [[[0, 0], [0, dst_w - 1], [dst_h - 1, dst_w - 1], [dst_h - 1, 0]]], device=device, dtype=dtype
+ )
+
+ # compute transformation between points
+ with pytest.raises(Exception):
+ _ = kornia.geometry.get_perspective_transform(points_src, points_dst)
+
+ def test_back_and_forth(self, device, dtype):
+ # generate input data
+ h_max, w_max = 64, 32 # height, width
+ h = h_max * torch.rand(1, device=device, dtype=dtype)
+ w = w_max * torch.rand(1, device=device, dtype=dtype)
+
+ norm = torch.rand(1, 4, 2, device=device, dtype=dtype)
+ points_src = torch.zeros_like(norm, device=device, dtype=dtype)
+ points_src[:, 1, 0] = h
+ points_src[:, 2, 1] = w
+ points_src[:, 3, 0] = h
+ points_src[:, 3, 1] = w
+ points_dst = points_src + norm
+
+ # compute transform from source to target
+ dst_trans_src = kornia.geometry.get_perspective_transform(points_src, points_dst)
+ points_dst_hat = kornia.geometry.transform_points(dst_trans_src, points_src)
+ assert_close(points_dst, points_dst_hat)
+
+ def test_hflip(self, device, dtype):
+ points_src = torch.tensor(
+ [[[0., 0.], [1., 0.], [1., 1.], [0., 1.]]], device=device, dtype=dtype)
+
+ points_dst = torch.tensor(
+ [[[1., 0.], [0., 0.], [0., 1.], [1., 1.]]], device=device, dtype=dtype)
- assert_close(kornia.geometry.transform_points(dst_homo_src, points_src), points_dst, rtol=1e-4, atol=1e-4)
+ dst_trans_src = kornia.geometry.get_perspective_transform(
+ points_src, points_dst)
- # compute gradient check
- points_src = utils.tensor_to_gradcheck_var(points_src) # to var
- points_dst = utils.tensor_to_gradcheck_var(points_dst) # to var
- assert gradcheck(kornia.geometry.get_perspective_transform, (points_src, points_dst), raise_exception=True)
+ point_left = torch.tensor([[[0., 0.]]], device=device, dtype=dtype)
+ point_right = torch.tensor([[[1., 0.]]], device=device, dtype=dtype)
+
+ assert_close(
+ kornia.geometry.transform_points(dst_trans_src, point_left),
+ point_right)
+
+ def test_jit(self, device, dtype):
+ points_src = torch.rand(1, 4, 2, device=device, dtype=dtype)
+ points_dst = torch.rand(1, 4, 2, device=device, dtype=dtype)
+
+ op = kornia.geometry.get_perspective_transform
+ op_jit = torch.jit.script(op)
+
+ assert_close(op(points_src, points_dst), op_jit(points_src, points_dst))
+
+ @pytest.mark.skipif(
+ torch_version_lt(1, 11, 0),
+ reason="backward for LSTSQ not supported in pytorch < 1.11.0")
+ def test_gradcheck(self, device):
+ # compute gradient check
+ points_src = torch.rand(1, 4, 2, device=device, dtype=torch.float64, requires_grad=True)
+ points_dst = torch.rand(1, 4, 2, device=device, dtype=torch.float64, requires_grad=True)
+ assert gradcheck(kornia.geometry.get_perspective_transform, (points_src, points_dst), raise_exception=True)
@pytest.mark.parametrize("batch_size", [1, 2, 5])
@@ -313,28 +376,6 @@ class TestWarpPerspective:
patch_warped = kornia.geometry.warp_perspective(patch, dst_trans_src, (dst_h, dst_w))
assert_close(patch_warped, expected)
- @pytest.mark.parametrize("batch_size", [1, 5])
- def test_crop_src_dst_type_mismatch(self, device, dtype, batch_size):
- # generate input data
- src_h, src_w = 3, 3
- dst_h, dst_w = 3, 3
-
- # [x, y] origin
- # top-left, top-right, bottom-right, bottom-left
- points_src = torch.tensor(
- [[[0, 0], [0, src_w - 1], [src_h - 1, src_w - 1], [src_h - 1, 0]]], device=device, dtype=torch.int64
- )
-
- # [x, y] destination
- # top-left, top-right, bottom-right, bottom-left
- points_dst = torch.tensor(
- [[[0, 0], [0, dst_w - 1], [dst_h - 1, dst_w - 1], [dst_h - 1, 0]]], device=device, dtype=dtype
- )
-
- # compute transformation between points
- with pytest.raises(TypeError):
- kornia.geometry.get_perspective_transform(points_src, points_dst).expand(batch_size, -1, -1)
-
def test_crop_center_resize(self, device, dtype):
# generate input data
dst_h, dst_w = 4, 4
diff --git a/test/utils/test_helpers.py b/test/utils/test_helpers.py
index ecc3c76ab..69ac74fc8 100644
--- a/test/utils/test_helpers.py
+++ b/test/utils/test_helpers.py
@@ -107,7 +107,7 @@ class TestSolveCast:
A = torch.randn(2, 3, 1, 4, 4, device=device, dtype=dtype)
B = torch.randn(2, 3, 1, 4, 6, device=device, dtype=dtype)
- X, _ = _torch_solve_cast(B, A)
+ X = _torch_solve_cast(A, B)
error = torch.dist(B, A.matmul(X))
tol_val: float = 1e-1 if dtype == torch.float16 else 1e-4
@@ -120,7 +120,7 @@ class TestSolveWithMask:
B = torch.randn(2, 3, 1, 4, 6, device=device, dtype=dtype)
X, _, mask = safe_solve_with_mask(B, A)
- X2, _ = _torch_solve_cast(B, A)
+ X2 = _torch_solve_cast(A, B)
tol_val: float = 1e-1 if dtype == torch.float16 else 1e-4
if mask.sum() > 0:
assert_close(X[mask], X2[mask], atol=tol_val, rtol=tol_val)