π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
move and rename functions to normalize homographies. Added test for them.
Luis Ferraz1281a56f9250
diff --git a/kornia/geometry/transform/imgwarp.py b/kornia/geometry/transform/imgwarp.pyindex 9de75a2cb..12fc0535c 100644--- a/kornia/geometry/transform/imgwarp.py+++ b/kornia/geometry/transform/imgwarp.py@@ -4,7 +4,7 @@ import torchimport torch.nn.functional as Fimport kornia-from kornia.geometry.warp.homography_warper import homography_warp+import kornia.geometry.warp.homography_warper as warper# TODO: move to utils or conversionsfrom kornia.geometry.conversions import (deg2rad, normalize_pixel_coordinates, convert_affinematrix_to_homography@@ -15,80 +15,22 @@ __all__ = ["warp_affine","get_perspective_transform","get_rotation_matrix2d",- "normal_transform_pixel","remap","invert_affine_transform","angle_to_rotation_matrix"]-def normal_transform_pixel(height, width):-- tr_mat = torch.Tensor([[1.0, 0.0, -1.0],- [0.0, 1.0, -1.0],- [0.0, 0.0, 1.0]]) # 1x3x3-- 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 = tr_mat.unsqueeze(0)-- return tr_mat---def src_norm_to_dst_norm(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 from source to destiantion to be- normalized. :math:`(B, 3, 3)`- dsize_src (tuple): size of the source image (height, width).- dsize_src (tuple): size of the destination image (height, width).-- Returns:- Tensor: the normalized homography.-- 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)))-- 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- # 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_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)- # 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 transform_warp_impl(src: torch.Tensor, dst_pix_trans_src_pix: torch.Tensor,dsize_src: Tuple[int, int], dsize_dst: Tuple[int, int],grid_mode: str, padding_mode: str) -> torch.Tensor:"""Compute the transform in normalized cooridnates and perform the warping."""- dst_norm_trans_src_norm: torch.Tensor = src_norm_to_dst_norm(+ dst_norm_trans_src_norm: torch.Tensor = warper.normalize_homography(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)+ return warper.homography_warp(src, src_norm_trans_dst_norm, dsize_dst, grid_mode, padding_mode)def warp_perspective(src: torch.Tensor, M: torch.Tensor, dsize: Tuple[int, int],@@ -196,7 +138,7 @@ def warp_affine(src: torch.Tensor, M: torch.Tensor,out_size = dsize# we generate a 3x3 transformation matrix from 2x3 affineM_3x3: torch.Tensor = convert_affinematrix_to_homography(M)- dst_norm_trans_src_norm: torch.Tensor = src_norm_to_dst_norm(+ dst_norm_trans_src_norm: torch.Tensor = warper.normalize_homography(M_3x3, dsize_src, out_size)src_norm_trans_dst_norm = torch.inverse(dst_norm_trans_src_norm)grid = F.affine_grid(src_norm_trans_dst_norm[:, :2, :], # type: ignore@@ -314,8 +256,7 @@ def get_perspective_transform(src, dst):def angle_to_rotation_matrix(angle: torch.Tensor) -> torch.Tensor:- """- Creates a rotation matrix out of angles in degrees+ r"""Create a rotation matrix out of angles in degrees.Args:angle: (torch.Tensor): tensor of angles in degrees, any shape.diff --git a/kornia/geometry/warp/homography_warper.py b/kornia/geometry/warp/homography_warper.pyindex 5fd3e8997..5cfae7e87 100644--- a/kornia/geometry/warp/homography_warper.py+++ b/kornia/geometry/warp/homography_warper.py@@ -11,11 +11,12 @@ from kornia.geometry.linalg import transform_points__all__ = ["HomographyWarper","homography_warp",+ "normalize_homography",+ "normal_transform_pixel",]# layer api-class HomographyWarper(nn.Module):r"""Warp tensors by homographies.@@ -64,6 +65,8 @@ class HomographyWarper(nn.Module):src_homo_dst (torch.Tensor): Homography or homographies (stacked) totransform all points in the grid. Shape of the homographyhas 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 = self.warp_grid(src_homo_dst)@@ -74,11 +77,12 @@ class HomographyWarper(nn.Module):src_homo_dst (torch.Tensor): Homography or homographies (stacked) totransform all points in the grid. Shape of the homographyhas 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.devicedtype: torch.dtype = src_homo_dst.dtype@@ -102,7 +106,8 @@ class HomographyWarper(nn.Module):patch_src (torch.Tensor): The tensor to warp.src_homo_dst (torch.Tensor, optional): The homography or stack ofhomographies from destination to source. The homography assumes- normalized coordinates [-1, 1]. Default: None.+ normalized coordinates [-1, 1] if normalized_coordinates is True.+ Default: None.Return:torch.Tensor: Patch sampled at locations from source to destination.@@ -147,8 +152,6 @@ class HomographyWarper(nn.Module):# functional api--def homography_warp(patch_src: torch.Tensor,src_homo_dst: torch.Tensor,dsize: Tuple[int, int],@@ -163,7 +166,8 @@ def homography_warp(patch_src: torch.Tensor,source of shape :math:`(N, C, H, W)`.src_homo_dst (torch.Tensor): The homography or stack of homographiesfrom destination to source of shape- :math:`(N, 3, 3)`.+ :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'.@@ -181,3 +185,70 @@ def homography_warp(patch_src: torch.Tensor,height, width = dsizewarper = HomographyWarper(height, width, mode, padding_mode)return warper(patch_src, src_homo_dst)+++def normal_transform_pixel(height: int, width: int) -> torch.Tensor:+ r"""Compute the normalization matrix from image size in pixels to [-1, 1].++ Args:+ height (int): image height.+ width (int): image width.++ Returns:+ Tensor: normalized transform.++ Shape:+ Output: :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]]) # 3x3++ 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 = tr_mat.unsqueeze(0) # 1x3x3+ return tr_mat+++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 destiantion to be+ normalized. :math:`(B, 3, 3)`+ dsize_src (tuple): size of the source image (height, width).+ dsize_src (tuple): size of the destination image (height, width).++ Returns:+ Tensor: the normalized homography.++ 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)))++ 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+ # 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_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)+ # 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_normdiff --git a/test/geometry/warp/test_homography_warper.py b/test/geometry/warp/test_homography_warper.pyindex b33a1c87f..8bc179d71 100644--- a/test/geometry/warp/test_homography_warper.py+++ b/test/geometry/warp/test_homography_warper.py@@ -27,14 +27,58 @@ class TestHomographyWarper:patch_dst = warper(patch_src, dst_homo_src)assert_allclose(patch_src, patch_dst)+ @pytest.mark.parametrize("batch_size", [1, 3])+ def test_normalize_homography_identity(self, batch_size, device):+ # create input data+ height, width = 2, 5+ dst_homo_src = utils.create_eye_batch(batch_size=batch_size, eye_size=3).to(device)++ res = torch.tensor([[[0.5, 0.0, -1.0],+ [0.0, 2.0, -1.0],+ [0.0, 0.0, 1.0]]])+ assert (kornia.normal_transform_pixel(height, width) == res).all()++ norm_homo = kornia.normalize_homography(dst_homo_src, (height, width), (height, width))+ assert (norm_homo == dst_homo_src).all()++ norm_homo = kornia.normalize_homography(dst_homo_src,+ (height, width),+ (height, width))+ assert (norm_homo == dst_homo_src).all()++ # change output scale+ norm_homo = kornia.normalize_homography(dst_homo_src,+ (height, width),+ (height * 2, width // 2))+ res = torch.tensor([[[4.0, 0.0, 3.0],+ [0.0, 1 / 3, -2 / 3],+ [0.0, 0.0, 1.0]]]).to(device)+ assert_allclose(norm_homo, res)++ @pytest.mark.parametrize("batch_size", [1, 3])+ def test_normalize_homography_general(self, batch_size, device):+ # create input data+ height, width = 2, 5+ dst_homo_src = torch.eye(3).to(device)+ dst_homo_src[..., 0, 0] = 0.5+ dst_homo_src[..., 1, 1] = 2.0+ dst_homo_src[..., 0, 2] = 1.0+ dst_homo_src[..., 1, 2] = 2.0+ dst_homo_src = dst_homo_src.expand(batch_size, -1, -1)++ norm_homo = kornia.normalize_homography(dst_homo_src, (height, width), (height, width))+ res = torch.tensor([[[0.5, 0.0, 0.0],+ [0.0, 2.0, 5.0],+ [0.0, 0.0, 1.0]]]).to(device)+ assert (norm_homo == res).all()+@pytest.mark.parametrize("offset", [1, 3, 7])@pytest.mark.parametrize("shape", [(4, 5), (2, 6), (4, 3), (5, 7), ])- def test_warp_grid_translation(self, shape, offset):+ def test_warp_grid_translation(self, shape, offset, device):# create input dataheight, width = shape- patch_src = torch.rand(1, 1, height, width)- dst_homo_src = utils.create_eye_batch(batch_size=1, eye_size=3)+ 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@@ -45,9 +89,9 @@ class TestHomographyWarper:# 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] + offset, flow[..., 0])+ warper.grid[..., 0].to(device) + offset, flow[..., 0])assert_allclose(- warper.grid[..., 1], flow[..., 1])+ warper.grid[..., 1].to(device), flow[..., 1])@pytest.mark.parametrize("batch_shape", [(1, 1, 4, 5), (2, 2, 4, 6), (3, 1, 5, 7), ])@@ -142,6 +186,11 @@ class TestHomographyWarper:patch_dst = warper(patch_src, dst_homo_src_i)patch_dst_to_src = warper(patch_dst, torch.inverse(dst_homo_src_i))+ # same transform precomputing the grid+ warper.precompute_warp_grid(torch.inverse(dst_homo_src_i))+ patch_dst_to_src_precomputed = warper(patch_dst)+ assert (patch_dst_to_src_precomputed == patch_dst_to_src).all()+# projected should be equal as initialerror = utils.compute_patch_error(patch_dst, patch_dst_to_src, height, width)