Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

[Feat] Jit warp perspective (#574)

Vadim Bereznyuk26c5fb669fc6
diff --git a/kornia/geometry/linalg.py b/kornia/geometry/linalg.py
index 82beef5c8..89828029e 100644
--- a/kornia/geometry/linalg.py
+++ b/kornia/geometry/linalg.py
@@ -1,9 +1,11 @@
from typing import Optional
import torch
+
import kornia
from kornia.geometry.conversions import convert_points_to_homogeneous
from kornia.geometry.conversions import convert_points_from_homogeneous
+from kornia.testing import check_is_tensor
__all__ = [
@@ -195,8 +197,8 @@ def transform_points(trans_01: torch.Tensor,
>>> trans_01 = torch.eye(4).view(1, 4, 4) # Bx4x4
>>> points_0 = kornia.transform_points(trans_01, points_1) # BxNx3
"""
- if not torch.is_tensor(trans_01) or not torch.is_tensor(points_1):
- raise TypeError("Input type is not a torch.Tensor")
+ check_is_tensor(trans_01)
+ check_is_tensor(points_1)
if not trans_01.device == points_1.device:
raise TypeError("Tensor must be in the same device")
if not trans_01.shape[0] == points_1.shape[0] and trans_01.shape[0] != 1:
diff --git a/kornia/geometry/transform/imgwarp.py b/kornia/geometry/transform/imgwarp.py
index 8bbb3e4fe..7b6f0d3ee 100644
--- a/kornia/geometry/transform/imgwarp.py
+++ b/kornia/geometry/transform/imgwarp.py
@@ -12,6 +12,7 @@ from kornia.geometry.warp import (
from kornia.geometry.conversions import (
deg2rad, normalize_pixel_coordinates, convert_affinematrix_to_homography
)
+from kornia.testing import check_is_tensor
__all__ = [
"warp_perspective",
@@ -35,7 +36,8 @@ def transform_warp_impl(src: torch.Tensor, dst_pix_trans_src_pix: torch.Tensor,
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)
+ 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],
@@ -74,13 +76,8 @@ def warp_perspective(src: torch.Tensor, M: torch.Tensor, dsize: Tuple[int, int],
See a working example `here <https://kornia.readthedocs.io/en/latest/
tutorials/warp_perspective.html>`_.
"""
- if not torch.is_tensor(src):
- raise TypeError("Input src type is not a torch.Tensor. Got {}"
- .format(type(src)))
-
- if not torch.is_tensor(M):
- raise TypeError("Input M type is not a torch.Tensor. Got {}"
- .format(type(M)))
+ check_is_tensor(src)
+ check_is_tensor(M)
if not len(src.shape) == 4:
raise ValueError("Input src must be a BxCxHxW tensor. Got {}"
diff --git a/kornia/geometry/warp/homography_warper.py b/kornia/geometry/warp/homography_warper.py
index 2f7721e1a..bcc45661f 100644
--- a/kornia/geometry/warp/homography_warper.py
+++ b/kornia/geometry/warp/homography_warper.py
@@ -6,16 +6,92 @@ import torch.nn.functional as F
from kornia.utils import create_meshgrid
from kornia.geometry.linalg import transform_points
+from kornia.testing import check_is_tensor
__all__ = [
"HomographyWarper",
"homography_warp",
+ "warp_grid",
"normalize_homography",
"normal_transform_pixel",
]
+def warp_grid(grid: torch.Tensor, src_homo_dst: torch.Tensor) -> torch.Tensor:
+ r"""Compute the grid to warp the coordinates grid by the homography/ies.
+
+ Args:
+ grid: Unwrapped grid of the shape :math:`(1, N, W, 2)`.
+ src_homo_dst (torch.Tensor): Homography or homographies (stacked) to
+ transform all points in the grid. Shape of the homography
+ has to be :math:`(1, 3, 3)` or :math:`(N, 1, 3, 3)`.
+
+
+ Returns:
+ torch.Tensor: the transformed grid of shape :math:`(N, H, W, 2)`.
+ """
+ batch_size: int = src_homo_dst.size(0)
+ _, height, width, _ = grid.size()
+ # expand grid to match the input batch size
+ grid = grid.expand(batch_size, -1, -1, -1) # NxHxWx2
+ if len(src_homo_dst.shape) == 3: # local homography case
+ src_homo_dst = src_homo_dst.view(batch_size, 1, 3, 3) # Nx1x3x3
+ # perform the actual grid transformation,
+ # the grid is copied to input device and casted to the same type
+ flow: torch.Tensor = transform_points(src_homo_dst, grid.to(src_homo_dst)) # NxHxWx2
+ return flow.view(batch_size, height, width, 2) # NxHxWx2
+
+
+# functional api
+def homography_warp(patch_src: torch.Tensor,
+ src_homo_dst: torch.Tensor,
+ dsize: Tuple[int, int],
+ mode: str = 'bilinear',
+ padding_mode: str = 'zeros',
+ align_corners: bool = False,
+ normalized_coordinates: bool = True) -> torch.Tensor:
+ r"""Function that warps image patchs or tensors by homographies.
+
+ See :class:`~kornia.geometry.warp.HomographyWarper` for details.
+
+ Args:
+ patch_src (torch.Tensor): The image or tensor to warp. Should be from
+ source of shape :math:`(N, C, H, W)`.
+ src_homo_dst (torch.Tensor): The homography or stack of homographies
+ from destination to source of shape
+ :math:`(N, 3, 3)`.
+ dsize (Tuple[int, int]): The height and width of the image to warp.
+ 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): interpolation flag. Default: False. See
+ https://pytorch.org/docs/stable/nn.functional.html#torch.nn.functional.interpolate for detail
+ normalized_coordinates (bool): Whether the homography assumes [-1, 1] normalized
+ coordinates or not.
+
+ Return:
+ torch.Tensor: Patch sampled at locations from source to destination.
+
+ Example:
+ >>> input = torch.rand(1, 3, 32, 32)
+ >>> homography = torch.eye(3).view(1, 3, 3)
+ >>> output = kornia.homography_warp(input, homography, (32, 32))
+ """
+ if not src_homo_dst.device == patch_src.device:
+ raise TypeError("Patch and homography must be on the same device. \
+ Got patch.device: {} src_H_dst.device: {}.".format(
+ patch_src.device, src_homo_dst.device))
+
+ height, width = dsize
+ grid = create_meshgrid(height, width, normalized_coordinates=normalized_coordinates)
+ warped_grid = warp_grid(grid, src_homo_dst)
+
+ return F.grid_sample(patch_src, warped_grid, mode=mode, padding_mode=padding_mode,
+ align_corners=align_corners)
+
+
# layer api
class HomographyWarper(nn.Module):
r"""Warp tensors by homographies.
@@ -36,6 +112,7 @@ class HomographyWarper(nn.Module):
align_corners(bool): interpolation flag. Default: False. See
https://pytorch.org/docs/stable/nn.functional.html#torch.nn.functional.interpolate for detail
"""
+ _warped_grid: Optional[torch.Tensor]
def __init__(
self,
@@ -57,7 +134,7 @@ class HomographyWarper(nn.Module):
height, width, normalized_coordinates=normalized_coordinates)
# initialice the warped destination grid
- self._warped_grid: Optional[torch.Tensor] = None
+ self._warped_grid = None
def precompute_warp_grid(self, src_homo_dst: torch.Tensor) -> None:
r"""Compute and store internaly the transformations of the points.
@@ -71,35 +148,9 @@ class HomographyWarper(nn.Module):
The homography assumes normalized coordinates [-1, 1] if
normalized_coordinates is True.
"""
- self._warped_grid = self.warp_grid(src_homo_dst)
-
- def warp_grid(self, src_homo_dst: torch.Tensor) -> torch.Tensor:
- r"""Compute the grid to warp the coordinates grid by the homography/ies.
+ self._warped_grid = warp_grid(self.grid, src_homo_dst)
- Args:
- src_homo_dst (torch.Tensor): Homography or homographies (stacked) to
- transform all points in the grid. Shape of the homography
- has to be :math:`(1, 3, 3)` or :math:`(N, 1, 3, 3)`.
- The homography assumes normalized coordinates [-1, 1] if
- normalized_coordinates is True.
-
- Returns:
- torch.Tensor: the transformed grid of shape :math:`(N, H, W, 2)`.
- """
- batch_size: int = src_homo_dst.shape[0]
- device: torch.device = src_homo_dst.device
- dtype: torch.dtype = src_homo_dst.dtype
- # expand grid to match the input batch size
- grid: torch.Tensor = self.grid.expand(batch_size, -1, -1, -1) # NxHxWx2
- if len(src_homo_dst.shape) == 3: # local homography case
- src_homo_dst = src_homo_dst.view(batch_size, 1, 3, 3) # Nx1x3x3
- # perform the actual grid transformation,
- # the grid is copied to input device and casted to the same type
- flow: torch.Tensor = transform_points(
- src_homo_dst, grid.to(device).to(dtype)) # NxHxWx2
- return flow.view(batch_size, self.height, self.width, 2) # NxHxWx2
-
- def forward( # type: ignore
+ def forward(
self,
patch_src: torch.Tensor,
src_homo_dst: Optional[torch.Tensor] = None) -> torch.Tensor:
@@ -129,67 +180,28 @@ class HomographyWarper(nn.Module):
>>> warper.precompute_warp_grid(homography)
>>> output = warper(input) # NxCxHxW
"""
- warped_grid: torch.Tensor
+ _warped_grid = self._warped_grid
if src_homo_dst is not None:
- if not src_homo_dst.device == patch_src.device:
- raise TypeError("Patch and homography must be on the same device. \
- Got patch.device: {} src_H_dst.device: {}."
- .format(patch_src.device, src_homo_dst.device))
- warped_grid = self.warp_grid(src_homo_dst)
- elif self._warped_grid is not None:
- if not self._warped_grid.device == patch_src.device:
+ warped_patch = homography_warp(
+ patch_src, src_homo_dst, (self.height, self.width), mode=self.mode,
+ padding_mode=self.padding_mode, align_corners=self.align_corners,
+ normalized_coordinates=self.normalized_coordinates)
+ elif _warped_grid is not None:
+ if not _warped_grid.device == patch_src.device:
raise TypeError("Patch and warped grid must be on the same device. \
- Got patch.device: {} warped_grid.device: {}. Wheter \
- recall precompute_warp_grid() with the correct device \
- for the homograhy or change the patch device."
- .format(patch_src.device, self._warped_grid.device))
- warped_grid = self._warped_grid
+ Got patch.device: {} warped_grid.device: {}. Wheter \
+ recall precompute_warp_grid() with the correct device \
+ for the homograhy or change the patch device.".format(
+ patch_src.device, _warped_grid.device))
+ warped_patch = F.grid_sample(
+ patch_src, _warped_grid, mode=self.mode, padding_mode=self.padding_mode,
+ align_corners=self.align_corners)
else:
raise RuntimeError("Unknown warping. If homographies are not provided \
they must be presetted using the method: \
precompute_warp_grid().")
- return F.grid_sample(patch_src, warped_grid, # type: ignore
- mode=self.mode, padding_mode=self.padding_mode,
- align_corners=self.align_corners)
-
-
-# functional api
-def homography_warp(patch_src: torch.Tensor,
- src_homo_dst: torch.Tensor,
- dsize: Tuple[int, int],
- mode: str = 'bilinear',
- padding_mode: str = 'zeros',
- align_corners: bool = False) -> torch.Tensor:
- r"""Function that warps image patchs or tensors by homographies.
-
- See :class:`~kornia.geometry.warp.HomographyWarper` for details.
-
- Args:
- patch_src (torch.Tensor): The image or tensor to warp. Should be from
- source of shape :math:`(N, C, H, W)`.
- src_homo_dst (torch.Tensor): The homography or stack of homographies
- from destination to source of shape
- :math:`(N, 3, 3)`. The homography assumes
- normalized coordinates [-1, 1].
- dsize (Tuple[int, int]): The height and width of the image to warp.
- 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): interpolation flag. Default: False. See
- https://pytorch.org/docs/stable/nn.functional.html#torch.nn.functional.interpolate for detail
- Return:
- torch.Tensor: Patch sampled at locations from source to destination.
-
- Example:
- >>> input = torch.rand(1, 3, 32, 32)
- >>> homography = torch.eye(3).view(1, 3, 3)
- >>> output = kornia.homography_warp(input, homography, (32, 32))
- """
- height, width = dsize
- warper = HomographyWarper(height, width, mode, padding_mode, align_corners=align_corners)
- return warper(patch_src, src_homo_dst)
+ return warped_patch
def normal_transform_pixel(height: int, width: int) -> torch.Tensor:
@@ -232,9 +244,7 @@ def normalize_homography(dst_pix_trans_src_pix: torch.Tensor,
Shape:
Output: :math:`(B, 3, 3)`
"""
- if not torch.is_tensor(dst_pix_trans_src_pix):
- raise TypeError("Input dst_pix_trans_src_pix type is not a torch.Tensor. Got {}"
- .format(type(dst_pix_trans_src_pix)))
+ check_is_tensor(dst_pix_trans_src_pix)
if not (len(dst_pix_trans_src_pix.shape) == 3 or dst_pix_trans_src_pix.shape[-2:] == (3, 3)):
raise ValueError("Input dst_pix_trans_src_pix must be a Bx3x3 tensor. Got {}"
@@ -243,15 +253,12 @@ def normalize_homography(dst_pix_trans_src_pix: torch.Tensor,
# source and destination sizes
src_h, src_w = dsize_src
dst_h, dst_w = dsize_dst
- # the devices and types
- device: torch.device = dst_pix_trans_src_pix.device
- dtype: torch.dtype = dst_pix_trans_src_pix.dtype
# compute the transformation pixel/norm for src/dst
src_norm_trans_src_pix: torch.Tensor = normal_transform_pixel(
- src_h, src_w).to(device, dtype)
+ 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_transform_pixel(
- dst_h, dst_w).to(device, dtype)
+ 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)
diff --git a/kornia/jit/__init__.py b/kornia/jit/__init__.py
index 6e31e8232..863d7b7ff 100644
--- a/kornia/jit/__init__.py
+++ b/kornia/jit/__init__.py
@@ -9,3 +9,4 @@ spatial_soft_argmax2d = torch.jit.script(K.geometry.spatial_soft_argmax2d)
spatial_softmax2d = torch.jit.script(K.geometry.dsnt.spatial_softmax2d)
spatial_expectation2d = torch.jit.script(K.geometry.dsnt.spatial_expectation2d)
render_gaussian2d = torch.jit.script(K.geometry.dsnt.render_gaussian2d)
+warp_perspective = torch.jit.script(K.geometry.warp_perspective)
diff --git a/test/geometry/transform/test_imgwarp.py b/test/geometry/transform/test_imgwarp.py
index 493addc18..ae338909b 100644
--- a/test/geometry/transform/test_imgwarp.py
+++ b/test/geometry/transform/test_imgwarp.py
@@ -184,6 +184,11 @@ class TestWarpPerspective:
(dst_h, dst_w))
assert_allclose(patch_warped, expected)
+ # check jit
+ patch_warped_jit = kornia.jit.warp_perspective(patch, dst_trans_src,
+ (dst_h, dst_w))
+ assert_allclose(patch_warped, patch_warped_jit)
+
def test_crop_center_resize(self, device):
# generate input data
dst_h, dst_w = 4, 4
@@ -228,6 +233,11 @@ class TestWarpPerspective:
(dst_h, dst_w))
assert_allclose(patch_warped, expected)
+ # check jit
+ patch_warped_jit = kornia.jit.warp_perspective(patch, dst_trans_src,
+ (dst_h, dst_w))
+ assert_allclose(patch_warped, patch_warped_jit)
+
class TestWarpAffine:
def test_smoke(self, device):
diff --git a/test/geometry/warp/test_homography_warper.py b/test/geometry/warp/test_homography_warper.py
index 906d49fca..ef470fdfe 100644
--- a/test/geometry/warp/test_homography_warper.py
+++ b/test/geometry/warp/test_homography_warper.py
@@ -11,7 +11,7 @@ from torch.testing import assert_allclose
class TestHomographyWarper:
num_tests = 10
- threshold = 0.05
+ threshold = 0.1
def test_identity(self, device):
# create input data
@@ -79,19 +79,15 @@ class TestHomographyWarper:
height, width = shape
dst_homo_src = utils.create_eye_batch(batch_size=1, eye_size=3).to(device)
dst_homo_src[..., 0, 2] = offset # apply offset in x
-
- # instantiate warper
- warper = kornia.HomographyWarper(height, width,
- normalized_coordinates=False,
- align_corners=True)
- flow = warper.warp_grid(dst_homo_src)
+ grid = kornia.create_meshgrid(height, width, normalized_coordinates=False)
+ flow = kornia.warp_grid(grid, dst_homo_src)
# the grid the src plus the offset should be equal to the flow
# on the x-axis, y-axis remains the same.
assert_allclose(
- warper.grid[..., 0].to(device) + offset, flow[..., 0])
+ grid[..., 0].to(device) + offset, flow[..., 0])
assert_allclose(
- warper.grid[..., 1].to(device), flow[..., 1])
+ grid[..., 1].to(device), flow[..., 1])
@pytest.mark.parametrize("batch_shape", [
(1, 1, 4, 5), (2, 2, 4, 6), (3, 1, 5, 7), ])
@@ -177,8 +173,7 @@ class TestHomographyWarper:
for i in range(self.num_tests):
# generate homography noise
- homo_delta = torch.zeros_like(dst_homo_src)
- homo_delta[:, -1, -1] = 0.0
+ homo_delta = torch.rand_like(dst_homo_src) * 0.3
dst_homo_src_i = dst_homo_src + homo_delta
@@ -193,7 +188,7 @@ class TestHomographyWarper:
# projected should be equal as initial
error = utils.compute_patch_error(
- patch_dst, patch_dst_to_src, height, width)
+ patch_src, patch_dst_to_src, height, width)
assert error.item() < self.threshold
@@ -226,3 +221,35 @@ class TestHomographyWarper:
# evaluate function gradient
assert gradcheck(warper, (patch_src, dst_homo_src,),
raise_exception=True)
+
+ @pytest.mark.parametrize("batch_size", [1, 2, 3])
+ @pytest.mark.parametrize("align_corners", [True, False])
+ @pytest.mark.parametrize("normalized_coordinates", [True, False])
+ def test_jit_warp_homography(self, device, batch_size, align_corners, normalized_coordinates):
+ # generate input data
+ height, width = 128, 64
+ eye_size = 3 # identity 3x3
+
+ # create checkerboard
+ board = utils.create_checkerboard(height, width, 4)
+ patch_src = torch.from_numpy(board).view(1, 1, height, width).expand(batch_size, 1, height,
+ width).to(device)
+
+ # create base homography
+ dst_homo_src = utils.create_eye_batch(batch_size, eye_size).to(device)
+
+ for i in range(self.num_tests):
+ # generate homography noise
+ homo_delta = torch.rand_like(dst_homo_src) * 0.3
+
+ dst_homo_src_i = dst_homo_src + homo_delta
+
+ # transform the points with and without jit
+ patch_dst = kornia.homography_warp(
+ patch_src, dst_homo_src_i, (height, width), align_corners=align_corners,
+ normalized_coordinates=normalized_coordinates)
+ patch_dst_jit = torch.jit.script(kornia.homography_warp)(
+ patch_src, dst_homo_src_i, (height, width), align_corners=align_corners,
+ normalized_coordinates=normalized_coordinates)
+
+ assert_allclose(patch_dst, patch_dst_jit)