π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
add test and improve docs for warp_affine
edgarribad8957f12eed1
diff --git a/docs/source/geometric.rst b/docs/source/geometric.rstindex 85680f62d..65de210e2 100644--- a/docs/source/geometric.rst+++ b/docs/source/geometric.rst@@ -1,5 +1,5 @@-Geometric Image Transformations--------------------------------+Image Transformations+---------------------.. currentmodule:: torchgeometrydiff --git a/test/test_imgwarp.py b/test/test_imgwarp.pyindex ef15bdf9a..315acd328 100644--- a/test/test_imgwarp.py+++ b/test/test_imgwarp.py@@ -200,3 +200,33 @@ def test_warp_perspective_crop(batch_size, device_type, channels):patch_warped = tgm.warp_perspective(patch, dst_pix_trans_src_pix, (dst_h, dst_w))assert patch_warped.shape == (batch_size, channels, dst_h, dst_w)+++class TestWarpAffine:+ def test_smoke(self):+ batch_size, channels, height, width = 1, 2, 3, 4+ aff_ab = torch.eye(2, 3)[None] # 1x2x3+ img_b = torch.rand(batch_size, channels, height, width)+ img_a = tgm.warp_affine(img_b, aff_ab, (height, width))+ assert img_b.shape == img_a.shape++ @pytest.mark.parametrize("batch_size", [1, 2, 5])+ def test_translation(self, batch_size):+ offset = 1.+ channels, height, width = 1, 3, 4+ aff_ab = torch.eye(2, 3).repeat(batch_size, 1, 1) # Bx2x3+ aff_ab[..., -1] += offset+ img_b = torch.arange(float(height * width)).view(+ 1, channels, height, width).repeat(batch_size, 1, 1, 1)+ img_a = tgm.warp_affine(img_b, aff_ab, (height, width))+ assert utils.check_equal_torch(img_b[..., :2, :3], img_a[..., 1:, 1:])++ def test_gradcheck(self):+ batch_size, channels, height, width = 1, 2, 3, 4+ aff_ab = torch.eye(2, 3)[None] # 1x2x3+ img_b = torch.rand(batch_size, channels, height, width)+ aff_ab = utils.tensor_to_gradcheck_var(+ aff_ab, requires_grad=False) # to var+ img_b = utils.tensor_to_gradcheck_var(img_b) # to var+ assert gradcheck(tgm.warp_affine, (img_b, aff_ab, (height, width),),+ raise_exception=True)diff --git a/torchgeometry/core/homography_warper.py b/torchgeometry/core/homography_warper.pyindex 1a886fb7e..7b256e708 100644--- a/torchgeometry/core/homography_warper.py+++ b/torchgeometry/core/homography_warper.py@@ -26,9 +26,10 @@ class HomographyWarper(nn.Module):Args:height (int): The height of the image to warp.width (int): The width of the image to warp.- padding_mode (str): Either 'zeros' to replace out of bounds with- zeros or 'border' to choose the closest- border data.+ mode (Optional[str]): interpolation mode to calculate output values+ 'bilinear' | 'nearest'. Default: 'bilinear'.+ padding_mode (Optional[str]): padding mode for outside grid values+ 'zeros' | 'border' | 'reflection'. Default: 'zeros'.normalized_coordinates (Optional[bool]): wether to use a grid withnormalized coordinates."""@@ -37,11 +38,13 @@ class HomographyWarper(nn.Module):self,height: int,width: int,+ mode: Optional[str] = 'bilinear',padding_mode: Optional[str] = 'zeros',normalized_coordinates: Optional[bool] = True) -> None:super(HomographyWarper, self).__init__()self.width: int = widthself.height: int = height+ self.mode: Optional[str] = modeself.padding_mode: Optional[str] = padding_modeself.normalized_coordinates: Optional[bool] = normalized_coordinates@@ -103,19 +106,18 @@ class HomographyWarper(nn.Module):raise TypeError("Patch and homography must be on the same device. \Got patch.device: {} dst_H_src.device: {}.".format(patch_src.device, dst_homo_src.device))- return torch.nn.functional.grid_sample(- patch_src, self.warp_grid(dst_homo_src), mode='bilinear',- padding_mode=self.padding_mode)+ return F.grid_sample(patch_src, self.warp_grid(dst_homo_src),+ mode=self.mode, padding_mode=self.padding_mode)# functional apidef homography_warp(patch_src: torch.Tensor,- dst_H_src: torch.Tensor,- dsize: Tuple[int,- int],- padding_mode: Optional[str] = 'zeros'):+ dst_homo_src: torch.Tensor,+ dsize: Tuple[int, int],+ mode: Optional[str] = 'bilinear',+ padding_mode: Optional[str] = 'zeros') -> torch.Tensor:r"""Function that warps image patchs or tensors by homographies.See :class:`~torchgeometry.HomographyWarper` for details.@@ -127,9 +129,10 @@ def homography_warp(patch_src: torch.Tensor,from source to destination of shape:math:`(N, 3, 3)`.dsize (Tuple[int, int]): The height and width of the image to warp.- padding_mode (Optional[string]): Either 'zeros' to replace out of- bounds with zeros or 'border' to- choose the closest border data.+ mode (Optional[str]): interpolation mode to calculate output values+ 'bilinear' | 'nearest'. Default: 'bilinear'.+ padding_mode (Optional[str]): padding mode for outside grid values+ 'zeros' | 'border' | 'reflection'. Default: 'zeros'.Return:torch.Tensor: Patch sampled at locations from source to destination.@@ -140,5 +143,5 @@ def homography_warp(patch_src: torch.Tensor,>>> output = tgm.homography_warp(input, homography, (32, 32)) # NxCxHxW"""height, width = dsize- warper = HomographyWarper(height, width, padding_mode)- return warper(patch_src, dst_H_src)+ warper = HomographyWarper(height, width, mode, padding_mode)+ return warper(patch_src, dst_homo_src)diff --git a/torchgeometry/core/imgwarp.py b/torchgeometry/core/imgwarp.pyindex 57a5e66ed..b2a34e88e 100644--- a/torchgeometry/core/imgwarp.py+++ b/torchgeometry/core/imgwarp.py@@ -1,8 +1,10 @@+from typing import Tuple, Optional+import torchimport torch.nn.functional as F-from .homography_warper import homography_warp-from .conversions import deg2rad+from torchgeometry.core.conversions import deg2rad+from torchgeometry.core.homography_warper import homography_warp__all__ = [@@ -102,11 +104,15 @@ def warp_perspective(src, M, dsize, flags='bilinear', border_mode=None,return transform_warp_impl(src, M, (src.shape[-2:]), dsize)-def warp_affine(src, M, dsize, flags='bilinear', border_mode=None,- border_value=0):- r"""Applies an affine transformation to an image.+def warp_affine(src: torch.Tensor,+ M: torch.Tensor,+ dsize: Tuple[int,+ int],+ flags: Optional[str] = 'bilinear',+ padding_mode: Optional[str] = 'zeros') -> torch.Tensor:+ r"""Applies an affine transformation to a tensor.- The function warp_affine transforms the source image using+ The function warp_affine transforms the source tensor usingthe specified matrix:.. math::@@ -114,20 +120,23 @@ def warp_affine(src, M, dsize, flags='bilinear', border_mode=None,M_{21} x + M_{22} y + M_{23} \right )Args:- src (Tensor): input image.- M (Tensor): transformation matrix.- dsize (tuple): size of the output image (height, width).+ src (torch.Tensor): input tensor of shape :math:`(B, C, H, W)`.+ M (torch.Tensor): affine transformation of shape :math:`(B, 2, 3)`.+ dsize (Tuple[int, int]): size of the output image (height, width).+ mode (Optional[str]): interpolation mode to calculate output values+ 'bilinear' | 'nearest'. Default: 'bilinear'.+ padding_mode (Optional[str]): padding mode for outside grid values+ 'zeros' | 'border' | 'reflection'. Default: 'zeros'.Returns:- Tensor: the warped input image.+ torch.Tensor: the warped tensor.Shape:- - Input: :math:`(B, C, H, W)` and :math:`(B, 2, 3)`- Output: :math:`(B, C, H, W)`.. note::- See a working example `here <https://github.com/arraiy/torchgeometry/- blob/master/examples/warp_affine.ipynb>`__.+ See a working example `here <https://github.com/arraiyopensource/+ torchgeometry/blob/master/docs/source/warp_affine.ipynb>`__."""if not torch.is_tensor(src):raise TypeError("Input src type is not a torch.Tensor. Got {}"@@ -142,7 +151,8 @@ def warp_affine(src, M, dsize, flags='bilinear', border_mode=None,raise ValueError("Input M must be a Bx2x3 tensor. Got {}".format(src.shape))# we generate a 3x3 transformation matrix from 2x3 affine- M_3x3 = F.pad(M, (0, 0, 0, 1, 0, 0))+ M_3x3: torch.Tensor = F.pad(M, (0, 0, 0, 1, 0, 0),+ mode="constant", value=0)M_3x3[:, 2, 2] += 1.0# launches the warper