Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

Feat/warp projective (#587)

Edgar Riba6766725c2a3a
diff --git a/docs/source/geometry.transform.rst b/docs/source/geometry.transform.rst
index adc9d7288..ff0d695f1 100644
--- a/docs/source/geometry.transform.rst
+++ b/docs/source/geometry.transform.rst
@@ -7,10 +7,16 @@ The functions in this section perform various geometrical transformations of 2D
.. autofunction:: warp_perspective
.. autofunction:: warp_affine
+.. autofunction:: warp_projective
.. autofunction:: get_perspective_transform
+.. autofunction:: get_projective_transform
.. autofunction:: get_rotation_matrix2d
.. autofunction:: remap
.. autofunction:: invert_affine_transform
+.. autofunction:: matrix_to_homogeneous
+.. autofunction:: projection_from_Rt
+.. autofunction:: normal_transform_pixel
+.. autofunction:: normal_transform3d_pixel
.. autofunction:: center_crop
.. autofunction:: crop_and_resize
.. autofunction:: pyrdown
diff --git a/kornia/filters/filter.py b/kornia/filters/filter.py
index 55f8668e4..3dde7ff3a 100644
--- a/kornia/filters/filter.py
+++ b/kornia/filters/filter.py
@@ -80,15 +80,10 @@ def filter2D(input: torch.Tensor, kernel: torch.Tensor,
raise ValueError("Invalid input shape, we expect BxCxHxW. Got: {}"
.format(input.shape))
- if not len(kernel.shape) == 3:
+ if not len(kernel.shape) == 3 and kernel.shape[0] != 1:
raise ValueError("Invalid kernel shape, we expect 1xHxW. Got: {}"
.format(kernel.shape))
- borders_list: List[str] = ['constant', 'reflect', 'replicate', 'circular']
- if border_type not in borders_list:
- raise ValueError("Invalid border_type, we expect the following: {0}."
- "Got: {1}".format(borders_list, border_type))
-
# prepare kernel
b, c, h, w = input.shape
tmp_kernel: torch.Tensor = kernel[None].type_as(input)
@@ -182,15 +177,10 @@ def filter3D(input: torch.Tensor, kernel: torch.Tensor,
raise ValueError("Invalid input shape, we expect BxCxDxHxW. Got: {}"
.format(input.shape))
- if not len(kernel.shape) == 4:
- raise ValueError("Invalid kernel shape, we expect BxDxHxW. Got: {}"
+ if not len(kernel.shape) == 4 and kernel.shape[0] != 1:
+ raise ValueError("Invalid kernel shape, we expect 1xDxHxW. Got: {}"
.format(kernel.shape))
- borders_list: List[str] = ['constant', 'replicate', 'circular']
- if border_type not in borders_list:
- raise ValueError("Invalid border_type, we expect the following: {0}."
- "Got: {1}".format(borders_list, border_type))
-
# prepare kernel
b, c, d, h, w = input.shape
tmp_kernel: torch.Tensor = kernel[None].type_as(input)
diff --git a/kornia/geometry/transform/__init__.py b/kornia/geometry/transform/__init__.py
index 61b3e8b85..9b888a33a 100644
--- a/kornia/geometry/transform/__init__.py
+++ b/kornia/geometry/transform/__init__.py
@@ -3,3 +3,4 @@ from kornia.geometry.transform.imgwarp import *
from kornia.geometry.transform.pyramid import *
from kornia.geometry.transform.affwarp import *
from kornia.geometry.transform.flips import *
+from kornia.geometry.transform.projwarp import *
diff --git a/kornia/geometry/transform/projwarp.py b/kornia/geometry/transform/projwarp.py
new file mode 100644
index 000000000..ffeb8f41e
--- /dev/null
+++ b/kornia/geometry/transform/projwarp.py
@@ -0,0 +1,186 @@
+"""Module to perform projective transformations to tensors."""
+from typing import Tuple, List
+
+import torch
+import kornia as K
+
+__all__ = [
+ "warp_projective",
+ "get_projective_transform",
+ "normal_transform3d_pixel",
+ "matrix_to_homogeneous",
+ "projection_from_Rt",
+]
+
+
+def warp_projective(src: torch.Tensor,
+ M: torch.Tensor,
+ dsize: Tuple[int, int, int],
+ flags: str = 'bilinear',
+ padding_mode: str = 'zeros',
+ align_corners: bool = True) -> torch.Tensor:
+ r"""Applies a projective transformation a to 3d tensor.
+
+ src (torch.Tensor): input tensor of shape :math:`(B, C, D, H, W)`.
+ M (torch.Tensor): projective transformation matrix of shape :math:`(B, 3, 4)`.
+ dsize (Tuple[int, int, int]): size of the output image (depth, height, width).
+ 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): mode for grid_generation. Default: True. See
+ https://pytorch.org/docs/stable/nn.functional.html#torch.nn.functional.interpolate for details
+
+ Returns:
+ torch.Tensor: the warped 3d tensor with shape :math:`(B, C, D, H, W)`.
+
+ """
+ assert len(src.shape) == 5, src.shape
+ assert len(M.shape) == 3 and M.shape[-2:] == (3, 4), M.shape
+ assert len(dsize) == 3, dsize
+ B, C, D, H, W = src.size()
+
+ size_src: Tuple[int, int, int] = (D, H, W)
+ size_out: Tuple[int, int, int] = dsize
+
+ M_4x4 = matrix_to_homogeneous(M) # Bx4x4
+
+ # we need to normalize the transformation since grid sample needs -1/1 coordinates
+ dst_norm_trans_src_norm: torch.Tensor = _normalize_projection_matrix(
+ M_4x4, size_src, size_out) # Bx4x4
+
+ src_norm_trans_dst_norm = torch.inverse(dst_norm_trans_src_norm)
+ P_norm: torch.Tensor = src_norm_trans_dst_norm[:, :3] # Bx3x4
+
+ # compute meshgrid and apply to input
+ dsize_out: List[int] = [B, C] + list(size_out)
+ grid = torch.nn.functional.affine_grid(P_norm, dsize_out, align_corners=align_corners)
+ return torch.nn.functional.grid_sample(
+ src, grid, align_corners=align_corners, mode=flags, padding_mode=padding_mode)
+
+
+def projection_from_Rt(rmat: torch.Tensor, tvec: torch.Tensor) -> torch.Tensor:
+ r"""Compute the projection matrix from Rotation and translation.
+
+ Concatenates the batch of rotations and translations such that :math:`P = [R | t]`.
+
+ Args:
+ rmat (torch.Tensor): the rotation matrix with shape :math:`(*, 3, 3)`.
+ tvec (torch.Tensor): the translation vector with shape :math:`(*, 3, 1)`.
+
+ Returns:
+ torch.Tensor: the projection matrix with shape :math:`(*, 3, 4)`.
+
+ """
+ assert len(rmat.shape) >= 2 and rmat.shape[-2:] == (3, 3), rmat.shape
+ assert len(tvec.shape) >= 2 and tvec.shape[-2:] == (3, 1), tvec.shape
+
+ return torch.cat([rmat, tvec], dim=-1) # Bx3x4
+
+
+def matrix_to_homogeneous(M: torch.Tensor) -> torch.Tensor:
+ r"""Converts a generic transformation matrix to make it usable for homogeneous coordinates.
+
+ Appends to the last matrix row an extra row filled with zeros with a one to the end.
+
+ Args:
+ M (torch.Tensor): the transformation matrix with at least two dimensions :math:`(*, M, N)`.
+
+ Returns:
+ torch.Tensor: the transformation matrix with shape :math:`(*, M, N + 1)`.
+
+ """
+ M_homo = torch.nn.functional.pad(M, [0, 0, 0, 1], "constant", value=0.)
+ M_homo[..., -1, -1] += 1.0
+
+ return M_homo
+
+
+def _normalize_projection_matrix(
+ dst_pix_trans_src_pix: torch.Tensor,
+ dsize_src: Tuple[int, int, int],
+ dsize_dst: Tuple[int, int, int]) -> torch.Tensor:
+ r"""Computes the transformation matrix to normalize points before applying sampling."""
+ # source and destination sizes
+ src_d, src_h, src_w = dsize_src
+ src_d, dst_h, dst_w = dsize_dst
+
+ # compute the transformation pixel/norm for src/dst
+ src_norm_trans_src_pix: torch.Tensor = normal_transform3d_pixel(
+ src_d, src_h, src_w).to(dst_pix_trans_src_pix)
+
+ src_pix_trans_src_norm = torch.inverse(src_norm_trans_src_pix)
+
+ dst_norm_trans_dst_pix: torch.Tensor = normal_transform3d_pixel(
+ src_d, dst_h, dst_w).to(dst_pix_trans_src_pix)
+
+ # compute chain transformations
+ dst_norm_trans_src_norm: torch.Tensor = (
+ dst_norm_trans_dst_pix @ (dst_pix_trans_src_pix @ src_pix_trans_src_norm)
+ )
+ return dst_norm_trans_src_norm
+
+
+def normal_transform3d_pixel(depth: int, height: int, width: int) -> torch.Tensor:
+ r"""Compute the normalization matrix from image size in pixels to [-1, 1].
+
+ Args:
+ depth (int): tensor depht.
+ height (int): tensor height.
+ width (int): tensor width.
+
+ Returns:
+ torch.Tensor: normalized transform with shape :math:`(1, 4, 4)`.
+
+ """
+ tr_mat = torch.tensor([[1.0, 0.0, 0.0, -1.0],
+ [0.0, 1.0, 0.0, -1.0],
+ [0.0, 0.0, 1.0, -1.0],
+ [0.0, 0.0, 0.0, 1.0]]) # 4x4
+
+ tr_mat[0, 0] = tr_mat[0, 0] * 2.0 / (width - 1.0)
+ tr_mat[1, 1] = tr_mat[1, 1] * 2.0 / (height - 1.0)
+ tr_mat[2, 2] = tr_mat[2, 2] * 2.0 / (depth - 1.0)
+
+ return tr_mat[None] # 1x4x4
+
+
+def get_projective_transform(center: torch.Tensor, angles: torch.Tensor) -> torch.Tensor:
+ r"""Calculates the projection matrix for a 3D rotation.
+
+ The function computes the projection matrix given the center, scales and angles per axis.
+
+ Args:
+ center (torch.Tensor): center of the rotation in the source with shape :math:`(B, 3)`.
+ angles (Tensor): angle axis vector containing the rotation angles in degrees in the form
+ of (rx, ry, rz) with shape :math:`(B, 3)`. Internally it calls Rodrigues to compute
+ the rotation matrix from axis-angle.
+
+ Returns:
+ Tensor: the projection matrix of 3D rotation with shape :math:`(B, 3, 4)`.
+
+ """
+ assert len(center.shape) == 2 and center.shape[-1] == 3, center.shape
+ assert len(angles.shape) == 2 and angles.shape[-1] == 3, angles.shape
+ assert center.device == angles.device, (center.device, angles.device)
+ assert center.dtype == angles.dtype, (center.dtype, angles.dtype)
+
+ # create rotation matrix
+ angle_axis_rad: torch.Tensor = K.deg2rad(angles)
+ rmat: torch.Tensor = K.angle_axis_to_rotation_matrix(angle_axis_rad) # Bx3x3
+
+ # define matrix to move forth and back to origin
+ from_origin_mat = torch.eye(4)[None].repeat(rmat.shape[0], 1, 1).type_as(center) # Bx4x4
+ from_origin_mat[..., :3, -1] += center
+
+ to_origin_mat = from_origin_mat.clone()
+ to_origin_mat = from_origin_mat.inverse()
+
+ # append tranlation with zeros
+ proj_mat = projection_from_Rt(rmat, torch.zeros_like(center)[..., None]) # Bx3x4
+
+ # chain 4x4 transforms
+ proj_mat = matrix_to_homogeneous(proj_mat) # Bx4x4
+ proj_mat = (from_origin_mat @ proj_mat @ to_origin_mat)
+
+ return proj_mat[..., :3, :] # Bx3x4
diff --git a/test/geometry/test_projwarp.py b/test/geometry/test_projwarp.py
new file mode 100644
index 000000000..3bdbc7fe3
--- /dev/null
+++ b/test/geometry/test_projwarp.py
@@ -0,0 +1,292 @@
+import pytest
+
+import torch
+from torch.autograd import gradcheck
+from torch.testing import assert_allclose
+
+import kornia.geometry.transform.projwarp as proj
+
+
+def dtype():
+ return torch.float32
+
+
+class TestWarpProjective:
+ def test_smoke(self, device, dtype):
+ input = torch.rand(1, 3, 3, 4, 5, device=device, dtype=dtype)
+ P = torch.rand(1, 3, 4, device=device, dtype=dtype)
+ output = proj.warp_projective(input, P, (3, 4, 5))
+ assert output.shape == (1, 3, 3, 4, 5)
+
+ @pytest.mark.parametrize("batch_size", [1, 3])
+ @pytest.mark.parametrize("num_channels", [1, 3, 5])
+ @pytest.mark.parametrize("out_shape", [(3, 3, 3), (4, 5, 6)])
+ def test_batch(self, batch_size, num_channels, out_shape, device, dtype):
+ B, C = batch_size, num_channels
+ input = torch.rand(B, C, 3, 4, 5, device=device, dtype=dtype)
+ P = torch.rand(B, 3, 4, device=device, dtype=dtype)
+ output = proj.warp_projective(input, P, out_shape)
+ assert list(output.shape) == [B, C] + list(out_shape)
+
+ def test_gradcheck(self, device):
+ # generate input data
+ input = torch.rand(1, 3, 3, 4, 5, device=device, dtype=torch.float64, requires_grad=True)
+ P = torch.rand(1, 3, 4, device=device, dtype=torch.float64)
+ assert gradcheck(proj.warp_projective, (input, P, (3, 3, 3)), raise_exception=True)
+
+ def test_forth_back(self, device, dtype):
+ out_shape = (3, 4, 5)
+ input = torch.rand(2, 5, 3, 4, 5, device=device, dtype=dtype)
+ P = torch.rand(2, 3, 4, device=device, dtype=dtype)
+ P = proj.matrix_to_homogeneous(P)
+ P_hat = (P.inverse() @ P)[:, :3]
+ output = proj.warp_projective(input, P_hat, out_shape)
+ assert_allclose(output, input)
+
+ def test_rotate_x(self, device, dtype):
+ input = torch.tensor([[[[
+ [0., 0., 0.],
+ [0., 2., 0.],
+ [0., 0., 0.],
+ ], [
+ [0., 0., 0.],
+ [0., 1., 0.],
+ [0., 0., 0.],
+ ], [
+ [0., 0., 0.],
+ [0., 0., 0.],
+ [0., 0., 0.],
+ ]]]], device=device, dtype=dtype)
+
+ expected = torch.tensor([[[[
+ [0., 0., 0.],
+ [0., 0., 0.],
+ [0., 0., 0.],
+ ], [
+ [0., 0., 0.],
+ [0., 1., 0.],
+ [0., 2., 0.],
+ ], [
+ [0., 0., 0.],
+ [0., 0., 0.],
+ [0., 0., 0.],
+ ]]]], device=device, dtype=dtype)
+
+ _, _, D, H, W = input.shape
+ center = torch.tensor([
+ [(W - 1) / 2, (H - 1) / 2, (D - 1) / 2]], device=device, dtype=dtype)
+
+ angles = torch.tensor([[90., 0., 0.]], device=device, dtype=dtype)
+
+ P = proj.get_projective_transform(center, angles)
+ output = proj.warp_projective(input, P, (3, 3, 3))
+ assert_allclose(output, expected)
+
+ def test_rotate_y(self, device, dtype):
+ input = torch.tensor([[[[
+ [0., 0., 0.],
+ [0., 2., 0.],
+ [0., 0., 0.],
+ ], [
+ [0., 0., 0.],
+ [0., 1., 0.],
+ [0., 0., 0.],
+ ], [
+ [0., 0., 0.],
+ [0., 0., 0.],
+ [0., 0., 0.],
+ ]]]], device=device, dtype=dtype)
+
+ expected = torch.tensor([[[[
+ [0., 0., 0.],
+ [0., 0., 0.],
+ [0., 0., 0.],
+ ], [
+ [0., 0., 0.],
+ [2., 1., 0.],
+ [0., 0., 0.],
+ ], [
+ [0., 0., 0.],
+ [0., 0., 0.],
+ [0., 0., 0.],
+ ]]]], device=device, dtype=dtype)
+
+ _, _, D, H, W = input.shape
+ center = torch.tensor([
+ [(W - 1) / 2, (H - 1) / 2, (D - 1) / 2]], device=device, dtype=dtype)
+
+ angles = torch.tensor([[0., 90., 0.]], device=device, dtype=dtype)
+
+ P = proj.get_projective_transform(center, angles)
+ output = proj.warp_projective(input, P, (3, 3, 3))
+ assert_allclose(output, expected)
+
+ def test_rotate_z(self, device, dtype):
+ input = torch.tensor([[[[
+ [0., 0., 0.],
+ [0., 0., 0.],
+ [0., 0., 0.],
+ ], [
+ [0., 2., 0.],
+ [0., 1., 0.],
+ [0., 0., 0.],
+ ], [
+ [0., 0., 0.],
+ [0., 0., 0.],
+ [0., 0., 0.],
+ ]]]], device=device, dtype=dtype)
+
+ expected = torch.tensor([[[[
+ [0., 0., 0.],
+ [0., 0., 0.],
+ [0., 0., 0.],
+ ], [
+ [0., 0., 0.],
+ [0., 1., 2.],
+ [0., 0., 0.],
+ ], [
+ [0., 0., 0.],
+ [0., 0., 0.],
+ [0., 0., 0.],
+ ]]]], device=device, dtype=dtype)
+
+ _, _, D, H, W = input.shape
+ center = torch.tensor([
+ [(W - 1) / 2, (H - 1) / 2, (D - 1) / 2]], device=device, dtype=dtype)
+
+ angles = torch.tensor([[0., 0., 90.]], device=device, dtype=dtype)
+
+ P = proj.get_projective_transform(center, angles)
+ output = proj.warp_projective(input, P, (3, 3, 3))
+ assert_allclose(output, expected)
+
+ def test_rotate_y_large(self, device, dtype):
+ """Rotates 90deg anti-clockwise."""
+ input = torch.tensor([[[[
+ [0., 4., 0.],
+ [0., 3., 0.],
+ [0., 0., 0.],
+ ], [
+ [0., 2., 0.],
+ [0., 1., 0.],
+ [0., 0., 0.],
+ ], [
+ [0., 0., 0.],
+ [0., 0., 0.],
+ [0., 0., 0.],
+ ]], [[
+ [0., 0., 0.],
+ [0., 0., 0.],
+ [0., 9., 0.],
+ ], [
+ [0., 0., 0.],
+ [0., 6., 7.],
+ [0., 0., 0.],
+ ], [
+ [0., 0., 0.],
+ [0., 8., 0.],
+ [0., 0., 0.],
+ ]]]], device=device, dtype=dtype)
+
+ expected = torch.tensor([[[[
+ [0., 0., 0.],
+ [0., 0., 0.],
+ [0., 0., 0.],
+ ], [
+ [4., 2., 0.],
+ [3., 1., 0.],
+ [0., 0., 0.],
+ ], [
+ [0., 0., 0.],
+ [0., 0., 0.],
+ [0., 0., 0.],
+ ]], [[
+ [0., 0., 0.],
+ [0., 7., 0.],
+ [0., 0., 0.],
+ ], [
+ [0., 0., 0.],
+ [0., 6., 8.],
+ [9., 0., 0.],
+ ], [
+ [0., 0., 0.],
+ [0., 0., 0.],
+ [0., 0., 0.],
+ ]]]], device=device, dtype=dtype)
+
+ _, _, D, H, W = input.shape
+ center = torch.tensor([
+ [(W - 1) / 2, (H - 1) / 2, (D - 1) / 2]], device=device, dtype=dtype)
+
+ angles = torch.tensor([[0., 90., 0.]], device=device, dtype=dtype)
+
+ P = proj.get_projective_transform(center, angles)
+ output = proj.warp_projective(input, P, (3, 3, 3))
+ assert_allclose(output, expected)
+
+
+class TestGetRotationMatrix3d:
+ def test_smoke(self, device, dtype):
+ center = torch.rand(1, 3, device=device, dtype=dtype)
+ angle = torch.rand(1, 3, device=device, dtype=dtype)
+ P = proj.get_projective_transform(center, angle)
+ assert P.shape == (1, 3, 4)
+
+ @pytest.mark.parametrize("batch_size", [1, 3, 6])
+ def test_batch(self, batch_size, device, dtype):
+ B: int = batch_size
+ center = torch.rand(B, 3, device=device, dtype=dtype)
+ angle = torch.rand(B, 3, device=device, dtype=dtype)
+ P = proj.get_projective_transform(center, angle)
+ assert P.shape == (B, 3, 4)
+
+ def test_identity(self, device, dtype):
+ center = torch.zeros(1, 3, device=device, dtype=dtype)
+ angle = torch.zeros(1, 3, device=device, dtype=dtype)
+ P = proj.get_projective_transform(center, angle)
+ P_expected = torch.tensor([
+ [1., 0., 0., 0.],
+ [0., 1., 0., 0.],
+ [0., 0., 1., 0.],
+ ], device=device, dtype=dtype)
+ assert_allclose(P, P_expected)
+
+ def test_rot90x(self, device, dtype):
+ center = torch.zeros(1, 3, device=device, dtype=dtype)
+ angle = torch.tensor([[90., 0., 0.]], device=device, dtype=dtype)
+ P = proj.get_projective_transform(center, angle)
+ P_expected = torch.tensor([
+ [1., 0., 0., 0.],
+ [0., 0., -1., 0.],
+ [0., 1., 0., 0.],
+ ], device=device, dtype=dtype)
+ assert_allclose(P, P_expected)
+
+ def test_rot90y(self, device, dtype):
+ center = torch.zeros(1, 3, device=device, dtype=dtype)
+ angle = torch.tensor([[0., 90., 0.]], device=device, dtype=dtype)
+ P = proj.get_projective_transform(center, angle)
+ P_expected = torch.tensor([
+ [0., 0., 1., 0.],
+ [0., 1., 0., 0.],
+ [-1., 0., 0., 0.],
+ ], device=device, dtype=dtype)
+ assert_allclose(P, P_expected)
+
+ def test_rot90z(self, device, dtype):
+ center = torch.zeros(1, 3, device=device, dtype=dtype)
+ angle = torch.tensor([[0., 0., 90.]], device=device, dtype=dtype)
+ P = proj.get_projective_transform(center, angle)
+ P_expected = torch.tensor([
+ [0., -1., 0., 0.],
+ [1., 0., 0., 0.],
+ [0., 0., 1., 0.],
+ ], device=device, dtype=dtype)
+ assert_allclose(P, P_expected)
+
+ def test_gradcheck(self, device):
+ # generate input data
+ center = torch.rand(1, 3, device=device, dtype=torch.float64, requires_grad=True)
+ angle = torch.rand(1, 3, device=device, dtype=torch.float64)
+ assert gradcheck(proj.get_projective_transform, (center, angle), raise_exception=True)