π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(geometry): correct Kannala-Brandt Jacobian (#4368)
Hrithik Sharmaa38a9514be62
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex dbba7dff4..fe92df17e 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -369,6 +369,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Bug fixes+* Fixed `dx_distort_points_kannala_brandt` to return the true Jacobian of `distort_points_kannala_brandt`, including a finite affine Jacobian at the origin. (#4277, #4368)* `Boxes3D.from_tensor(..., validate_boxes=True)` rejects non-finite coordinates, and `validate_bbox3d`returns `False` for them instead of raising an `AssertionError` that names the wrong defect. This is the3D counterpart of #4243. An `inf` passed the positive-extent checks outright, and a `NaN` passed themdiff --git a/kornia/geometry/camera/distortion_kannala_brandt.py b/kornia/geometry/camera/distortion_kannala_brandt.pyindex cdfbfb304..8bf7e027e 100644--- a/kornia/geometry/camera/distortion_kannala_brandt.py+++ b/kornia/geometry/camera/distortion_kannala_brandt.py@@ -200,21 +200,15 @@ def undistort_points_kannala_brandt(distorted_points_in_camera: torch.Tensor, padef dx_distort_points_kannala_brandt(projected_points_in_camera_z1_plane: torch.Tensor, params: torch.Tensor) -> torch.Tensor:- r"""Return the analytic matrix the Kannala-Brandt model provides as its distortion Jacobian.+ r"""Return the analytic Jacobian of the Kannala-Brandt distortion model.Convention:- the result has shape :math:`(..., 2, 2)` and is laid out like the Jacobian that:func:`~kornia.geometry.camera.dx_distort_points_affine` returns: rows are the output components``(u, v)``, columns the input components ``(x, y)``.-- .. warning::- The matrix this function returns today is **not** the Jacobian of- :func:`distort_points_kannala_brandt`. It disagrees with :func:`torch.autograd.functional.jacobian`- and with central finite differences, which agree with each other, and transposing it does not close- the gap; at the origin it is ``nan``. Tracked as- `#4277 <https://github.com/kornia/kornia/issues/4277>`_. The ``Example:`` block below prints the value- this implementation returns today and is deliberately left byte-identical -- it is the executable- evidence for the issue, and the repair has to re-derive it together with the existing regression tests.+ - the Jacobian matches :func:`distort_points_kannala_brandt` with respect to the input point.+ For squared radii less than or equal to ``1e-8``, the forward function uses its affine branch,+ so the Jacobian is ``diag(fx, fy)``.Args:projected_points_in_camera_z1_plane: torch.Tensor representing the points to distort with shape (..., 2).@@ -228,53 +222,103 @@ def dx_distort_points_kannala_brandt(>>> points = torch.tensor([1., 2.])>>> params = torch.tensor([1000.0, 1000.0, 320.0, 280.0, 0.1, 0.01, 0.001, 0.0001])>>> dx_distort_points_kannala_brandt(points, params)- tensor([[ 486.0507, -213.5573],- [-213.5573, 165.7147]])+ tensor([[ 524.3779, -136.9029],+ [-136.9029, 319.0236]])"""KORNIA_CHECK_SHAPE(projected_points_in_camera_z1_plane, ["*", "2"])KORNIA_CHECK_SHAPE(params, ["*", "8"])- a = projected_points_in_camera_z1_plane[..., 0]- b = projected_points_in_camera_z1_plane[..., 1]+ # Match normal PyTorch dtype promotion. Half-precision arithmetic is+ # evaluated in float32 and rounded once at the end for numerical stability.+ output_dtype = torch.promote_types(projected_points_in_camera_z1_plane.dtype, params.dtype)+ compute_dtype = output_dtype- fx, fy = params[..., 0], params[..., 1]+ if compute_dtype in (torch.float16, torch.bfloat16):+ compute_dtype = torch.float32- k0 = params[..., 4]- k1 = params[..., 5]- k2 = params[..., 6]- k3 = params[..., 7]+ points = projected_points_in_camera_z1_plane.to(dtype=compute_dtype)+ params_work = params.to(dtype=compute_dtype)++ x = points[..., 0]+ y = points[..., 1]++ fx, fy = params_work[..., 0], params_work[..., 1]++ k0 = params_work[..., 4]+ k1 = params_work[..., 5]+ k2 = params_work[..., 6]+ k3 = params_work[..., 7]++ radius_sq = x * x + y * y++ # The forward distortion uses the affine model for very small radii.+ # Keep the nonlinear expression finite too because both branch tensors+ # are evaluated before torch.where selects the result.+ nonlinear_mask = radius_sq > 1e-8+ safe_radius_sq = torch.where(+ nonlinear_mask,+ radius_sq,+ torch.ones_like(radius_sq),+ )++ radius = safe_radius_sq.sqrt()+ theta = radius.atan2(torch.ones_like(radius))++ theta2 = theta * theta+ theta4 = theta2 * theta2+ theta6 = theta4 * theta2+ theta8 = theta4 * theta4- # TODO: return identity matrix if a and b are zero- # radius_sq = a ** 2 + b ** 2-- c0 = a.pow(2.0)- c1 = b.pow(2.0)- c2 = c0 + c1- c3 = c2.pow(5.0 / 2.0)- c4 = c2 + 1.0- c5 = c2.sqrt().atan()- c6 = c5.pow(2.0)- c7 = c6 * k0- c8 = c5.pow(4.0)- c9 = c8 * k1- c10 = c5.pow(6.0)- c11 = c10 * k2- c12 = c5.pow(8.0) * k3- c13 = 1.0 * c4 * c5 * (c11 + c12 + c7 + c9 + 1.0)- c14 = c13 * c3- c15 = c2.pow(3.0 / 2.0)- c16 = c13 * c15- c17 = 1.0 * c11 + 1.0 * c12 + 2.0 * c6 * (4.0 * c10 * k3 + 2.0 * c6 * k1 + 3.0 * c8 * k2 + k0)- c18 = c17 * c2.pow(2.0)- c19 = 1.0 / c4- c20 = c19 / c2.pow(3.0)- c21 = a * b * c19 * (-c13 * c2 + c15 * c17) / c3-- return torch.stack(+ polynomial = 1.0 + k0 * theta2 + k1 * theta4 + k2 * theta6 + k3 * theta8++ radius_distorted = theta * polynomial++ d_radius_distorted_d_theta = 1.0 + 3.0 * k0 * theta2 + 5.0 * k1 * theta4 + 7.0 * k2 * theta6 + 9.0 * k3 * theta8++ d_radius_distorted_d_radius = d_radius_distorted_d_theta / (1.0 + safe_radius_sq)++ scaling = radius_distorted / radius++ radial_term = (radius * d_radius_distorted_d_radius - radius_distorted) / (radius * radius * radius)++ nonlinear_jacobian = torch.stack(+ [+ torch.stack(+ [+ fx * (scaling + x * x * radial_term),+ fx * x * y * radial_term,+ ],+ dim=-1,+ ),+ torch.stack(+ [+ fy * x * y * radial_term,+ fy * (scaling + y * y * radial_term),+ ],+ dim=-1,+ ),+ ],+ dim=-2,+ )++ zero = torch.zeros_like(fx)++ affine_jacobian = torch.stack([- torch.stack([c20 * fx * (-c0 * c16 + c0 * c18 + c14), c21 * fx], dim=-1),- torch.stack([c21 * fy, c20 * fy * (-c1 * c16 + c1 * c18 + c14)], dim=-1),+ torch.stack([fx, zero], dim=-1),+ torch.stack([zero, fy], dim=-1),],dim=-2,)++ jacobian = torch.where(+ nonlinear_mask[..., None, None],+ nonlinear_jacobian,+ affine_jacobian,+ )++ if output_dtype in (torch.float16, torch.bfloat16):+ jacobian = jacobian.to(dtype=output_dtype)++ return jacobiandiff --git a/testing/half_precision_xfails/cpu_bfloat16.txt b/testing/half_precision_xfails/cpu_bfloat16.txtindex 43df48b69..59b705bab 100644--- a/testing/half_precision_xfails/cpu_bfloat16.txt+++ b/testing/half_precision_xfails/cpu_bfloat16.txt@@ -165,7 +165,6 @@ call builtins.AssertionError tests/geometry/calibration/test_undistort.py::TestUcall builtins.AssertionError tests/geometry/calibration/test_undistort.py::TestUndistortPoints::test_opencv_five_coeff[cpu-bfloat16]call builtins.AssertionError tests/geometry/calibration/test_undistort.py::TestUndistortPoints::test_opencv_stereo[cpu-bfloat16]call builtins.AssertionError tests/geometry/camera/test_distortion.py::TestDistortionKannalaBrandt::test_distort_points_roundtrip[cpu-bfloat16]-call builtins.AssertionError tests/geometry/camera/test_distortion.py::TestDistortionKannalaBrandt::test_dx_distort_points_kannala_brandt[cpu-bfloat16]call builtins.AssertionError tests/geometry/camera/test_pinhole.py::TestCam2Pixel::test_consistency[cpu-bfloat16-1]call builtins.AssertionError tests/geometry/camera/test_pinhole.py::TestCam2Pixel::test_consistency[cpu-bfloat16-2]call builtins.AssertionError tests/geometry/camera/test_pinhole.py::TestCam2Pixel::test_consistency[cpu-bfloat16-5]diff --git a/tests/geometry/camera/test_distortion.py b/tests/geometry/camera/test_distortion.pyindex 61f0c3a50..70bafe3f7 100644--- a/tests/geometry/camera/test_distortion.py+++ b/tests/geometry/camera/test_distortion.py@@ -171,8 +171,8 @@ class TestDistortionAffine(BaseTester):# Jacobian of distort_points_affine with respect to the POINT (rows = output components, columns = input# components), byte-identical to torch.autograd.functional.jacobian, and constant in the point because the# map is affine -- diag(fx, fy) = diag(100, 100). This is the control probe for the Kannala-Brandt- # Jacobian pinned in TestDistortionKannalaBrandt below, which is NOT the Jacobian of the function it- # documents (kornia#4277).+ # Jacobian pinned in TestDistortionKannalaBrandt below, which now also matches the Jacobian of+ # distort_points_kannala_brandt (kornia#4277, kornia#4368).# Snippet used to generate expected: torch.equal(dx_distort_points_affine(p, par),# torch.autograd.functional.jacobian(lambda q: distort_points_affine(q, par), p)) executed 2026-09-06 on# c0b50ad7 (torch 2.14.0) -> True on cpu (float32/float64/float16/bfloat16) and on mps@@ -250,8 +250,8 @@ class TestDistortionKannalaBrandt(BaseTester):params = torch.tensor([600.0, 600.0, 319.5, 239.5, 0.1, 0.2, 0.3, 0.4], device=device, dtype=dtype)expected = torch.tensor([- [1191.5316162109375, 282.3212890625],- [282.3212890625, 1615.0135498046875],+ [1221.1801242852937, 341.6185175810278],+ [341.6185175810278, 1733.6079006568352],],device=device,dtype=dtype,@@ -408,45 +408,45 @@ class TestDistortionKannalaBrandt(BaseTester):residual = (undistort_points_kannala_brandt(distorted, params) - far).abs().max().item()assert 1e-9 < residual < 1e-7- def test_wart_dx_distort_points_kannala_brandt_disagrees_with_autograd_4277(self, device, dtype):- # Wart pin for kornia#4277: the analytic Jacobian is- # not the Jacobian of distort_points_kannala_brandt. torch.autograd.functional.jacobian and central finite- # differences agree with each other and both disagree with the analytic matrix -- by 62.58 in absolute- # terms on entries of order 1e2 at this point. The asymmetric focal lengths also make the analytic matrix- # nonsymmetric, and its transpose still does not close the gap, so it is not an index-order slip. The- # sibling dx_distort_points_affine (pinned in- # TestDistortionAffine) matches autograd byte for byte.- # The pre-existing test_dx_distort_points_kannala_brandt in this class asserts the same wrong analytic- # family at a different input; the fix for- # #4277 has to re-derive both its ``expected`` and the function's docstring example.- # Snippet used to generate expected: dx_distort_points_kannala_brandt(tensor([0.5, 0.25]), params) executed- # 2026-09-06 at c0b50ad7 (torch 2.14.0, cpu float32) with fx = 100 and fy = 50 ->- # [[22.0633487701416, -35.7770881652832], [-17.8885440826416, 37.8644866943359]]; autograd at the same- # input -> [[84.64064025878906, -4.488434791564941], [-2.24421739578247, 45.6866455078125]].- # Pins the CURRENT value; NOT a contract; delete when #4277 is repaired.+ def test_dx_distort_points_kannala_brandt_affine_branch(self, device, dtype) -> None:+ # The forward distortion switches to the affine model when radius_sq <= 1e-8.+ # Its Jacobian must therefore be diag(fx, fy), including exactly at the origin.+ points = torch.tensor([[0.0, 0.0], [1e-5, 0.0]], device=device, dtype=dtype)params = torch.tensor([100.0, 50.0, 4.0, 3.0, 0.1, 0.01, 0.001, 0.0001], device=device, dtype=dtype)- points = torch.tensor([0.5, 0.25], device=device, dtype=dtype)- analytic = dx_distort_points_kannala_brandt(points, params)++ expected_single = torch.tensor([[100.0, 0.0], [0.0, 50.0]], device=device, dtype=dtype)+ expected = torch.stack([expected_single, expected_single])+self.assert_close(- analytic,- torch.tensor(- [[22.0633487701416, -35.7770881652832], [-17.8885440826416, 37.8644866943359]],- device=device,- dtype=dtype,- ),+ dx_distort_points_kannala_brandt(points, params),+ expected,+ atol=0.0,+ rtol=0.0,)- autograd = torch.autograd.functional.jacobian(lambda q: distort_points_kannala_brandt(q, params), points)- assert not torch.allclose(analytic.float(), analytic.transpose(-1, -2).float())- assert not torch.allclose(analytic.float(), autograd.float())- assert not torch.allclose(analytic.transpose(-1, -2).float(), autograd.float())- @pytest.mark.xfail(strict=True, reason="kornia#4277: the analytic Kannala-Brandt Jacobian disagrees with autograd")def test_convention_dx_distort_points_kannala_brandt_matches_autograd_4277(self, device, dtype):- # Intended contract, asserted as a strict xfail so the repair makes it XPASS and forces this mark out:- # dx_distort_points_kannala_brandt returns the Jacobian of the function it is named after, exactly as- # dx_distort_points_affine and dx_project_points_z1 already do.- # Settled by #4277's own Expected section ("re-derived so it matches autograd and central differences").- params = torch.tensor([100.0, 100.0, 4.0, 3.0, 0.1, 0.01, 0.001, 0.0001], device=device, dtype=dtype)+ # Regression for #4277: the analytic Kannala-Brandt Jacobian must match+ # the derivative of distort_points_kannala_brandt with respect to the point.+ # Asymmetric focal lengths ensure an fx/fy or row/column swap cannot hide.+ params = torch.tensor(+ [100.0, 50.0, 4.0, 3.0, 0.1, 0.01, 0.001, 0.0001],+ device=device,+ dtype=dtype,+ )points = torch.tensor([0.5, 0.25], device=device, dtype=dtype)- autograd = torch.autograd.functional.jacobian(lambda q: distort_points_kannala_brandt(q, params), points)- self.assert_close(dx_distort_points_kannala_brandt(points, params), autograd)++ analytic = dx_distort_points_kannala_brandt(points, params)++ reference_dtype = dtype+ if dtype in (torch.float16, torch.bfloat16):+ reference_dtype = torch.float32++ reference_points = points.to(reference_dtype)+ reference_params = params.to(reference_dtype)++ autograd = torch.autograd.functional.jacobian(+ lambda q: distort_points_kannala_brandt(q, reference_params),+ reference_points,+ ).to(dtype)++ self.assert_close(analytic, autograd)