π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
add weighted PnP (#3027)
Dmytro Mishkin1cc943d2ff04
diff --git a/kornia/geometry/calibration/pnp.py b/kornia/geometry/calibration/pnp.pyindex e3aebcd52..dd0d78f14 100644--- a/kornia/geometry/calibration/pnp.py+++ b/kornia/geometry/calibration/pnp.py@@ -4,11 +4,11 @@ import torchfrom torch.linalg import qr as linalg_qrfrom kornia.core import arange, ones_like, where, zeros-from kornia.geometry.conversions import convert_points_to_homogeneous+from kornia.geometry.conversions import convert_points_to_homogeneous, normalize_points_with_intrinsicsfrom kornia.geometry.linalg import transform_pointsfrom kornia.utils import eye_like-from kornia.utils.helpers import _torch_linalg_svdvals-from kornia.core.check import KORNIA_CHECK_SHAPE, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SAME_SHAPE+from kornia.utils.helpers import _torch_linalg_svdvals, _torch_svd_cast+from kornia.core.check import KORNIA_CHECK_SHAPE, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SAME_SHAPE, KORNIA_CHECKdef _mean_isotropic_scale_normalize(points: torch.Tensor, eps: float = 1e-8) -> Tuple[torch.Tensor, torch.Tensor]:@@ -45,7 +45,7 @@ def solve_pnp_dlt(img_points: torch.Tensor,intrinsics: torch.Tensor,weights: Optional[torch.Tensor] = None,- svd_eps: float = 1e-4,+ svd_eps: float = 1e-4) -> torch.Tensor:r"""This function attempts to solve the Perspective-n-Point (PnP) problem using Direct Linear Transform (DLT).@@ -74,8 +74,8 @@ def solve_pnp_dlt(the points in the image space.intrinsics : A tensor with shape :math:`(B, 3, 3)` representingthe intrinsic matrices.- weights : This parameter is not used currently and is just a- placeholder for API consistency.+ weights : A tensor with shape :math:`(B, N)` representing the+ weights for each point. If None, all points are considered to be equally important.svd_eps : A small float value to avoid numerical precision issues.Returns:@@ -123,46 +123,21 @@ def solve_pnp_dlt(# 3. http://rpg.ifi.uzh.ch/docs/teaching/2020/03_camera_calibration.pdf# 4. http://www.cs.cmu.edu/~16385/s17/Slides/11.3_Pose_Estimation.pdf# 5. https://www.ece.mcmaster.ca/~shirani/vision/hartley_ch7.pdf+ accepted_dtypes = (torch.float32, torch.float64)KORNIA_CHECK_IS_TENSOR(world_points)KORNIA_CHECK_IS_TENSOR(img_points)KORNIA_CHECK_IS_TENSOR(intrinsics)-- if (weights is not None) and (not isinstance(weights, torch.Tensor)):- raise AssertionError(- "If weights is not None, then weights should be an instance "- f"of torch.Tensor. Type of weights is {type(weights)}"- )-- if not isinstance(svd_eps, float):- raise AssertionError(f"Type of svd_eps is not float. Got {type(svd_eps)}")-- accepted_dtypes = (torch.float32, torch.float64)-- if world_points.dtype not in accepted_dtypes:- raise AssertionError(- f"world_points must have one of the following dtypes {accepted_dtypes}. "- f"Currently it has {world_points.dtype}."- )-- if img_points.dtype not in accepted_dtypes:- raise AssertionError(- f"img_points must have one of the following dtypes {accepted_dtypes}. Currently it has {img_points.dtype}."- )-- if intrinsics.dtype not in accepted_dtypes:- raise AssertionError(- f"intrinsics must have one of the following dtypes {accepted_dtypes}. Currently it has {intrinsics.dtype}."- )-+ KORNIA_CHECK(isinstance(svd_eps, float))+ KORNIA_CHECK(world_points.dtype in accepted_dtypes)+ KORNIA_CHECK(img_points.dtype in accepted_dtypes)+ KORNIA_CHECK(intrinsics.dtype in accepted_dtypes)KORNIA_CHECK_SHAPE(world_points, ["B", "N", "3"])KORNIA_CHECK_SHAPE(img_points, ["B", "N", "2"])KORNIA_CHECK_SHAPE(intrinsics, ["B", "3", "3"])KORNIA_CHECK_SAME_SHAPE(world_points[:,:, 0], img_points[:,:, 0])-- if world_points.shape[1] < 6:- raise AssertionError(- f"At least 6 points are required to use this function. Got {world_points.shape[1]} points."- )+ KORNIA_CHECK(world_points.shape[1] >= 6)+ if (weights is not None):+ KORNIA_CHECK_IS_TENSOR(weights)B, N = world_points.shape[:2]@@ -180,14 +155,10 @@ def solve_pnp_dlt("element of the batch) lie on a line or if all world_points (of any ""element of the batch) lie on a plane.")-- intrinsics_inv = torch.inverse(intrinsics)world_points_norm_h = convert_points_to_homogeneous(world_points_norm)- # Transforming img_points with intrinsics_inv to get img_points_inv- img_points_inv = transform_points(intrinsics_inv, img_points)-# Normalizing img_points_inv+ img_points_inv = normalize_points_with_intrinsics(img_points, intrinsics)img_points_norm, img_transform_norm = _mean_isotropic_scale_normalize(img_points_inv)inv_img_transform_norm = torch.inverse(img_transform_norm)@@ -198,8 +169,16 @@ def solve_pnp_dlt(system[:, 0::2, 8:12] = world_points_norm_h * (-1) * img_points_norm[..., 0:1]system[:, 1::2, 8:12] = world_points_norm_h * (-1) * img_points_norm[..., 1:2]+ # Apply weights to the system if provided+ if weights is not None:+ if weights.shape != (B, N):+ raise AssertionError(f"Weights should have shape (B, N). Got {weights.shape}.")+ weights_expanded = weights.unsqueeze(-1).repeat(1, 1, 2).view(B, 2 * N, 1)+ # Multiply the system matrix by the expanded weights+ system = weights_expanded * system+# Getting the solution vectors.- _, _, v = torch.svd(system)+ _, _, v = _torch_svd_cast(system)solution = v[..., -1]# Reshaping the solution vectors to the correct shape.diff --git a/tests/geometry/calibration/test_pnp.py b/tests/geometry/calibration/test_pnp.pyindex d677bb022..f785cf588 100644--- a/tests/geometry/calibration/test_pnp.py+++ b/tests/geometry/calibration/test_pnp.py@@ -99,16 +99,39 @@ class TestSolvePnpDlt(BaseTester):@pytest.mark.parametrize("num_points", (6,))def test_gradcheck(self, num_points, device):intrinsics, _, world_points, img_points = self._get_test_data(num_points, device, torch.float64)-self.gradcheck(kornia.geometry.solve_pnp_dlt, (world_points, img_points, intrinsics))+ @pytest.mark.parametrize("num_points", (8,))+ def test_gradcheck_weights(self, num_points, device):+ intrinsics, _, world_points, img_points = self._get_test_data(num_points, device, torch.float64)+ weights = torch.rand(*world_points.shape[:2], device=device, dtype=torch.float64).abs()+ self.gradcheck(kornia.geometry.solve_pnp_dlt, (world_points, img_points, intrinsics, weights))+@pytest.mark.parametrize("num_points", (6, 20))def test_pred_world_to_cam(self, num_points, device, dtype):intrinsics, gt_world_to_cam, world_points, img_points = self._get_test_data(num_points, device, dtype)-pred_world_to_cam = kornia.geometry.solve_pnp_dlt(world_points, img_points, intrinsics)self.assert_close(pred_world_to_cam, gt_world_to_cam, atol=1e-4, rtol=1e-4)+ @pytest.mark.parametrize("num_points", (16, 20))+ def test_pred_world_to_cam_weighted(self, num_points, device, dtype):+ intrinsics, gt_world_to_cam, world_points, img_points = self._get_test_data(num_points, device, dtype)+ weights = torch.ones(*world_points.shape[:2], device=device, dtype=dtype)+ pred_world_to_cam = kornia.geometry.solve_pnp_dlt(world_points, img_points, intrinsics, weights)+ self.assert_close(pred_world_to_cam, gt_world_to_cam, atol=1e-4, rtol=1e-4)++ @pytest.mark.parametrize("num_points", (25,))+ def test_pred_world_to_cam_weighted_rand(self, num_points, device, dtype):+ torch.manual_seed(0)+ intrinsics, gt_world_to_cam, world_points, img_points = self._get_test_data(num_points, device, dtype)+ weights = torch.ones(*world_points.shape[:2], device=device, dtype=dtype)+ weights[0, 0:2] = 1e-9+ world_points[0, 0:1] *= 0.1+ world_points[0, 1:2] += 100+ pred_world_to_cam = kornia.geometry.solve_pnp_dlt(world_points, img_points, intrinsics, weights)+ self.assert_close(pred_world_to_cam, gt_world_to_cam, atol=1e-4, rtol=1e-3)++@pytest.mark.parametrize("num_points", (6, 20))def test_project(self, num_points, device, dtype):intrinsics, _, world_points, img_points = self._get_test_data(num_points, device, dtype)