π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(calibration): preserve sensor tilt gradients at zero (#5668)
Devulapalli Naga Sri Vaishnavib2e340fc0419
diff --git a/changelog.d/5668.fixed.md b/changelog.d/5668.fixed.mdnew file mode 100644index 000000000..1d0d305f7--- /dev/null+++ b/changelog.d/5668.fixed.md@@ -0,0 +1 @@+Preserve sensor tilt gradients at zero tilt in `distort_points` and `undistort_points`, so gradient-based calibration can learn tilt from a zero initialization.diff --git a/kornia/geometry/calibration/distort.py b/kornia/geometry/calibration/distort.pyindex 40e6101ec..e336f5084 100644--- a/kornia/geometry/calibration/distort.py+++ b/kornia/geometry/calibration/distort.py@@ -20,8 +20,6 @@ from typing import Optionalimport torchimport torch.nn.functional as F-from kornia.core.utils import is_compiling, is_exporting-# Based on https://github.com/opencv/opencv/blob/master/modules/calib3d/src/distortion_model.hpp#L75def tilt_projection(taux: torch.Tensor, tauy: torch.Tensor, return_inverse: bool = False) -> torch.Tensor:@@ -161,6 +159,7 @@ def distort_points(if dist.shape[-1] not in [4, 5, 8, 12, 14]:raise ValueError(f"Invalid number of distortion coefficients. Got {dist.shape[-1]}")+ has_tilt = dist.shape[-1] == 14# Adding torch.zeros to obtain vector with 14 coeffs.if dist.shape[-1] < 14:dist = F.pad(dist, [0, 14 - dist.shape[-1]])@@ -198,12 +197,9 @@ def distort_points(+ dist[..., 11:12] * r4)- # Graph capture cannot read the coefficient values on the host. Apply the tilt unconditionally- # while compiling or exporting; zero angles give the identity. Keep eager and scripted behavior.- capture = is_exporting()- if not torch.jit.is_scripting():- capture = capture or is_compiling()- if capture or torch.any(dist[..., 12] != 0) or torch.any(dist[..., 13] != 0):+ # Zero tilt is the identity but has nonzero angle derivatives. Branch on the model's+ # coefficient count, not its values, so calibration can learn tilt from a zero initialization.+ if has_tilt:tilt = tilt_projection(dist[..., 12:13], dist[..., 13:14])# Transposed untilt points (instead of [x,y,1]^T, we obtain [x,y,1])diff --git a/kornia/geometry/calibration/undistort.py b/kornia/geometry/calibration/undistort.pyindex 82d3dddcc..4eaebc2f4 100644--- a/kornia/geometry/calibration/undistort.py+++ b/kornia/geometry/calibration/undistort.py@@ -23,7 +23,6 @@ import torchimport torch.nn.functional as Ffrom kornia.core.check import KORNIA_CHECK_SHAPE-from kornia.core.utils import is_compiling, is_exportingfrom kornia.geometry.grid import create_meshgridfrom kornia.geometry.linalg import transform_pointsfrom kornia.geometry.transform import remap@@ -100,6 +99,7 @@ def undistort_points(if dist.shape[-1] not in [4, 5, 8, 12, 14]:raise ValueError(f"Invalid number of distortion coefficients. Got {dist.shape[-1]}")+ has_tilt = dist.shape[-1] == 14# Adding torch.zeros to obtain vector with 14 coeffs.if dist.shape[-1] < 14:dist = F.pad(dist, [0, 14 - dist.shape[-1]])@@ -114,12 +114,9 @@ def undistort_points(x: torch.Tensor = (points[..., 0] - cx) / fx # (BxN - Bx1)/Bx1 -> BxNy: torch.Tensor = (points[..., 1] - cy) / fy # (BxN - Bx1)/Bx1 -> BxN- # Graph capture cannot read the coefficient values on the host. Apply the tilt unconditionally- # while compiling or exporting; zero angles give the identity. Keep eager and scripted behavior.- capture = is_exporting()- if not torch.jit.is_scripting():- capture = capture or is_compiling()- if capture or torch.any(dist[..., 12] != 0) or torch.any(dist[..., 13] != 0):+ # Zero tilt is the identity but has nonzero angle derivatives. Branch on the model's+ # coefficient count, not its values, so calibration can learn tilt from a zero initialization.+ if has_tilt:inv_tilt = tilt_projection(dist[..., 12:13], dist[..., 13:14], True)if inv_tilt.dim() == 2:inv_tilt = inv_tilt.unsqueeze(0)diff --git a/tests/geometry/calibration/test_distort.py b/tests/geometry/calibration/test_distort.pyindex 5471bf7e0..4f717bc48 100644--- a/tests/geometry/calibration/test_distort.py+++ b/tests/geometry/calibration/test_distort.py@@ -18,11 +18,11 @@import pytestimport torch-import kornia.geometry.calibration.distort as distort_modulefrom kornia.geometry.calibration.distort import distort_points, tilt_projection+from kornia.geometry.calibration.undistort import undistort_pointsfrom kornia.geometry.camera.distortion_affine import distort_points_affine-from testing.base import BaseTester+from testing.base import DYNAMO_UNAVAILABLE_REASON, BaseTester, dynamo_is_availablefrom testing.geometry.linalg import euler_angles_to_rotation_matrix@@ -72,6 +72,76 @@ class TestTiltProjection(BaseTester):self.assert_close(actual, expected)[email protected]("op", [distort_points, undistort_points])+class TestZeroTiltGradients(BaseTester):+ @pytest.mark.parametrize("batch_shape", [(), (2,), (2, 3)])+ def test_tilt_gradient(self, op, batch_shape, device, dtype):+ points = torch.tensor([[0.3, 0.2], [-0.2, 0.4]], device=device, dtype=dtype).expand(*batch_shape, 2, 2)+ K = torch.eye(3, device=device, dtype=dtype).expand(*batch_shape, 3, 3)+ dist = torch.zeros(*batch_shape, 14, device=device, dtype=dtype, requires_grad=True)++ output = op(points, K, dist)+ self.assert_close(output, points)+ (gradient,) = torch.autograd.grad(output.sum(), dist)+ # At zero tilt, d(x, y)/d(taux) = (xy, y^2) and d(x, y)/d(tauy) = (-x^2, -xy).+ # The inverse map has the opposite derivatives; sum over the two points and coordinates.+ expected = torch.tensor([0.18, -0.11], device=device, dtype=dtype).expand(*batch_shape, 2)+ if op is undistort_points:+ expected = -expected+ self.assert_close(gradient[..., 12:], expected)++ def test_gradcheck(self, op, device):+ points = torch.tensor([[[0.3, 0.2], [-0.2, 0.4]]], device=device, dtype=torch.float64)+ K = torch.eye(3, device=device, dtype=torch.float64)[None]+ dist = torch.zeros(1, 14, device=device, dtype=torch.float64, requires_grad=True)+ self.gradcheck(op, (points, K, dist), requires_grad=(False, False, True))++ @pytest.mark.skipif(not dynamo_is_available(), reason=DYNAMO_UNAVAILABLE_REASON)+ @pytest.mark.parametrize("batch_shape", [(), (2, 3)])+ @pytest.mark.parametrize("num_coeffs", [4, 14])+ def test_export(self, op, batch_shape, num_coeffs, device, dtype):+ class Calibration(torch.nn.Module):+ def forward(self, points, K, dist):+ return op(points, K, dist)++ points = torch.tensor([[0.3, 0.2]], device=device, dtype=dtype).expand(*batch_shape, 1, 2)+ K = torch.eye(3, device=device, dtype=dtype).expand(*batch_shape, 3, 3)+ dist = torch.zeros(*batch_shape, num_coeffs, device=device, dtype=dtype, requires_grad=True)+ exported = torch.export.export(Calibration(), (points, K, dist)).module()+ actual = exported(points, K, dist)+ expected = op(points, K, dist)+ self.assert_close(actual, expected)+ self.assert_close(torch.autograd.grad(actual.sum(), dist)[0], torch.autograd.grad(expected.sum(), dist)[0])++ def test_jit(self, op, device, dtype):+ points = torch.tensor([[[0.3, 0.2]]], device=device, dtype=dtype)+ K = torch.eye(3, device=device, dtype=dtype)[None]+ dist = torch.zeros(1, 14, device=device, dtype=dtype, requires_grad=True)+ scripted = torch.jit.script(op)+ eager_gradient = torch.autograd.grad(op(points, K, dist).sum(), dist)[0]+ scripted_gradient = torch.autograd.grad(scripted(points, K, dist).sum(), dist)[0]+ expected = torch.tensor([[0.1, -0.15]], device=device, dtype=dtype)+ if op is undistort_points:+ expected = -expected+ self.assert_close(eager_gradient[..., 12:], expected)+ self.assert_close(scripted_gradient, eager_gradient)++ def test_dynamo(self, op, device, dtype, torch_optimizer):+ points = torch.tensor([[[0.3, 0.2]]], device=device, dtype=dtype)+ K = torch.eye(3, device=device, dtype=dtype)[None]+ dist = torch.zeros(1, 14, device=device, dtype=dtype, requires_grad=True)+ compiled = torch_optimizer(op, fullgraph=True)+ # At zero coefficients one iteration has the same tilt derivatives as the default five;+ # keep the backward graph small for the oldest supported compiler.+ output = compiled(points, K, dist, num_iters=1) if op is undistort_points else compiled(points, K, dist)+ self.assert_close(output, points)+ compiled_gradient = torch.autograd.grad(output.sum(), dist)[0]+ expected = torch.tensor([[0.1, -0.15]], device=device, dtype=dtype)+ if op is undistort_points:+ expected = -expected+ self.assert_close(compiled_gradient[..., 12:], expected)++class TestDistortPoints(BaseTester):def test_smoke(self, device, dtype):points = torch.rand(1, 2, device=device, dtype=dtype)@@ -112,18 +182,6 @@ class TestDistortPoints(BaseTester):assert actual.shape == (*batch_shape, num_points, 2)self.assert_close(actual, expected)- def test_export_multi_axis_batch(self, monkeypatch, device, dtype):- points = torch.rand(2, 3, 5, 2, device=device, dtype=dtype)- K = torch.eye(3, device=device, dtype=dtype).expand(2, 3, 3, 3).clone()- dist = torch.tensor([0.01, -0.02, 0.001, -0.001], device=device, dtype=dtype).expand(2, 3, 4).clone()- expected = distort_points(points, K, dist)-- monkeypatch.setattr(distort_module, "is_exporting", lambda: True)- actual = distort_points(points, K, dist)-- assert actual.shape == points.shape- self.assert_close(actual, expected)-@pytest.mark.parametrize("batch_size, num_points, num_distcoeff", [(1, 3, 4), (2, 4, 5), (3, 5, 8), (4, 6, 12), (5, 7, 14)])diff --git a/tests/geometry/calibration/test_undistort.py b/tests/geometry/calibration/test_undistort.pyindex 45e042be4..ed7311a39 100644--- a/tests/geometry/calibration/test_undistort.py+++ b/tests/geometry/calibration/test_undistort.py@@ -18,7 +18,6 @@import pytestimport torch-import kornia.geometry.calibration.undistort as undistort_modulefrom kornia.geometry.calibration.distort import distort_pointsfrom kornia.geometry.calibration.undistort import undistort_image, undistort_pointsfrom kornia.geometry.grid import create_meshgrid@@ -92,30 +91,6 @@ class TestUndistortPoints(BaseTester):assert actual.shape == points.shapeself.assert_close(actual, expected)- def test_export_multi_axis_batch(self, monkeypatch, device, dtype):- points = torch.rand(2, 3, 5, 2, device=device, dtype=dtype)- K = torch.eye(3, device=device, dtype=dtype).expand(2, 3, 3, 3).clone()- dist = torch.tensor([0.01, -0.02, 0.001, -0.001], device=device, dtype=dtype).expand(2, 3, 4).clone()- expected = undistort_points(points, K, dist)-- monkeypatch.setattr(undistort_module, "is_exporting", lambda: True)- actual = undistort_points(points, K, dist)-- assert actual.shape == points.shape- self.assert_close(actual, expected)-- def test_export_unbatched(self, monkeypatch, device, dtype):- points = torch.rand(5, 2, device=device, dtype=dtype)- K = torch.eye(3, device=device, dtype=dtype)- dist = torch.tensor([0.01, -0.02, 0.001, -0.001], device=device, dtype=dtype)- expected = undistort_points(points, K, dist)-- monkeypatch.setattr(undistort_module, "is_exporting", lambda: True)- actual = undistort_points(points, K, dist)-- assert actual.shape == points.shape- self.assert_close(actual, expected)-@pytest.mark.parametrize("batch_size, num_points, num_distcoeff", [(1, 3, 4), (2, 4, 5), (3, 5, 8), (4, 6, 12), (5, 7, 14)])