π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(geometry): use solve_pnp_dlt weights in the normalization and degeneracy check (#4829)
RitiGrover9f70c0c1a6aa
diff --git a/changelog.d/4829.breaking.md b/changelog.d/4829.breaking.mdnew file mode 100644index 000000000..96a14b2cb--- /dev/null+++ b/changelog.d/4829.breaking.md@@ -0,0 +1,9 @@+`solve_pnp_dlt` now applies `weights` to the point normalization and the degeneracy check as well as to the+linear system, so a zero weight is the same as removing the point. The weights used to scale only the rows of+the linear system: a zero-weight point still moved the normalization and counted in the degeneracy check, so+coplanar points plus zero-weight points off the plane passed the check and returned a wrong pose (#4799). That+input now raises the check's `AssertionError`, as do off-plane points whose weights are too small to lift the+weighted points off the plane (for example `1e-8`). Fewer than 6 nonzero weights in a batch element now raise+`BaseError`, as fewer than 6 points do; they used to return an arbitrary pose, or NaN for an all-zero row.+Non-uniform weights on noisy data now return a different pose. `weights=None` gives the same result as before,+uniform weights give it up to rounding, and only the weights' magnitudes relative to each other matter.diff --git a/kornia/geometry/calibration/pnp.py b/kornia/geometry/calibration/pnp.pyindex b05a935c5..fd637e3e0 100644--- a/kornia/geometry/calibration/pnp.py+++ b/kornia/geometry/calibration/pnp.py@@ -27,12 +27,16 @@ from kornia.geometry.conversions import convert_points_to_homogeneous, normalizefrom kornia.geometry.linalg import transform_points-def _mean_isotropic_scale_normalize(points: torch.Tensor, eps: float = 1e-8) -> Tuple[torch.Tensor, torch.Tensor]:+def _mean_isotropic_scale_normalize(+ points: torch.Tensor, eps: float = 1e-8, weights: Optional[torch.Tensor] = None+) -> Tuple[torch.Tensor, torch.Tensor]:r"""Normalize points.Args:points : torch.Tensor containing the points to be normalized with shape :math:`(B, N, D)`.eps : Small value to avoid division by zero error.+ weights : Optional non-negative per-point weights with shape :math:`(B, N)` for the mean and the scale.+ A point with weight zero does not affect the normalization.Returns:Tuple containing the normalized points in the shape :math:`(B, N, D)` and the transformation matrix@@ -40,8 +44,13 @@ def _mean_isotropic_scale_normalize(points: torch.Tensor, eps: float = 1e-8) ->"""KORNIA_CHECK_SHAPE(points, ["B", "N", "D"])- x_mean = torch.mean(points, dim=1, keepdim=True) # Bx1xD- scale = (points - x_mean).norm(dim=-1, p=2).mean(dim=-1) # B+ if weights is None:+ x_mean = torch.mean(points, dim=1, keepdim=True) # Bx1xD+ scale = (points - x_mean).norm(dim=-1, p=2).mean(dim=-1) # B+ else:+ w = weights / weights.sum(dim=1, keepdim=True) # BxN+ x_mean = (w[..., None] * points).sum(dim=1, keepdim=True) # Bx1xD+ scale = (w * (points - x_mean).norm(dim=-1, p=2)).sum(dim=-1) # BD_int = points.shape[-1]scale = (D_int**0.5) / (scale + eps) # B@@ -89,16 +98,12 @@ def solve_pnp_dlt(camera-to-world pose.- ``intrinsics`` is the :math:`(B, 3, 3)` ``K``; the :math:`(B, 4, 4)` matrix that a``PinholeCamera`` stores is rejected.- - ``weights`` scales the two rows each point contributes to the homogeneous linear system, so a uniform- ``weights`` leaves the answer unchanged up to rounding.- - fewer than 6 points, or a ``world_points``, ``img_points`` or ``intrinsics`` in a dtype other than- float32/float64, raise :class:`~kornia.core.exceptions.BaseError` naming the argument; a degenerate- ``world_points`` raises :class:`AssertionError` from the check above.-- .. warning::- A zero weight removes a point's rows but not the point: it still enters the normalization and the- degeneracy check, so coplanar points plus zero-weight points off the plane pass the check and return a- wrong pose: `#4799 <https://github.com/kornia/kornia/issues/4799>`_.+ - ``weights`` scales the two rows each point contributes to the homogeneous linear system, and the+ normalization and the degeneracy check use the same weighting. A uniform ``weights`` leaves the answer+ unchanged up to rounding, and a zero weight is the same as removing the point.+ - fewer than 6 points or 6 nonzero ``weights``, or a ``world_points``, ``img_points`` or ``intrinsics``+ in a dtype other than float32/float64, raise :class:`~kornia.core.exceptions.BaseError` naming the+ argument; a degenerate ``world_points`` raises :class:`AssertionError` from the check above.Args:world_points : A torch.Tensor with shape :math:`(B, N, 3)` representing@@ -180,13 +185,34 @@ def solve_pnp_dlt(B, N = world_points.shape[:2]+ # The weights scale each point's rows of the linear system, so the normalization and the+ # degeneracy check below use the same weighting: a point with weight zero drops out of all three.+ point_weights = None+ check_scale = None+ if weights is not None:+ if weights.shape != (B, N):+ raise AssertionError(f"Weights should have shape (B, N). Got {weights.shape}.")+ num_used = (weights != 0).sum(dim=1, keepdim=True)+ KORNIA_CHECK(+ bool((num_used >= 6).all()),+ "weights must hold at least 6 nonzero entries in every batch element, as world_points must hold 6 points.",+ )+ # Only the weights relative to the largest one matter below; dividing by it first keeps the squares+ # from overflowing or underflowing.+ rel_weights = weights / weights.abs().amax(dim=1, keepdim=True)+ point_weights = rel_weights**2+ # Rescale so that the squared weights sum to the number of nonzero-weight points: uniform weights+ # leave the check unchanged, and zero weights check the same as the remaining points alone.+ num_used = num_used.to(point_weights.dtype)+ check_scale = (rel_weights * torch.sqrt(num_used / point_weights.sum(dim=1, keepdim=True)))[..., None]+# Getting normalized world points.- world_points_norm, world_transform_norm = _mean_isotropic_scale_normalize(world_points)+ world_points_norm, world_transform_norm = _mean_isotropic_scale_normalize(world_points, weights=point_weights)# Checking if world_points_norm (of any element of the batch) has rank = 3. This# function cannot be used if all world points (of any element of the batch) lie# on a line or if all world points (of any element of the batch) lie on a plane.- s = _torch_linalg_svdvals(world_points_norm)+ s = _torch_linalg_svdvals(world_points_norm if check_scale is None else check_scale * world_points_norm)if torch.any(s[:, -1] < svd_eps):raise AssertionError("The last singular value of one/more of the elements of the batch is smaller "@@ -198,7 +224,7 @@ def solve_pnp_dlt(# Normalizing img_points_invimg_points_inv = normalize_points_with_intrinsics(img_points, intrinsics)- img_points_norm, img_transform_norm = _mean_isotropic_scale_normalize(img_points_inv)+ img_points_norm, img_transform_norm = _mean_isotropic_scale_normalize(img_points_inv, weights=point_weights)inv_img_transform_norm = torch.inverse(img_transform_norm)# Setting up the system (the matrix A in Ax=0)@@ -210,8 +236,6 @@ def solve_pnp_dlt(# Apply weights to the system if providedif 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 weightssystem = weights_expanded * systemdiff --git a/tests/geometry/calibration/test_pnp.py b/tests/geometry/calibration/test_pnp.pyindex 19c40461f..0a9455b1c 100644--- a/tests/geometry/calibration/test_pnp.py+++ b/tests/geometry/calibration/test_pnp.py@@ -246,10 +246,9 @@ class TestSolvePnpDlt(BaseTester):with pytest.raises(AssertionError, match="last singular value"):kornia.geometry.solve_pnp_dlt(planar, kornia.geometry.project_points(planar, K), K)- def test_wart_zero_weight_point_still_enters_the_degeneracy_check_4799(self, device, dtype):+ def test_zero_weight_points_do_not_pass_the_degeneracy_check(self, device, dtype):# kornia#4799: the same coplanar set plus two off-plane points recovers [I | 0]; with those two points at- # weight 0 it still passes the degeneracy check, which ignores the weights, and the rank-deficient system- # returns a wrong pose. A fix that checks the weighted points raises here instead.+ # weight 0 only the coplanar points are left, so the degeneracy check must reject it.if dtype not in (torch.float32, torch.float64):pytest.skip("solve_pnp_dlt accepts float32 and float64 only")world_points = self._convention_world_points(device, dtype)@@ -264,8 +263,121 @@ class TestSolvePnpDlt(BaseTester):pose = kornia.geometry.solve_pnp_dlt(points, img_points, K, weights=weights)assert pose[0, :, 3].abs().max() < 1e-2weights[0, -2:] = 0.0- pose = kornia.geometry.solve_pnp_dlt(points, img_points, K, weights=weights)- assert pose[0, :, 3].abs().max() > 1.0+ with pytest.raises(AssertionError, match="last singular value"):+ kornia.geometry.solve_pnp_dlt(points, img_points, K, weights=weights)++ def test_zero_weight_point_is_the_same_as_removing_it(self, device, dtype):+ # kornia#4799: a zero weight also kept the point in the normalization, so on noisy data the pose+ # differed from the solve without that point.+ if dtype not in (torch.float32, torch.float64):+ pytest.skip("solve_pnp_dlt accepts float32 and float64 only")+ torch.manual_seed(0)+ K = torch.tensor([[[500.0, 0.0, 320.0], [0.0, 500.0, 240.0], [0.0, 0.0, 1.0]]], device=device, dtype=dtype)+ points = torch.rand(1, 10, 3, device=device, dtype=dtype) * 4 - 2+ points[..., 2] += 10.0+ img_points = kornia.geometry.project_points(points, K)+ img_points = img_points + torch.randn_like(img_points)+ far_point = torch.tensor([[[30.0, -20.0, 60.0]]], device=device, dtype=dtype)+ far_img = torch.tensor([[[0.0, 0.0]]], device=device, dtype=dtype)+ weights = torch.ones(1, 11, device=device, dtype=dtype)+ weights[0, -1] = 0.0+ with_zero = kornia.geometry.solve_pnp_dlt(+ torch.cat([points, far_point], 1), torch.cat([img_points, far_img], 1), K, weights=weights+ )+ without = kornia.geometry.solve_pnp_dlt(points, img_points, K)+ self.assert_close(with_zero, without, rtol=1e-4, atol=1e-4)++ def test_weight_squared_is_the_point_multiplicity(self, device, dtype):+ # A weight scales the point's rows, so its square multiplies the point's residual: weight sqrt(2) is the+ # same as listing the point twice, also in the normalization. On noisy data this separates w**2 from w.+ if dtype not in (torch.float32, torch.float64):+ pytest.skip("solve_pnp_dlt accepts float32 and float64 only")+ torch.manual_seed(0)+ K = torch.tensor([[[500.0, 0.0, 320.0], [0.0, 500.0, 240.0], [0.0, 0.0, 1.0]]], device=device, dtype=dtype)+ points = torch.rand(1, 10, 3, device=device, dtype=dtype) * 4 - 2+ points[..., 2] += 10.0+ img_points = kornia.geometry.project_points(points, K)+ img_points = img_points + 3 * torch.randn_like(img_points)+ weights = torch.ones(1, 10, device=device, dtype=dtype)+ weights[0, 0] = 2.0**0.5+ weighted = kornia.geometry.solve_pnp_dlt(points, img_points, K, weights=weights)+ duplicated = kornia.geometry.solve_pnp_dlt(+ torch.cat([points, points[:, :1]], 1), torch.cat([img_points, img_points[:, :1]], 1), K+ )+ self.assert_close(weighted, duplicated, rtol=1e-4, atol=1e-4)++ def test_weights_scale_and_sign_do_not_change_the_result(self, device, dtype):+ # Only the weights' magnitudes relative to each other matter: a negative weight counts as its magnitude,+ # and scales whose squares overflow or underflow the dtype do not change the pose or the degeneracy+ # decision.+ if dtype not in (torch.float32, torch.float64):+ pytest.skip("solve_pnp_dlt accepts float32 and float64 only")+ torch.manual_seed(0)+ K = torch.tensor([[[500.0, 0.0, 320.0], [0.0, 500.0, 240.0], [0.0, 0.0, 1.0]]], device=device, dtype=dtype)+ points = torch.rand(2, 10, 3, device=device, dtype=dtype) * 4 - 2+ points[..., 2] += 10.0+ img_points = kornia.geometry.project_points(points, K[:, None])+ img_points = img_points + torch.randn_like(img_points)+ weights = torch.rand(2, 10, device=device, dtype=dtype) + 0.1+ weights[:, 0] = 0.0+ expected = kornia.geometry.solve_pnp_dlt(points, img_points, K.expand(2, 3, 3), weights=weights)+ for scale in (-1.0, 1e20, 1e-25) if dtype == torch.float32 else (-1.0, 1e160, 1e-170):+ scaled = kornia.geometry.solve_pnp_dlt(points, img_points, K.expand(2, 3, 3), weights=weights * scale)+ self.assert_close(scaled, expected, rtol=1e-4, atol=1e-4)++ def test_degeneracy_check_ignores_zero_weights_and_the_weight_scale(self, device, dtype):+ # The check sees the nonzero-weight points as if they were passed alone, with the squared weights+ # rescaled to sum to their count: the six points listed twice, the copies at half weight, have the last+ # singular value of the six listed twice (sqrt(2) times theirs), whatever the overall weight scale and+ # whatever the zero-weight points.+ if dtype not in (torch.float32, torch.float64):+ pytest.skip("solve_pnp_dlt accepts float32 and float64 only")+ world_points = self._convention_world_points(device, dtype)+ K = torch.tensor([[[100.0, 0.0, 4.0], [0.0, 100.0, 3.0], [0.0, 0.0, 1.0]]], device=device, dtype=dtype)+ last = 2.0**0.5 * torch.linalg.svdvals(_mean_isotropic_scale_normalize(world_points)[0])[0, -1].item()+ extra = world_points * torch.tensor([3.0, -2.0, 4.0], device=device, dtype=dtype)+ points = torch.cat([world_points, world_points, extra], 1)+ img_points = kornia.geometry.project_points(points, K)+ weights = torch.full((1, 18), 1e3, device=device, dtype=dtype)+ weights[0, 6:12] = 0.5e3+ weights[0, 12:] = 0.0+ kornia.geometry.solve_pnp_dlt(points, img_points, K, weights=weights, svd_eps=0.9 * last)+ with pytest.raises(AssertionError, match="last singular value"):+ kornia.geometry.solve_pnp_dlt(points, img_points, K, weights=weights, svd_eps=1.1 * last)++ def test_near_zero_weight_points_do_not_pass_the_degeneracy_check(self, device, dtype):+ # The check runs on the weighted points: off-plane points at weight 1e-8 leave the system as degenerate+ # as the coplanar points alone.+ if dtype not in (torch.float32, torch.float64):+ pytest.skip("solve_pnp_dlt accepts float32 and float64 only")+ world_points = self._convention_world_points(device, dtype)+ K = torch.tensor([[[100.0, 0.0, 4.0], [0.0, 100.0, 3.0], [0.0, 0.0, 1.0]]], device=device, dtype=dtype)+ planar = torch.stack(+ [world_points[0, :, 0], world_points[0, :, 1], torch.full_like(world_points[0, :, 0], 5.0)], -1+ )[None]+ off_plane = torch.tensor([[[0.0, 0.0, 8.0], [1.0, -1.0, 11.0]]], device=device, dtype=dtype)+ points = torch.cat([planar, off_plane], 1)+ weights = torch.ones(1, 8, device=device, dtype=dtype)+ weights[0, -2:] = 1e-8+ with pytest.raises(AssertionError, match="last singular value"):+ kornia.geometry.solve_pnp_dlt(points, kornia.geometry.project_points(points, K), K, weights=weights)++ def test_fewer_than_six_nonzero_weights_raise(self, device, dtype):+ # A zero weight removes the point, so fewer than 6 nonzero weights is rejected like fewer than 6 points.+ if dtype not in (torch.float32, torch.float64):+ pytest.skip("solve_pnp_dlt accepts float32 and float64 only")+ world_points = self._convention_world_points(device, dtype)+ points = torch.cat([world_points, world_points + 1.0], 1).repeat(2, 1, 1)+ K = torch.tensor([[[100.0, 0.0, 4.0], [0.0, 100.0, 3.0], [0.0, 0.0, 1.0]]], device=device, dtype=dtype)+ K = K.expand(2, 3, 3)+ img_points = kornia.geometry.project_points(points, K[:, None])+ weights = torch.ones(2, 12, device=device, dtype=dtype)+ weights[1, 5:] = 0.0+ with pytest.raises(BaseError, match="at least 6 nonzero"):+ kornia.geometry.solve_pnp_dlt(points, img_points, K, weights=weights)+ weights[1] = 0.0+ with pytest.raises(BaseError, match="at least 6 nonzero"):+ kornia.geometry.solve_pnp_dlt(points, img_points, K, weights=weights)class TestNormalization(BaseTester):