π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
Laf reprojection (#343)
Dmytro Mishkin0e1f9d267cb1
diff --git a/kornia/feature/__init__.py b/kornia/feature/__init__.pyindex c29f309fc..10c52537e 100644--- a/kornia/feature/__init__.py+++ b/kornia/feature/__init__.py@@ -18,7 +18,9 @@ from .laf import (extract_patches_from_pyramid,get_laf_orientation,raise_error_if_laf_is_not_valid,laf_from_center_scale_ori,- laf_is_inside_image)+ laf_is_inside_image,+ laf_to_three_points,+ laf_from_three_points)from .siftdesc import SIFTDescriptorfrom .scale_space_detector import ScaleSpaceDetector, PassLAFfrom .affine_shape import LAFAffineShapeEstimator, PatchAffineShapeEstimator@@ -54,4 +56,6 @@ __all__ = ["raise_error_if_laf_is_not_valid","laf_is_inside_image","laf_from_center_scale_ori",+ "laf_to_three_points",+ "laf_from_three_points",]diff --git a/kornia/feature/laf.py b/kornia/feature/laf.pyindex 9a8084c39..cdef371a1 100644--- a/kornia/feature/laf.py+++ b/kornia/feature/laf.py@@ -478,3 +478,36 @@ def laf_is_inside_image(laf: torch.Tensor, images: torch.Tensor) -> torch.Tensorgood_lafs_mask: torch.Tensor = (pts[..., 0] >= 0) * (pts[..., 0] <= w) * (pts[..., 1] >= 0) * (pts[..., 1] <= h)good_lafs_mask = good_lafs_mask.min(dim=2)[0]return good_lafs_mask+++def laf_to_three_points(laf: torch.Tensor):+ """Converts local affine frame(LAF) to alternative representation: coordinates of+ LAF center, LAF-x unit vector, LAF-y unit vector.++ Args:+ laf (torch.Tensor): :math:`(B, N, 2, 3)`++ Returns:+ threepts (torch.Tensor): :math:`(B, N, 2, 3)`+ """+ raise_error_if_laf_is_not_valid(laf)+ three_pts: torch.Tensor = torch.stack([laf[..., 2] + laf[..., 0],+ laf[..., 2] + laf[..., 1],+ laf[..., 2]], dim=-1)+ return three_pts+++def laf_from_three_points(threepts: torch.Tensor):+ """Converts three points to local affine frame.+ Order is (0,0), (0, 1), (1, 0).++ Args:+ threepts (torch.Tensor): :math:`(B, N, 2, 3)`++ Returns:+ laf (torch.Tensor): :math:`(B, N, 2, 3)`+ """+ laf: torch.Tensor = torch.stack([threepts[..., 0] - threepts[..., 2],+ threepts[..., 1] - threepts[..., 2],+ threepts[..., 2]], dim=-1)+ return lafdiff --git a/kornia/feature/siftdesc.py b/kornia/feature/siftdesc.pyindex 651c3b75e..f87668758 100644--- a/kornia/feature/siftdesc.py+++ b/kornia/feature/siftdesc.py@@ -5,7 +5,7 @@ import torch.nn as nnimport torch.nn.functional as Ffrom kornia.filters import get_gaussian_kernel2dfrom kornia.filters import spatial_gradient-from kornia.geometry import pi+from kornia.geometry.conversions import pidef get_sift_pooling_kernel(ksize: int = 25) -> torch.Tensor:diff --git a/kornia/geometry/linalg.py b/kornia/geometry/linalg.pyindex 3b5ca432b..0e10f36e4 100644--- a/kornia/geometry/linalg.py+++ b/kornia/geometry/linalg.py@@ -1,8 +1,7 @@from typing import Optionalimport torch-import torch.nn as nn-+import korniafrom kornia.geometry.conversions import convert_points_to_homogeneousfrom kornia.geometry.conversions import convert_points_from_homogeneous@@ -12,6 +11,7 @@ __all__ = ["relative_transformation","inverse_transformation","transform_points",+ "perspective_transform_lafs",]@@ -212,6 +212,48 @@ def transform_points(trans_01: torch.Tensor,points_0 = convert_points_from_homogeneous(points_0_h) # BxNxDreturn points_0++def perspective_transform_lafs(trans_01: torch.Tensor,+ lafs_1: torch.Tensor) -> torch.Tensor:+ r"""Function that applies perspective transformations to a set of local affine frames (LAFs).++ Args:+ trans_01 (torch.Tensor): tensor for perspective transformations of shape+ :math:`(B, 3, 3)`.+ lafs_1 (torch.Tensor): tensor of lafs of shape :math:`(B, N, 2, 3)`.+ Returns:+ torch.Tensor: tensor of N-dimensional points.++ Shape:+ - Output: :math:`(B, N, 2, 3)`++ Examples:++ >>> lafs_1 = torch.rand(2, 4, 2, 3) # BxNx2x3+ >>> trans_01 = torch.eye(3).view(1, 3, 3) # Bx3x3+ >>> lafs_0 = kornia.perspective_transform_lafs(trans_01, lafs_1) # BxNx2x3+ """+ kornia.feature.laf.raise_error_if_laf_is_not_valid(lafs_1)+ if not torch.is_tensor(trans_01):+ raise TypeError("Input type is not a torch.Tensor")+ if not trans_01.device == lafs_1.device:+ raise TypeError("Tensor must be in the same device")+ if not trans_01.shape[0] == lafs_1.shape[0]:+ raise ValueError("Input batch size must be the same for both tensors")+ if (not (trans_01.shape[-1] == 3)) or (not (trans_01.shape[-2] == 3)):+ raise ValueError("Tranformation should be homography")+ bs, n, _, _ = lafs_1.size()+ # First, we convert LAF to points+ threepts_1 = kornia.feature.laf.laf_to_three_points(lafs_1)+ points_1 = threepts_1.permute(0, 1, 3, 2).reshape(bs, n * 3, 2)++ # First, transform the points+ points_0 = transform_points(trans_01, points_1)+ # Back to LAF format+ threepts_0 = points_0.view(bs, n, 3, 2).permute(0, 1, 3, 2)+ return kornia.feature.laf.laf_from_three_points(threepts_0)++# TODO:# - project_points: from opencvdiff --git a/test/feature/test_laf.py b/test/feature/test_laf.pyindex 09ee3d859..d535f59b3 100644--- a/test/feature/test_laf.py+++ b/test/feature/test_laf.py@@ -388,3 +388,62 @@ class TestGetCreateLAF:assert gradcheck(kornia.feature.laf_from_center_scale_ori,(xy, scale, ori,),raise_exception=True)+++class TestGetLAF3pts:+ def test_shape(self):+ inp = torch.ones(1, 3, 2, 3)+ out = kornia.feature.laf_to_three_points(inp)+ assert out.shape == inp.shape++ def test_batch_shape(self):+ inp = torch.ones(5, 3, 2, 3)+ out = kornia.feature.laf_to_three_points(inp)+ assert out.shape == inp.shape++ def test_conversion(self):+ inp = torch.tensor([[1, 0, 2], [0, 1, 3]]).float().view(1, 1, 2, 3)+ expected = torch.tensor([[3, 2, 2], [3, 4, 3]]).float().view(1, 1, 2, 3)+ threepts = kornia.feature.laf_to_three_points(inp)+ assert_allclose(threepts, expected)++ def test_gradcheck(self):+ batch_size, channels, height, width = 3, 2, 2, 3+ inp = torch.rand(batch_size, channels, height, width)+ inp = utils.tensor_to_gradcheck_var(inp) # to var+ assert gradcheck(kornia.feature.laf_to_three_points,+ (inp,),+ raise_exception=True)+++class TestGetLAFFrom3pts:+ def test_shape(self):+ inp = torch.ones(1, 3, 2, 3)+ out = kornia.feature.laf_from_three_points(inp)+ assert out.shape == inp.shape++ def test_batch_shape(self):+ inp = torch.ones(5, 3, 2, 3)+ out = kornia.feature.laf_from_three_points(inp)+ assert out.shape == inp.shape++ def test_conversion(self):+ expected = torch.tensor([[1, 0, 2], [0, 1, 3]]).float().view(1, 1, 2, 3)+ inp = torch.tensor([[3, 2, 2], [3, 4, 3]]).float().view(1, 1, 2, 3)+ threepts = kornia.feature.laf_from_three_points(inp)+ assert_allclose(threepts, expected)++ def test_cross_consistency(self):+ batch_size, channels, height, width = 3, 2, 2, 3+ inp = torch.rand(batch_size, channels, height, width)+ inp_2 = kornia.feature.laf_from_three_points(inp)+ inp_2 = kornia.feature.laf_to_three_points(inp_2)+ assert_allclose(inp_2, inp)++ def test_gradcheck(self):+ batch_size, channels, height, width = 3, 2, 2, 3+ inp = torch.rand(batch_size, channels, height, width)+ inp = utils.tensor_to_gradcheck_var(inp) # to var+ assert gradcheck(kornia.feature.laf_from_three_points,+ (inp,),+ raise_exception=True)diff --git a/test/geometry/test_linalg.py b/test/geometry/test_linalg.pyindex c3502ac24..caefdfec5 100644--- a/test/geometry/test_linalg.py+++ b/test/geometry/test_linalg.py@@ -222,3 +222,41 @@ class TestRelativeTransformation:trans_02 = utils.tensor_to_gradcheck_var(trans_02) # to varassert gradcheck(kornia.relative_transformation, (trans_01, trans_02,),raise_exception=True)+++class TestTransformLAFs:++ @pytest.mark.parametrize("device_type", TEST_DEVICES)+ @pytest.mark.parametrize("batch_size", [1, 2, 5])+ @pytest.mark.parametrize("num_points", [2, 3, 5])+ def test_transform_points(+ self, batch_size, num_points, device_type):+ # generate input data+ eye_size = 3+ lafs_src = torch.rand(batch_size, num_points, 2, 3)+ lafs_src = lafs_src.to(torch.device(device_type))++ dst_homo_src = utils.create_random_homography(batch_size, eye_size)+ dst_homo_src = dst_homo_src.to(torch.device(device_type))++ # transform the points from dst to ref+ lafs_dst = kornia.perspective_transform_lafs(dst_homo_src, lafs_src)++ # transform the points from ref to dst+ src_homo_dst = torch.inverse(dst_homo_src)+ lafs_dst_to_src = kornia.perspective_transform_lafs(src_homo_dst, lafs_dst)++ # projected should be equal as initial+ assert_allclose(lafs_src, lafs_dst_to_src)++ def test_gradcheck(self):+ # generate input data+ batch_size, num_points, num_dims = 2, 3, 2+ eye_size = 3+ points_src = torch.rand(batch_size, num_points, 2, 3)+ dst_homo_src = utils.create_random_homography(batch_size, eye_size)+ # evaluate function gradient+ points_src = utils.tensor_to_gradcheck_var(points_src) # to var+ dst_homo_src = utils.tensor_to_gradcheck_var(dst_homo_src) # to var+ assert gradcheck(kornia.perspective_transform_lafs, (dst_homo_src, points_src,),+ raise_exception=True)