Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

[Enhance] Reorganized geometry.warper package (#898)

shijianjianbc573c809434
diff --git a/kornia/geometry/__init__.py b/kornia/geometry/__init__.py
index adbd7c690..02a1e458d 100644
--- a/kornia/geometry/__init__.py
+++ b/kornia/geometry/__init__.py
@@ -2,7 +2,6 @@ from kornia.geometry.camera import *
from kornia.geometry.conversions import *
from kornia.geometry.linalg import *
from kornia.geometry.transform import *
-from kornia.geometry.warp import *
from kornia.geometry.depth import *
from kornia.geometry.subpix import *
from kornia.geometry.epipolar import *
diff --git a/kornia/geometry/depth.py b/kornia/geometry/depth.py
index 528c600f1..50ead24ed 100644
--- a/kornia/geometry/depth.py
+++ b/kornia/geometry/depth.py
@@ -1,13 +1,27 @@
"""Module containing operators to work on RGB-Depth images."""
+from typing import Union
import torch
+import torch.nn as nn
import torch.nn.functional as F
-from kornia.geometry import (
- project_points, unproject_points, transform_points, normalize_pixel_coordinates,
+from kornia.geometry.linalg import (
+ transform_points, inverse_transformation, compose_transformations, convert_points_to_homogeneous
+)
+from kornia.geometry.conversions import normalize_pixel_coordinates
+from kornia.geometry.camera import (
+ PinholeCamera, cam2pixel, pixel2cam, project_points, unproject_points
)
from kornia.utils import create_meshgrid
-from kornia.filters import spatial_gradient
+from kornia.filters.sobel import spatial_gradient
+
+__all__ = [
+ "depth_to_3d",
+ "depth_to_normals",
+ "warp_frame_depth",
+ "depth_warp",
+ "DepthWarper",
+]
def depth_to_3d(depth: torch.Tensor, camera_matrix: torch.Tensor, normalize_points: bool = False) -> torch.Tensor:
@@ -174,3 +188,213 @@ def warp_frame_depth(
points_2d_src, height, width) # BxHxWx2
return F.grid_sample(image_src, points_2d_src_norm, align_corners=True) # type: ignore
+
+
+class DepthWarper(nn.Module):
+ r"""Warps a patch by depth.
+
+ .. math::
+ P_{src}^{\{dst\}} = K_{dst} * T_{src}^{\{dst\}}
+
+ I_{src} = \\omega(I_{dst}, P_{src}^{\{dst\}}, D_{src})
+
+ Args:
+ pinholes_dst (PinholeCamera): the pinhole models for the destination
+ frame.
+ height (int): the height of the image to warp.
+ width (int): the 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: True. See
+ https://pytorch.org/docs/stable/nn.functional.html#torch.nn.functional.interpolate for detail
+ """
+
+ def __init__(self,
+ pinhole_dst: PinholeCamera,
+ height: int, width: int,
+ mode: str = 'bilinear',
+ padding_mode: str = 'zeros',
+ align_corners: bool = True):
+ super(DepthWarper, self).__init__()
+ # constructor members
+ self.width: int = width
+ self.height: int = height
+ self.mode: str = mode
+ self.padding_mode: str = padding_mode
+ self.eps = 1e-6
+ self.align_corners: bool = align_corners
+
+ # state members
+ self._pinhole_dst: PinholeCamera = pinhole_dst
+ self._pinhole_src: Union[None, PinholeCamera] = None
+ self._dst_proj_src: Union[None, torch.Tensor] = None
+
+ self.grid: torch.Tensor = self._create_meshgrid(height, width)
+
+ @staticmethod
+ def _create_meshgrid(height: int, width: int) -> torch.Tensor:
+ grid: torch.Tensor = create_meshgrid(
+ height, width, normalized_coordinates=False) # 1xHxWx2
+ return convert_points_to_homogeneous(grid) # append ones to last dim
+
+ def compute_projection_matrix(
+ self, pinhole_src: PinholeCamera) -> 'DepthWarper':
+ r"""Computes the projection matrix from the source to destination frame.
+ """
+ if not isinstance(self._pinhole_dst, PinholeCamera):
+ raise TypeError("Member self._pinhole_dst expected to be of class "
+ "PinholeCamera. Got {}"
+ .format(type(self._pinhole_dst)))
+ if not isinstance(pinhole_src, PinholeCamera):
+ raise TypeError("Argument pinhole_src expected to be of class "
+ "PinholeCamera. Got {}".format(type(pinhole_src)))
+ # compute the relative pose between the non reference and the reference
+ # camera frames.
+ dst_trans_src: torch.Tensor = compose_transformations(
+ self._pinhole_dst.extrinsics,
+ inverse_transformation(pinhole_src.extrinsics),
+ )
+
+ # compute the projection matrix between the non reference cameras and
+ # the reference.
+ dst_proj_src: torch.Tensor = torch.matmul(
+ self._pinhole_dst.intrinsics, dst_trans_src)
+
+ # update class members
+ self._pinhole_src = pinhole_src
+ self._dst_proj_src = dst_proj_src
+ return self
+
+ def _compute_projection(self, x, y, invd):
+ point = torch.tensor(
+ [[[x], [y], [1.0], [invd]]], device=self._dst_proj_src.device, dtype=self._dst_proj_src.dtype)
+ flow = torch.matmul(self._dst_proj_src, point)
+ z = 1. / flow[:, 2]
+ x = (flow[:, 0] * z)
+ y = (flow[:, 1] * z)
+ return torch.cat([x, y], 1)
+
+ def compute_subpixel_step(self) -> torch.Tensor:
+ """This computes the required inverse depth step to achieve sub pixel
+ accurate sampling of the depth cost volume, per camera.
+
+ Szeliski, Richard, and Daniel Scharstein.
+ "Symmetric sub-pixel stereo matching." European Conference on Computer
+ Vision. Springer Berlin Heidelberg, 2002.
+ """
+ delta_d = 0.01
+ xy_m1 = self._compute_projection(self.width / 2, self.height / 2,
+ 1.0 - delta_d)
+ xy_p1 = self._compute_projection(self.width / 2, self.height / 2,
+ 1.0 + delta_d)
+ dx = torch.norm((xy_p1 - xy_m1), 2, dim=-1) / 2.0
+ dxdd = dx / (delta_d) # pixel*(1/meter)
+ # half pixel sampling, we're interested in the min for all cameras
+ return torch.min(0.5 / dxdd)
+
+ def warp_grid(self, depth_src: torch.Tensor) -> torch.Tensor:
+ """Computes a grid for warping a given the depth from the reference
+ pinhole camera.
+
+ The function `compute_projection_matrix` has to be called beforehand in
+ order to have precomputed the relative projection matrices encoding the
+ relative pose and the intrinsics between the reference and a non
+ reference camera.
+ """
+ # TODO: add type and value checkings
+ if self._dst_proj_src is None or self._pinhole_src is None:
+ raise ValueError("Please, call compute_projection_matrix.")
+
+ if len(depth_src.shape) != 4:
+ raise ValueError("Input depth_src has to be in the shape of "
+ "Bx1xHxW. Got {}".format(depth_src.shape))
+
+ # unpack depth attributes
+ batch_size, _, height, width = depth_src.shape
+ device: torch.device = depth_src.device
+ dtype: torch.dtype = depth_src.dtype
+
+ # expand the base coordinate grid according to the input batch size
+ pixel_coords: torch.Tensor = self.grid.to(device=device, dtype=dtype).expand(
+ batch_size, -1, -1, -1) # BxHxWx3
+
+ # reproject the pixel coordinates to the camera frame
+ cam_coords_src: torch.Tensor = pixel2cam(
+ depth_src,
+ self._pinhole_src.intrinsics_inverse().to(device=device, dtype=dtype),
+ pixel_coords) # BxHxWx3
+
+ # reproject the camera coordinates to the pixel
+ pixel_coords_src: torch.Tensor = cam2pixel(
+ cam_coords_src, self._dst_proj_src.to(device=device, dtype=dtype)) # (B*N)xHxWx2
+
+ # normalize between -1 and 1 the coordinates
+ pixel_coords_src_norm: torch.Tensor = normalize_pixel_coordinates(
+ pixel_coords_src, self.height, self.width)
+ return pixel_coords_src_norm
+
+ def forward( # type: ignore
+ self,
+ depth_src: torch.Tensor,
+ patch_dst: torch.Tensor) -> torch.Tensor:
+ """Warps a tensor from destination frame to reference given the depth
+ in the reference frame.
+
+ Args:
+ depth_src (torch.Tensor): the depth in the reference frame. The
+ tensor must have a shape :math:`(B, 1, H, W)`.
+ patch_dst (torch.Tensor): the patch in the destination frame. The
+ tensor must have a shape :math:`(B, C, H, W)`.
+
+ Return:
+ torch.Tensor: the warped patch from destination frame to reference.
+
+ Shape:
+ - Output: :math:`(N, C, H, W)` where C = number of channels.
+
+ Example:
+ >>> # pinholes camera models
+ >>> pinhole_dst = PinholeCamera(torch.randn(1, 4, 4), torch.randn(1, 4, 4),
+ ... torch.tensor([32]), torch.tensor([32]))
+ >>> pinhole_src = PinholeCamera(torch.randn(1, 4, 4), torch.randn(1, 4, 4),
+ ... torch.tensor([32]), torch.tensor([32]))
+ >>> # create the depth warper, compute the projection matrix
+ >>> warper = DepthWarper(pinhole_dst, 32, 32)
+ >>> _ = warper.compute_projection_matrix(pinhole_src)
+ >>> # warp the destionation frame to reference by depth
+ >>> depth_src = torch.ones(1, 1, 32, 32) # Nx1xHxW
+ >>> image_dst = torch.rand(1, 3, 32, 32) # NxCxHxW
+ >>> image_src = warper(depth_src, image_dst) # NxCxHxW
+ """
+ return F.grid_sample(patch_dst, self.warp_grid(depth_src), # type: ignore
+ mode=self.mode, padding_mode=self.padding_mode,
+ align_corners=self.align_corners)
+
+
+def depth_warp(pinhole_dst: PinholeCamera,
+ pinhole_src: PinholeCamera,
+ depth_src: torch.Tensor,
+ patch_dst: torch.Tensor,
+ height: int, width: int,
+ align_corners: bool = True):
+ r"""Function that warps a tensor from destination frame to reference
+ given the depth in the reference frame.
+
+ See :class:`~kornia.geometry.warp.DepthWarper` for details.
+
+ Example:
+ >>> # pinholes camera models
+ >>> pinhole_dst = PinholeCamera(torch.randn(1, 4, 4), torch.randn(1, 4, 4),
+ ... torch.tensor([32]), torch.tensor([32]))
+ >>> pinhole_src = PinholeCamera(torch.randn(1, 4, 4), torch.randn(1, 4, 4),
+ ... torch.tensor([32]), torch.tensor([32]))
+ >>> # warp the destionation frame to reference by depth
+ >>> depth_src = torch.ones(1, 1, 32, 32) # Nx1xHxW
+ >>> image_dst = torch.rand(1, 3, 32, 32) # NxCxHxW
+ >>> image_src = depth_warp(pinhole_dst, pinhole_src, depth_src, image_dst, 32, 32) # NxCxHxW
+ """
+ warper = DepthWarper(pinhole_dst, height, width, align_corners=align_corners)
+ warper.compute_projection_matrix(pinhole_src)
+ return warper(depth_src, patch_dst)
diff --git a/kornia/geometry/transform/__init__.py b/kornia/geometry/transform/__init__.py
index 095ddf18d..9ba9d27c4 100644
--- a/kornia/geometry/transform/__init__.py
+++ b/kornia/geometry/transform/__init__.py
@@ -7,3 +7,4 @@ from kornia.geometry.transform.affwarp import *
from kornia.geometry.transform.flips import *
from kornia.geometry.transform.projwarp import *
from kornia.geometry.transform.elastic_transform import *
+from kornia.geometry.transform.homography_warper import *
diff --git a/kornia/geometry/transform/homography_warper.py b/kornia/geometry/transform/homography_warper.py
new file mode 100644
index 000000000..27971b0e1
--- /dev/null
+++ b/kornia/geometry/transform/homography_warper.py
@@ -0,0 +1,412 @@
+from typing import Tuple, Optional
+
+import torch
+import torch.nn as nn
+import torch.nn.functional as F
+
+from kornia.utils import create_meshgrid, create_meshgrid3d
+from kornia.geometry.linalg import transform_points
+from kornia.testing import check_is_tensor
+
+__all__ = [
+ "HomographyWarper",
+ "homography_warp",
+ "homography_warp3d",
+ "warp_grid",
+ "warp_grid3d",
+ "normalize_homography",
+ "normalize_homography3d",
+ "normal_transform_pixel",
+ "normal_transform_pixel3d",
+]
+
+
+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
+
+
+def warp_grid3d(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, D, H, W, 3)`.
+ 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, 4, 4)` or :math:`(N, 1, 4, 4)`.
+
+ Returns:
+ torch.Tensor: the transformed grid of shape :math:`(N, H, W, 3)`.
+ """
+ batch_size: int = src_homo_dst.size(0)
+ _, depth, height, width, _ = grid.size()
+ # expand grid to match the input batch size
+ grid = grid.expand(batch_size, -1, -1, -1, -1) # NxDxHxWx3
+ if len(src_homo_dst.shape) == 3: # local homography case
+ src_homo_dst = src_homo_dst.view(batch_size, 1, 4, 4) # 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)) # NxDxHxWx3
+ return flow.view(batch_size, depth, height, width, 3) # NxDxHxWx3
+
+
+# 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"""Warp image patchs or tensors by normalized 2D 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 = 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)
+
+
+def homography_warp3d(patch_src: torch.Tensor,
+ src_homo_dst: torch.Tensor,
+ dsize: Tuple[int, int, int],
+ mode: str = 'bilinear',
+ padding_mode: str = 'zeros',
+ align_corners: bool = False,
+ normalized_coordinates: bool = True) -> torch.Tensor:
+ r"""Warp image patchs or tensors by normalized 3D homographies.
+
+ Args:
+ patch_src (torch.Tensor): The image or tensor to warp. Should be from
+ source of shape :math:`(N, C, D, H, W)`.
+ src_homo_dst (torch.Tensor): The homography or stack of homographies
+ from destination to source of shape
+ :math:`(N, 4, 4)`.
+ dsize (Tuple[int, 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 details.
+ 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 = 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))
+
+ depth, height, width = dsize
+ grid = create_meshgrid3d(depth, height, width, normalized_coordinates=normalized_coordinates,
+ device=patch_src.device)
+ warped_grid = warp_grid3d(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.
+
+ .. math::
+
+ X_{dst} = H_{src}^{\{dst\}} * X_{src}
+
+ Args:
+ height (int): The height of the destination tensor.
+ width (int): The width of the destination tensor.
+ 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'.
+ normalized_coordinates (bool): wether to use a grid with
+ normalized coordinates.
+ 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,
+ height: int,
+ width: int,
+ mode: str = 'bilinear',
+ padding_mode: str = 'zeros',
+ normalized_coordinates: bool = True,
+ align_corners: bool = False) -> None:
+ super(HomographyWarper, self).__init__()
+ self.width: int = width
+ self.height: int = height
+ self.mode: str = mode
+ self.padding_mode: str = padding_mode
+ self.normalized_coordinates: bool = normalized_coordinates
+ self.align_corners: bool = align_corners
+ # create base grid to compute the flow
+ self.grid: torch.Tensor = create_meshgrid(
+ height, width, normalized_coordinates=normalized_coordinates)
+
+ # initialice the warped destination grid
+ 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.
+
+ Useful when the same homography/homographies are reused.
+
+ 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.
+ """
+ self._warped_grid = warp_grid(self.grid, src_homo_dst)
+
+ def forward(
+ self,
+ patch_src: torch.Tensor,
+ src_homo_dst: Optional[torch.Tensor] = None) -> torch.Tensor:
+ r"""Warp a tensor from source into reference frame.
+
+ Args:
+ patch_src (torch.Tensor): The tensor to warp.
+ src_homo_dst (torch.Tensor, optional): The homography or stack of
+ homographies from destination to source. The homography assumes
+ normalized coordinates [-1, 1] if normalized_coordinates is True.
+ Default: None.
+
+ Return:
+ torch.Tensor: Patch sampled at locations from source to destination.
+
+ Shape:
+ - Input: :math:`(N, C, H, W)` and :math:`(N, 3, 3)`
+ - Output: :math:`(N, C, H, W)`
+
+ Example:
+ >>> input = torch.rand(1, 3, 32, 32)
+ >>> homography = torch.eye(3).view(1, 3, 3)
+ >>> warper = HomographyWarper(32, 32)
+ >>> # without precomputing the warp
+ >>> output = warper(input, homography) # NxCxHxW
+ >>> # precomputing the warp
+ >>> warper.precompute_warp_grid(homography)
+ >>> output = warper(input) # NxCxHxW
+ """
+ _warped_grid = self._warped_grid
+ if src_homo_dst is not None:
+ 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: {}. Whether \
+ 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 preset using the method: \
+ precompute_warp_grid().")
+
+ return warped_patch
+
+
+def normal_transform_pixel(
+ height: int, width: int, eps: float = 1e-14,
+ device: Optional[torch.device] = None, dtype: Optional[torch.dtype] = None
+) -> torch.Tensor:
+ r"""Compute the normalization matrix from image size in pixels to [-1, 1].
+
+ Args:
+ height (int): image height.
+ width (int): image width.
+ eps (float): epsilon to prevent divide-by-zero errors
+
+ Returns:
+ torch.Tensor: normalized transform with shape :math:`(1, 3, 3)`.
+ """
+ tr_mat = torch.tensor([[1.0, 0.0, -1.0],
+ [0.0, 1.0, -1.0],
+ [0.0, 0.0, 1.0]], device=device, dtype=dtype) # 3x3
+
+ # prevent divide by zero bugs
+ width_denom: float = eps if width == 1 else width - 1.0
+ height_denom: float = eps if height == 1 else height - 1.0
+
+ tr_mat[0, 0] = tr_mat[0, 0] * 2.0 / width_denom
+ tr_mat[1, 1] = tr_mat[1, 1] * 2.0 / height_denom
+
+ return tr_mat.unsqueeze(0) # 1x3x3
+
+
+def normal_transform_pixel3d(
+ depth: int, height: int, width: int, eps: float = 1e-14,
+ device: Optional[torch.device] = None, dtype: Optional[torch.dtype] = None
+) -> torch.Tensor:
+ r"""Compute the normalization matrix from image size in pixels to [-1, 1].
+
+ Args:
+ depth (int): image depth.
+ height (int): image height.
+ width (int): image width.
+ eps (float): epsilon to prevent divide-by-zero errors
+
+ Returns:
+ 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]], device=device, dtype=dtype) # 4x4
+
+ # prevent divide by zero bugs
+ width_denom: float = eps if width == 1 else width - 1.0
+ height_denom: float = eps if height == 1 else height - 1.0
+ depth_denom: float = eps if depth == 1 else depth - 1.0
+
+ tr_mat[0, 0] = tr_mat[0, 0] * 2.0 / width_denom
+ tr_mat[1, 1] = tr_mat[1, 1] * 2.0 / height_denom
+ tr_mat[2, 2] = tr_mat[2, 2] * 2.0 / depth_denom
+
+ return tr_mat.unsqueeze(0) # 1x4x4
+
+
+def normalize_homography(dst_pix_trans_src_pix: torch.Tensor,
+ dsize_src: Tuple[int, int], dsize_dst: Tuple[int, int]) -> torch.Tensor:
+ r"""Normalize a given homography in pixels to [-1, 1].
+
+ Args:
+ dst_pix_trans_src_pix (torch.Tensor): homography/ies from source to destination to be
+ normalized. :math:`(B, 3, 3)`
+ dsize_src (tuple): size of the source image (height, width).
+ dsize_dst (tuple): size of the destination image (height, width).
+
+ Returns:
+ torch.Tensor: the normalized homography of shape :math:`(B, 3, 3)`.
+ """
+ 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 {}"
+ .format(dst_pix_trans_src_pix.shape))
+
+ # source and destination sizes
+ src_h, src_w = dsize_src
+ dst_h, dst_w = dsize_dst
+
+ # compute the transformation pixel/norm for src/dst
+ src_norm_trans_src_pix: torch.Tensor = normal_transform_pixel(
+ 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(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 normalize_homography3d(dst_pix_trans_src_pix: torch.Tensor,
+ dsize_src: Tuple[int, int, int], dsize_dst: Tuple[int, int, int]) -> torch.Tensor:
+ r"""Normalize a given homography in pixels to [-1, 1].
+
+ Args:
+ dst_pix_trans_src_pix (torch.Tensor): homography/ies from source to destination to be
+ normalized. :math:`(B, 4, 4)`
+ dsize_src (tuple): size of the source image (depth, height, width).
+ dsize_src (tuple): size of the destination image (depth, height, width).
+
+ Returns:
+ Tensor: the normalized homography.
+
+ Shape:
+ Output: :math:`(B, 4, 4)`
+ """
+ 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:] == (4, 4)):
+ raise ValueError("Input dst_pix_trans_src_pix must be a Bx3x3 tensor. Got {}"
+ .format(dst_pix_trans_src_pix.shape))
+
+ # source and destination sizes
+ src_d, src_h, src_w = dsize_src
+ dst_d, dst_h, dst_w = dsize_dst
+ # compute the transformation pixel/norm for src/dst
+ src_norm_trans_src_pix: torch.Tensor = normal_transform_pixel3d(
+ 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_transform_pixel3d(
+ dst_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
diff --git a/kornia/geometry/transform/imgwarp.py b/kornia/geometry/transform/imgwarp.py
index d828efa4e..abcea11b7 100644
--- a/kornia/geometry/transform/imgwarp.py
+++ b/kornia/geometry/transform/imgwarp.py
@@ -3,7 +3,7 @@ from typing import Tuple, Optional
import torch
import torch.nn.functional as F
-from kornia.geometry.warp import (
+from kornia.geometry.transform.homography_warper import (
normalize_homography, homography_warp
)
from kornia.geometry.conversions import (
diff --git a/kornia/geometry/transform/projwarp.py b/kornia/geometry/transform/projwarp.py
index 8cf3bca7d..f1d132b77 100644
--- a/kornia/geometry/transform/projwarp.py
+++ b/kornia/geometry/transform/projwarp.py
@@ -4,7 +4,7 @@ from typing import Tuple, List
import torch
import kornia as K
from kornia.geometry.conversions import convert_affinematrix_to_homography3d
-from kornia.geometry.warp import normalize_homography3d, homography_warp3d
+from kornia.geometry.transform.homography_warper import normalize_homography3d, homography_warp3d
from kornia.testing import check_is_tensor
__all__ = [
diff --git a/kornia/geometry/warp/depth_warper.py b/kornia/geometry/warp/depth_warper.py
index 419a6409d..e7f25e361 100644
--- a/kornia/geometry/warp/depth_warper.py
+++ b/kornia/geometry/warp/depth_warper.py
@@ -1,15 +1,15 @@
from typing import Union
-import torch
-import torch.nn as nn
-import torch.nn.functional as F
-from kornia.geometry.linalg import transform_points, inverse_transformation, compose_transformations
-from kornia.geometry.conversions import convert_points_to_homogeneous
-from kornia.geometry.conversions import normalize_pixel_coordinates
-from kornia.geometry.camera import PinholeCamera
-from kornia.geometry.camera import cam2pixel, pixel2cam
-from kornia.utils import create_meshgrid
+import torch
+import warnings
+from kornia.geometry.depth import (
+ DepthWarper as _DepthWarper,
+ depth_warp as _depth_warp
+)
+from kornia.geometry.camera import (
+ PinholeCamera, cam2pixel, pixel2cam
+)
__all__ = [
"depth_warp",
@@ -17,26 +17,8 @@ __all__ = [
]
-class DepthWarper(nn.Module):
- r"""Warps a patch by depth.
-
- .. math::
- P_{src}^{\{dst\}} = K_{dst} * T_{src}^{\{dst\}}
-
- I_{src} = \\omega(I_{dst}, P_{src}^{\{dst\}}, D_{src})
-
- Args:
- pinholes_dst (PinholeCamera): the pinhole models for the destination
- frame.
- height (int): the height of the image to warp.
- width (int): the 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: True. See
- https://pytorch.org/docs/stable/nn.functional.html#torch.nn.functional.interpolate for detail
- """
+class DepthWarper(_DepthWarper):
+ __doc__ = _DepthWarper.__doc__
def __init__(self,
pinhole_dst: PinholeCamera,
@@ -44,163 +26,14 @@ class DepthWarper(nn.Module):
mode: str = 'bilinear',
padding_mode: str = 'zeros',
align_corners: bool = True):
- super(DepthWarper, self).__init__()
- # constructor members
- self.width: int = width
- self.height: int = height
- self.mode: str = mode
- self.padding_mode: str = padding_mode
- self.eps = 1e-6
- self.align_corners: bool = align_corners
-
- # state members
- self._pinhole_dst: PinholeCamera = pinhole_dst
- self._pinhole_src: Union[None, PinholeCamera] = None
- self._dst_proj_src: Union[None, torch.Tensor] = None
-
- self.grid: torch.Tensor = self._create_meshgrid(height, width)
-
- @staticmethod
- def _create_meshgrid(height: int, width: int) -> torch.Tensor:
- grid: torch.Tensor = create_meshgrid(
- height, width, normalized_coordinates=False) # 1xHxWx2
- return convert_points_to_homogeneous(grid) # append ones to last dim
-
- def compute_projection_matrix(
- self, pinhole_src: PinholeCamera) -> 'DepthWarper':
- r"""Computes the projection matrix from the source to destination frame.
- """
- if not isinstance(self._pinhole_dst, PinholeCamera):
- raise TypeError("Member self._pinhole_dst expected to be of class "
- "PinholeCamera. Got {}"
- .format(type(self._pinhole_dst)))
- if not isinstance(pinhole_src, PinholeCamera):
- raise TypeError("Argument pinhole_src expected to be of class "
- "PinholeCamera. Got {}".format(type(pinhole_src)))
- # compute the relative pose between the non reference and the reference
- # camera frames.
- dst_trans_src: torch.Tensor = compose_transformations(
- self._pinhole_dst.extrinsics,
- inverse_transformation(pinhole_src.extrinsics),
- )
-
- # compute the projection matrix between the non reference cameras and
- # the reference.
- dst_proj_src: torch.Tensor = torch.matmul(
- self._pinhole_dst.intrinsics, dst_trans_src)
-
- # update class members
- self._pinhole_src = pinhole_src
- self._dst_proj_src = dst_proj_src
- return self
-
- def _compute_projection(self, x, y, invd):
- point = torch.tensor(
- [[[x], [y], [1.0], [invd]]], device=self._dst_proj_src.device, dtype=self._dst_proj_src.dtype)
- flow = torch.matmul(self._dst_proj_src, point)
- z = 1. / flow[:, 2]
- x = (flow[:, 0] * z)
- y = (flow[:, 1] * z)
- return torch.cat([x, y], 1)
-
- def compute_subpixel_step(self) -> torch.Tensor:
- """This computes the required inverse depth step to achieve sub pixel
- accurate sampling of the depth cost volume, per camera.
-
- Szeliski, Richard, and Daniel Scharstein.
- "Symmetric sub-pixel stereo matching." European Conference on Computer
- Vision. Springer Berlin Heidelberg, 2002.
- """
- delta_d = 0.01
- xy_m1 = self._compute_projection(self.width / 2, self.height / 2,
- 1.0 - delta_d)
- xy_p1 = self._compute_projection(self.width / 2, self.height / 2,
- 1.0 + delta_d)
- dx = torch.norm((xy_p1 - xy_m1), 2, dim=-1) / 2.0
- dxdd = dx / (delta_d) # pixel*(1/meter)
- # half pixel sampling, we're interested in the min for all cameras
- return torch.min(0.5 / dxdd)
-
- def warp_grid(self, depth_src: torch.Tensor) -> torch.Tensor:
- """Computes a grid for warping a given the depth from the reference
- pinhole camera.
+ super(DepthWarper, self).__init__(
+ pinhole_dst=pinhole_dst, height=height, width=width, mode=mode, padding_mode=padding_mode,
+ align_corners=align_corners)
+ warnings.warn(
+ "`DepthWarper` is deprecated and will be removed > 0.6.0. "
+ "Please use `kornia.geometry.DepthWarper instead.`",
+ DeprecationWarning, stacklevel=2)
- The function `compute_projection_matrix` has to be called beforehand in
- order to have precomputed the relative projection matrices encoding the
- relative pose and the intrinsics between the reference and a non
- reference camera.
- """
- # TODO: add type and value checkings
- if self._dst_proj_src is None or self._pinhole_src is None:
- raise ValueError("Please, call compute_projection_matrix.")
-
- if len(depth_src.shape) != 4:
- raise ValueError("Input depth_src has to be in the shape of "
- "Bx1xHxW. Got {}".format(depth_src.shape))
-
- # unpack depth attributes
- batch_size, _, height, width = depth_src.shape
- device: torch.device = depth_src.device
- dtype: torch.dtype = depth_src.dtype
-
- # expand the base coordinate grid according to the input batch size
- pixel_coords: torch.Tensor = self.grid.to(device=device, dtype=dtype).expand(
- batch_size, -1, -1, -1) # BxHxWx3
-
- # reproject the pixel coordinates to the camera frame
- cam_coords_src: torch.Tensor = pixel2cam(
- depth_src,
- self._pinhole_src.intrinsics_inverse().to(device=device, dtype=dtype),
- pixel_coords) # BxHxWx3
-
- # reproject the camera coordinates to the pixel
- pixel_coords_src: torch.Tensor = cam2pixel(
- cam_coords_src, self._dst_proj_src.to(device=device, dtype=dtype)) # (B*N)xHxWx2
-
- # normalize between -1 and 1 the coordinates
- pixel_coords_src_norm: torch.Tensor = normalize_pixel_coordinates(
- pixel_coords_src, self.height, self.width)
- return pixel_coords_src_norm
-
- def forward( # type: ignore
- self,
- depth_src: torch.Tensor,
- patch_dst: torch.Tensor) -> torch.Tensor:
- """Warps a tensor from destination frame to reference given the depth
- in the reference frame.
-
- Args:
- depth_src (torch.Tensor): the depth in the reference frame. The
- tensor must have a shape :math:`(B, 1, H, W)`.
- patch_dst (torch.Tensor): the patch in the destination frame. The
- tensor must have a shape :math:`(B, C, H, W)`.
-
- Return:
- torch.Tensor: the warped patch from destination frame to reference.
-
- Shape:
- - Output: :math:`(N, C, H, W)` where C = number of channels.
-
- Example:
- >>> # pinholes camera models
- >>> pinhole_dst = PinholeCamera(torch.randn(1, 4, 4), torch.randn(1, 4, 4),
- ... torch.tensor([32]), torch.tensor([32]))
- >>> pinhole_src = PinholeCamera(torch.randn(1, 4, 4), torch.randn(1, 4, 4),
- ... torch.tensor([32]), torch.tensor([32]))
- >>> # create the depth warper, compute the projection matrix
- >>> warper = DepthWarper(pinhole_dst, 32, 32)
- >>> _ = warper.compute_projection_matrix(pinhole_src)
- >>> # warp the destionation frame to reference by depth
- >>> depth_src = torch.ones(1, 1, 32, 32) # Nx1xHxW
- >>> image_dst = torch.rand(1, 3, 32, 32) # NxCxHxW
- >>> image_src = warper(depth_src, image_dst) # NxCxHxW
- """
- return F.grid_sample(patch_dst, self.warp_grid(depth_src), # type: ignore
- mode=self.mode, padding_mode=self.padding_mode,
- align_corners=self.align_corners)
-
-
-# functional api
def depth_warp(pinhole_dst: PinholeCamera,
pinhole_src: PinholeCamera,
@@ -208,22 +41,8 @@ def depth_warp(pinhole_dst: PinholeCamera,
patch_dst: torch.Tensor,
height: int, width: int,
align_corners: bool = True):
- r"""Function that warps a tensor from destination frame to reference
- given the depth in the reference frame.
-
- See :class:`~kornia.geometry.warp.DepthWarper` for details.
-
- Example:
- >>> # pinholes camera models
- >>> pinhole_dst = PinholeCamera(torch.randn(1, 4, 4), torch.randn(1, 4, 4),
- ... torch.tensor([32]), torch.tensor([32]))
- >>> pinhole_src = PinholeCamera(torch.randn(1, 4, 4), torch.randn(1, 4, 4),
- ... torch.tensor([32]), torch.tensor([32]))
- >>> # warp the destionation frame to reference by depth
- >>> depth_src = torch.ones(1, 1, 32, 32) # Nx1xHxW
- >>> image_dst = torch.rand(1, 3, 32, 32) # NxCxHxW
- >>> image_src = depth_warp(pinhole_dst, pinhole_src, depth_src, image_dst, 32, 32) # NxCxHxW
- """
- warper = DepthWarper(pinhole_dst, height, width, align_corners=align_corners)
- warper.compute_projection_matrix(pinhole_src)
- return warper(depth_src, patch_dst)
+ __doc__ = _depth_warp.__doc__
+ warnings.warn(
+ "`depth_warp` is deprecated and will be removed > 0.6.0. Please use `kornia.geometry.depth_warp instead.`",
+ DeprecationWarning, stacklevel=2)
+ return _depth_warp(pinhole_dst, pinhole_src, depth_src, patch_dst, height, width, align_corners)
diff --git a/kornia/geometry/warp/homography_warper.py b/kornia/geometry/warp/homography_warper.py
index 27971b0e1..ba04d78d1 100644
--- a/kornia/geometry/warp/homography_warper.py
+++ b/kornia/geometry/warp/homography_warper.py
@@ -1,12 +1,12 @@
from typing import Tuple, Optional
import torch
-import torch.nn as nn
-import torch.nn.functional as F
+import warnings
from kornia.utils import create_meshgrid, create_meshgrid3d
from kornia.geometry.linalg import transform_points
from kornia.testing import check_is_tensor
+import kornia.geometry.transform.homography_warper as HMW
__all__ = [
"HomographyWarper",
@@ -22,51 +22,19 @@ __all__ = [
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
+ __doc__ = HMW.warp_grid.__doc__
+ warnings.warn(
+ "`warp_grid` is deprecated and will be removed > 0.6.0. "
+ "Please use `kornia.geometry.transform.warp_grid instead.`",
+ DeprecationWarning, stacklevel=2)
+ return HMW.warp_grid(grid, src_homo_dst)
def warp_grid3d(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, D, H, W, 3)`.
- 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, 4, 4)` or :math:`(N, 1, 4, 4)`.
-
- Returns:
- torch.Tensor: the transformed grid of shape :math:`(N, H, W, 3)`.
- """
- batch_size: int = src_homo_dst.size(0)
- _, depth, height, width, _ = grid.size()
- # expand grid to match the input batch size
- grid = grid.expand(batch_size, -1, -1, -1, -1) # NxDxHxWx3
- if len(src_homo_dst.shape) == 3: # local homography case
- src_homo_dst = src_homo_dst.view(batch_size, 1, 4, 4) # 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)) # NxDxHxWx3
- return flow.view(batch_size, depth, height, width, 3) # NxDxHxWx3
+ __doc__ = HMW.warp_grid3d.__doc__
+ warnings.warn("`warp_grid3d` is deprecated. Please use `kornia.geometry.transform.warp_grid3d instead.`",
+ DeprecationWarning, stacklevel=2)
+ return HMW.warp_grid3d(grid, src_homo_dst)
# functional api
@@ -77,45 +45,13 @@ def homography_warp(patch_src: torch.Tensor,
padding_mode: str = 'zeros',
align_corners: bool = False,
normalized_coordinates: bool = True) -> torch.Tensor:
- r"""Warp image patchs or tensors by normalized 2D 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 = 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)
+ __doc__ = HMW.homography_warp.__doc__
+ warnings.warn(
+ "`homography_warp` is deprecated and will be removed > 0.6.0."
+ "Please use `kornia.geometry.transform.homography_warp instead.`",
+ DeprecationWarning, stacklevel=2)
+ return HMW.homography_warp(
+ patch_src, src_homo_dst, dsize, mode, padding_mode, align_corners, normalized_coordinates)
def homography_warp3d(patch_src: torch.Tensor,
@@ -125,67 +61,18 @@ def homography_warp3d(patch_src: torch.Tensor,
padding_mode: str = 'zeros',
align_corners: bool = False,
normalized_coordinates: bool = True) -> torch.Tensor:
- r"""Warp image patchs or tensors by normalized 3D homographies.
-
- Args:
- patch_src (torch.Tensor): The image or tensor to warp. Should be from
- source of shape :math:`(N, C, D, H, W)`.
- src_homo_dst (torch.Tensor): The homography or stack of homographies
- from destination to source of shape
- :math:`(N, 4, 4)`.
- dsize (Tuple[int, 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 details.
- 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 = 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))
-
- depth, height, width = dsize
- grid = create_meshgrid3d(depth, height, width, normalized_coordinates=normalized_coordinates,
- device=patch_src.device)
- warped_grid = warp_grid3d(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.
-
- .. math::
+ __doc__ = HMW.homography_warp3d.__doc__
+ warnings.warn(
+ "`homography_warp3d` is deprecated and will be removed > 0.6.0. "
+ "Please use `kornia.geometry.transform.homography_warp3d instead.`",
+ DeprecationWarning, stacklevel=2
+ )
+ return HMW.homography_warp3d(
+ patch_src, src_homo_dst, dsize, mode, padding_mode, align_corners, normalized_coordinates)
- X_{dst} = H_{src}^{\{dst\}} * X_{src}
- Args:
- height (int): The height of the destination tensor.
- width (int): The width of the destination tensor.
- 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'.
- normalized_coordinates (bool): wether to use a grid with
- normalized coordinates.
- 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]
+class HomographyWarper(HMW.HomographyWarper):
+ __doc__ = HMW.HomographyWarper.__doc__
def __init__(
self,
@@ -195,218 +82,58 @@ class HomographyWarper(nn.Module):
padding_mode: str = 'zeros',
normalized_coordinates: bool = True,
align_corners: bool = False) -> None:
- super(HomographyWarper, self).__init__()
- self.width: int = width
- self.height: int = height
- self.mode: str = mode
- self.padding_mode: str = padding_mode
- self.normalized_coordinates: bool = normalized_coordinates
- self.align_corners: bool = align_corners
- # create base grid to compute the flow
- self.grid: torch.Tensor = create_meshgrid(
- height, width, normalized_coordinates=normalized_coordinates)
-
- # initialice the warped destination grid
- 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.
-
- Useful when the same homography/homographies are reused.
-
- 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.
- """
- self._warped_grid = warp_grid(self.grid, src_homo_dst)
-
- def forward(
- self,
- patch_src: torch.Tensor,
- src_homo_dst: Optional[torch.Tensor] = None) -> torch.Tensor:
- r"""Warp a tensor from source into reference frame.
-
- Args:
- patch_src (torch.Tensor): The tensor to warp.
- src_homo_dst (torch.Tensor, optional): The homography or stack of
- homographies from destination to source. The homography assumes
- normalized coordinates [-1, 1] if normalized_coordinates is True.
- Default: None.
-
- Return:
- torch.Tensor: Patch sampled at locations from source to destination.
-
- Shape:
- - Input: :math:`(N, C, H, W)` and :math:`(N, 3, 3)`
- - Output: :math:`(N, C, H, W)`
-
- Example:
- >>> input = torch.rand(1, 3, 32, 32)
- >>> homography = torch.eye(3).view(1, 3, 3)
- >>> warper = HomographyWarper(32, 32)
- >>> # without precomputing the warp
- >>> output = warper(input, homography) # NxCxHxW
- >>> # precomputing the warp
- >>> warper.precompute_warp_grid(homography)
- >>> output = warper(input) # NxCxHxW
- """
- _warped_grid = self._warped_grid
- if src_homo_dst is not None:
- 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: {}. Whether \
- 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 preset using the method: \
- precompute_warp_grid().")
-
- return warped_patch
+ super(HomographyWarper, self).__init__(
+ height, width, mode, padding_mode, normalized_coordinates, align_corners)
+ warnings.warn(
+ "`HomographyWarper` is deprecated and will be removed > 0.6.0. "
+ "Please use `kornia.geometry.transform.HomographyWarper instead.`",
+ DeprecationWarning, stacklevel=2
+ )
def normal_transform_pixel(
height: int, width: int, eps: float = 1e-14,
device: Optional[torch.device] = None, dtype: Optional[torch.dtype] = None
) -> torch.Tensor:
- r"""Compute the normalization matrix from image size in pixels to [-1, 1].
-
- Args:
- height (int): image height.
- width (int): image width.
- eps (float): epsilon to prevent divide-by-zero errors
-
- Returns:
- torch.Tensor: normalized transform with shape :math:`(1, 3, 3)`.
- """
- tr_mat = torch.tensor([[1.0, 0.0, -1.0],
- [0.0, 1.0, -1.0],
- [0.0, 0.0, 1.0]], device=device, dtype=dtype) # 3x3
-
- # prevent divide by zero bugs
- width_denom: float = eps if width == 1 else width - 1.0
- height_denom: float = eps if height == 1 else height - 1.0
-
- tr_mat[0, 0] = tr_mat[0, 0] * 2.0 / width_denom
- tr_mat[1, 1] = tr_mat[1, 1] * 2.0 / height_denom
-
- return tr_mat.unsqueeze(0) # 1x3x3
+ __doc__ = HMW.normal_transform_pixel.__doc__
+ warnings.warn(
+ "`normal_transform_pixel` is deprecated and will be removed > 0.6.0."
+ "Please use `kornia.geometry.transform.normal_transform_pixel instead.`",
+ DeprecationWarning, stacklevel=2
+ )
+ return HMW.normal_transform_pixel(height, width, eps, device, dtype)
def normal_transform_pixel3d(
depth: int, height: int, width: int, eps: float = 1e-14,
device: Optional[torch.device] = None, dtype: Optional[torch.dtype] = None
) -> torch.Tensor:
- r"""Compute the normalization matrix from image size in pixels to [-1, 1].
-
- Args:
- depth (int): image depth.
- height (int): image height.
- width (int): image width.
- eps (float): epsilon to prevent divide-by-zero errors
-
- Returns:
- 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]], device=device, dtype=dtype) # 4x4
-
- # prevent divide by zero bugs
- width_denom: float = eps if width == 1 else width - 1.0
- height_denom: float = eps if height == 1 else height - 1.0
- depth_denom: float = eps if depth == 1 else depth - 1.0
-
- tr_mat[0, 0] = tr_mat[0, 0] * 2.0 / width_denom
- tr_mat[1, 1] = tr_mat[1, 1] * 2.0 / height_denom
- tr_mat[2, 2] = tr_mat[2, 2] * 2.0 / depth_denom
-
- return tr_mat.unsqueeze(0) # 1x4x4
+ __doc__ = HMW.normal_transform_pixel3d.__doc__
+ warnings.warn(
+ "`normal_transform_pixel3d` is deprecated and will be removed > 0.6.0. "
+ "Please use `kornia.geometry.transform.normal_transform_pixel3d instead.`",
+ DeprecationWarning, stacklevel=2
+ )
+ return HMW.normal_transform_pixel3d(height, width, eps, device, dtype)
def normalize_homography(dst_pix_trans_src_pix: torch.Tensor,
dsize_src: Tuple[int, int], dsize_dst: Tuple[int, int]) -> torch.Tensor:
- r"""Normalize a given homography in pixels to [-1, 1].
-
- Args:
- dst_pix_trans_src_pix (torch.Tensor): homography/ies from source to destination to be
- normalized. :math:`(B, 3, 3)`
- dsize_src (tuple): size of the source image (height, width).
- dsize_dst (tuple): size of the destination image (height, width).
-
- Returns:
- torch.Tensor: the normalized homography of shape :math:`(B, 3, 3)`.
- """
- 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 {}"
- .format(dst_pix_trans_src_pix.shape))
-
- # source and destination sizes
- src_h, src_w = dsize_src
- dst_h, dst_w = dsize_dst
-
- # compute the transformation pixel/norm for src/dst
- src_norm_trans_src_pix: torch.Tensor = normal_transform_pixel(
- 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(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)
+ __doc__ = HMW.normalize_homography.__doc__
+ warnings.warn(
+ "`normalize_homography` is deprecated and will be removed > 0.6.0. "
+ "Please use `kornia.geometry.transform.normalize_homography instead.`",
+ DeprecationWarning, stacklevel=2
)
- return dst_norm_trans_src_norm
+ return HMW.normalize_homography(dst_pix_trans_src_pix, dsize_src, dsize_dst)
def normalize_homography3d(dst_pix_trans_src_pix: torch.Tensor,
dsize_src: Tuple[int, int, int], dsize_dst: Tuple[int, int, int]) -> torch.Tensor:
- r"""Normalize a given homography in pixels to [-1, 1].
-
- Args:
- dst_pix_trans_src_pix (torch.Tensor): homography/ies from source to destination to be
- normalized. :math:`(B, 4, 4)`
- dsize_src (tuple): size of the source image (depth, height, width).
- dsize_src (tuple): size of the destination image (depth, height, width).
-
- Returns:
- Tensor: the normalized homography.
-
- Shape:
- Output: :math:`(B, 4, 4)`
- """
- 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:] == (4, 4)):
- raise ValueError("Input dst_pix_trans_src_pix must be a Bx3x3 tensor. Got {}"
- .format(dst_pix_trans_src_pix.shape))
-
- # source and destination sizes
- src_d, src_h, src_w = dsize_src
- dst_d, dst_h, dst_w = dsize_dst
- # compute the transformation pixel/norm for src/dst
- src_norm_trans_src_pix: torch.Tensor = normal_transform_pixel3d(
- 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_transform_pixel3d(
- dst_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)
+ __doc__ = HMW.normalize_homography3d.__doc__
+ warnings.warn(
+ "`normalize_homography3d` is deprecated and will be removed > 0.6.0. "
+ "Please use `kornia.geometry.transform.normalize_homography3d instead.`",
+ DeprecationWarning, stacklevel=2
)
- return dst_norm_trans_src_norm
+ return HMW.normalize_homography3d(dst_pix_trans_src_pix, dsize_src, dsize_dst)
diff --git a/test/geometry/warp/test_depth_warper.py b/test/geometry/test_depth_warper.py
similarity index 100%
rename from test/geometry/warp/test_depth_warper.py
rename to test/geometry/test_depth_warper.py
diff --git a/test/geometry/warp/test_homography_warper.py b/test/geometry/transform/test_homography_warper.py
similarity index 100%
rename from test/geometry/warp/test_homography_warper.py
rename to test/geometry/transform/test_homography_warper.py