π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(sensors): implement Brown-Conrady, Kannala-Brandt, and orthographic camera models (#4377)
Hrithik Sharmad9f56df87a69
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 3df8abca7..c1e488652 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -10,6 +10,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Added+* Implemented the exported Brown-Conrady, Kannala-Brandt K3, and Orthographic sensor camera models,+ including distortion/projection plumbing, intrinsic matrices, and batched project/unproject support. (#4284, #4377)* New "Camera and world conventions across the ecosystem" page cataloguing the pixel-centre, axisand extrinsics conventions of OpenCV, COLMAP, OpenGL, ARKit, ARCore, PyTorch3D and Direct3D with thekornia converter for each, plus the baked `align_corners` rows for the depth and undistortion warps ondiff --git a/docs/export_support/cases_models.py b/docs/export_support/cases_models.pyindex 44f3105ce..0b2cccf1e 100644--- a/docs/export_support/cases_models.py+++ b/docs/export_support/cases_models.py@@ -1333,12 +1333,24 @@ A(from kornia.geometry.vector import Vector2, Vector3 # noqa: E402from kornia.image import ImageSize # noqa: E402from kornia.sensors.camera import ( # noqa: E402+ BrownConradyModel,CameraModel,CameraModelType,+ KannalaBrandtK3,+ Orthographic,PinholeModel,)_pin = PinholeModel(ImageSize(480, 640), torch.tensor([[328.0, 328.0, 320.0, 240.0]]))+_bc = BrownConradyModel(+ ImageSize(480, 640),+ torch.tensor([328.0, 328.0, 320.0, 240.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]),+)+_kb = KannalaBrandtK3(+ ImageSize(480, 640),+ torch.tensor([328.0, 328.0, 320.0, 240.0, 0.0, 0.0, 0.0, 0.0]),+)+_orth = Orthographic(ImageSize(480, 640), torch.tensor([328.0, 328.0, 320.0, 240.0]))_pts3 = torch.tensor([[1.0, 2.0, 5.0], [-0.5, 0.3, 2.0]])A(case(@@ -1393,27 +1405,27 @@ A(case("sensors.camera.BrownConradyModel.project","sensors.camera",- None,- [],- skip="raises NotImplementedError in kornia (BrownConradyTransform.distort is a stub)",+ lambda p: _bc.project(Vector3(p)).data,+ [_pts3],+ note="zero Brown-Conrady coefficients; params baked",))A(case("sensors.camera.KannalaBrandtK3.project","sensors.camera",- None,- [],- skip="raises NotImplementedError in kornia (KannalaBrandtK3Transform.distort is a stub)",+ lambda p: _kb.project(Vector3(p)).data,+ [_pts3],+ note="zero Kannala-Brandt coefficients; params baked",))A(case("sensors.camera.Orthographic.project","sensors.camera",- None,- [],- skip="raises NotImplementedError in kornia (Orthographic.project is a stub)",+ lambda p: _orth.project(Vector3(p)).data,+ [_pts3],+ note="orthographic projection with affine intrinsics baked",))A(case("sensors.camera.CameraModelBase/CameraModelType", "sensors.camera", None, [], skip="base class / enum"))diff --git a/docs/source/sensors.camera.rst b/docs/source/sensors.camera.rstindex 9b58bab95..891df11df 100644--- a/docs/source/sensors.camera.rst+++ b/docs/source/sensors.camera.rst@@ -2,7 +2,7 @@ kornia.sensors.camera======================.. meta::- :description: The `kornia.sensors.camera` module provides tools to define and manipulate various camera models, including the Pinhole model. It allows users to specify distortion and projection types in a differentiable way. Pinhole is the only model that works today; the Brown-Conrady, Kannala-Brandt and orthographic models are exported but not yet implemented. It also enables users to define custom camera models using distortion and projection types.+ :description: The `kornia.sensors.camera` module provides differentiable Pinhole, Brown-Conrady, Kannala-Brandt K3, and Orthographic camera models, together with reusable distortion and projection components for defining custom camera models... currentmodule:: kornia.sensors.camera@@ -37,7 +37,7 @@ To define a custom camera model based on distortion and projection types, one cacam = CameraModelBase(AffineTransform(), Z1Projection(), ImageSize(480, 640), params).. note::- Pinhole is the model that works today. :class:`BrownConradyModel`, :class:`KannalaBrandtK3` and :class:`Orthographic` validate their parameters and construct, and then every ``project``, ``unproject`` and ``matrix`` call on them raises ``NotImplementedError``; implementing them is tracked in `#4284 <https://github.com/kornia/kornia/issues/4284>`_.+ The built-in camera models are Pinhole, Brown-Conrady, Kannala-Brandt K3, and Orthographic... autoclass:: CameraModelBase:members:@@ -68,6 +68,12 @@ Distortions.. autoclass:: AffineTransform:members:+.. autoclass:: BrownConradyTransform+ :members:++.. autoclass:: KannalaBrandtK3Transform+ :members:+Projections-----------@@ -76,3 +82,6 @@ Projections.. autoclass:: Z1Projection:members:++.. autoclass:: OrthographicProjection+ :members:diff --git a/kornia/sensors/camera/camera_model.py b/kornia/sensors/camera/camera_model.pyindex 9b5ece25a..a257aa3d1 100644--- a/kornia/sensors/camera/camera_model.py+++ b/kornia/sensors/camera/camera_model.py@@ -105,11 +105,11 @@ class CameraModelBase:Distortion is of 3 types:- Affine, implemented by :class:`~kornia.sensors.camera.distortion_model.AffineTransform`- - Brown Conrady, a placeholder that raises ``NotImplementedError``- - Kannala Brandt K3, a placeholder that raises ``NotImplementedError``+ - Brown Conrady, implemented by :class:`~kornia.sensors.camera.distortion_model.BrownConradyTransform`+ - Kannala Brandt K3, implemented by :class:`~kornia.sensors.camera.distortion_model.KannalaBrandtK3Transform`Projection is of 2 types:- Z1, implemented by :class:`~kornia.sensors.camera.projection_model.Z1Projection`- - Orthographic, a placeholder that raises ``NotImplementedError``+ - Orthographic, implemented by :class:`~kornia.sensors.camera.projection_model.OrthographicProjection`Convention:- the API is ``Vector``-typed: :meth:`project` takes a ``Vector3`` and returns a ``Vector2``, and@@ -129,8 +129,7 @@ class CameraModelBase:``[[fx, 0, cx], [0, fy, cy], [0, 0, 1]]``, carrying the batch axis of ``params`` -- not the:math:`(B, 4, 4)` ``intrinsics`` that :class:`~kornia.geometry.camera.pinhole.PinholeCamera`stores, whose :attr:`~kornia.geometry.camera.pinhole.PinholeCamera.camera_matrix` property returns- the :math:`(B, 3, 3)` block of it. :class:`PinholeModel` implements it; ``CameraModelBase.matrix``- itself raises ``NotImplementedError``.+ the :math:`(B, 3, 3)` block of it. ``CameraModelBase.matrix`` implements it for all supported camera models.- :meth:`project` is ``self.distortion.distort(self.params, self.projection.project(points))`` and:meth:`unproject` the reverse,``self.projection.unproject(self.distortion.undistort(self.params, points), depth)``. ``depth`` is@@ -160,15 +159,6 @@ class CameraModelBase:are kept separate by design -- this one takes ``Vector`` objects, that one plain tensors -- which isrecorded in `#4274 <https://github.com/kornia/kornia/issues/4274>`_.- .. warning::- :class:`BrownConradyModel`, :class:`KannalaBrandtK3` and :class:`Orthographic` validate their- parameters and construct, and then every :meth:`project`, :meth:`unproject` and :meth:`matrix` call on- them raises ``NotImplementedError`` with an empty message, from three independent sites: the- distortion placeholders ``BrownConradyTransform`` and ``KannalaBrandtK3Transform``, the projection- placeholder ``OrthographicProjection``, and ``CameraModelBase.matrix``, which those three classes do- not override. Tracked in `#4284 <https://github.com/kornia/kornia/issues/4284>`_; the behaviour is- documented as it is.-Example:>>> params = torch.Tensor([328., 328., 320., 240.])>>> cam = CameraModelBase(AffineTransform(), Z1Projection(), ImageSize(480, 640), params)@@ -253,7 +243,13 @@ class CameraModelBase:See the Convention block on :class:`~kornia.sensors.camera.CameraModelBase`."""- raise NotImplementedError+ z = torch.zeros_like(self.fx)+ row1 = torch.stack((self.fx, z, self.cx), -1)+ row2 = torch.stack((z, self.fy, self.cy), -1)+ row3 = torch.stack((z, z, z), -1)+ K = torch.stack((row1, row2, row3), -2)+ K[..., -1, -1] = 1.0+ return Kdef K(self) -> torch.Tensor:"""Return the camera matrix.@@ -404,23 +400,17 @@ class PinholeModel(CameraModelBase):class BrownConradyModel(CameraModelBase):- """Brown Conrady Camera Model.-- .. warning::- Constructing this model succeeds; :meth:`~kornia.sensors.camera.CameraModelBase.project` and- :meth:`~kornia.sensors.camera.CameraModelBase.unproject` then raise ``NotImplementedError`` with an- empty message inside ``BrownConradyTransform``, and- :meth:`~kornia.sensors.camera.CameraModelBase.matrix` inside ``CameraModelBase.matrix``, which this- class does not override. Tracked in `#4284 <https://github.com/kornia/kornia/issues/4284>`_.- """+ """Brown Conrady Camera Model."""def __init__(self, image_size: ImageSize, params: torch.Tensor) -> None:"""Construct BrownConradyModel class.Args:image_size: Image size- params: Camera parameters of shape :math:`(B, 12)` of the form :math:`(fx, fy, cx, cy, kb0, kb1, kb2, kb3,- k1, k2, k3, k4)`.+ params: Camera parameters of shape :math:`(12,)` or :math:`(B, 12)`, ordered as+ :math:`(fx, fy, cx, cy, k1, k2, p1, p2, k3, k4, k5, k6)`. The first four values+ are the camera intrinsics and the trailing eight values are the Brown-Conrady+ distortion coefficients."""if params.shape[-1] != 12 or len(params.shape) > 2:@@ -429,15 +419,7 @@ class BrownConradyModel(CameraModelBase):class KannalaBrandtK3(CameraModelBase):- """Kannala Brandt K3 Camera Model.-- .. warning::- Constructing this model succeeds; :meth:`~kornia.sensors.camera.CameraModelBase.project` and- :meth:`~kornia.sensors.camera.CameraModelBase.unproject` then raise ``NotImplementedError`` with an- empty message inside ``KannalaBrandtK3Transform``, and- :meth:`~kornia.sensors.camera.CameraModelBase.matrix` inside ``CameraModelBase.matrix``, which this- class does not override. Tracked in `#4284 <https://github.com/kornia/kornia/issues/4284>`_.- """+ """Kannala Brandt K3 Camera Model."""def __init__(self, image_size: ImageSize, params: torch.Tensor) -> None:"""Construct KannalaBrandtK3 class.@@ -453,15 +435,7 @@ class KannalaBrandtK3(CameraModelBase):class Orthographic(CameraModelBase):- """Orthographic Camera Model.-- .. warning::- Constructing this model succeeds; :meth:`~kornia.sensors.camera.CameraModelBase.project` and- :meth:`~kornia.sensors.camera.CameraModelBase.unproject` then raise ``NotImplementedError`` with an- empty message inside ``OrthographicProjection``, and- :meth:`~kornia.sensors.camera.CameraModelBase.matrix` inside ``CameraModelBase.matrix``, which this- class does not override. Tracked in `#4284 <https://github.com/kornia/kornia/issues/4284>`_.- """+ """Orthographic Camera Model."""def __init__(self, image_size: ImageSize, params: torch.Tensor) -> None:"""Construct Orthographic class.diff --git a/kornia/sensors/camera/distortion_model.py b/kornia/sensors/camera/distortion_model.pyindex 66714cd44..799abeb1d 100644--- a/kornia/sensors/camera/distortion_model.py+++ b/kornia/sensors/camera/distortion_model.py@@ -18,6 +18,11 @@import torch+from kornia.geometry.calibration import distort_points, undistort_points+from kornia.geometry.camera.distortion_kannala_brandt import (+ distort_points_kannala_brandt,+ undistort_points_kannala_brandt,+)from kornia.geometry.vector import Vector2@@ -99,58 +104,120 @@ class BrownConradyTransform:distortion (due to lens misalignment). It is commonly used to transformpoints between ideal pinhole projections and distorted image coordinates.- .. warning::- Both methods are placeholders: :meth:`distort` and :meth:`undistort` raise- ``NotImplementedError`` with an empty message, which is what makes- :class:`~kornia.sensors.camera.BrownConradyModel` unusable in either direction. Tracked in- `#4284 <https://github.com/kornia/kornia/issues/4284>`_.- :func:`~kornia.geometry.calibration.distort_points` is the implemented Brown-Conrady model, in- pixel space with a separate ``K`` and coefficient vector rather than one packed parameter vector.-- Args:- params: A tensor containing the distortion coefficients- (usually k1, k2, p1, p2, k3).- points: A :class:`Vector2` representing the 2D coordinates to be transformed.+ The transform expects a 12-value parameter vector ordered as+ :math:`(fx, fy, cx, cy, k1, k2, p1, p2, k3, k4, k5, k6)`. The first four+ values are camera intrinsics and the trailing eight values are the+ Brown-Conrady distortion coefficients.++ :meth:`distort` maps normalized :math:`z = 1` image-plane coordinates to+ distorted pixel coordinates, while :meth:`undistort` maps distorted pixel+ coordinates back to normalized :math:`z = 1` coordinates."""def distort(self, params: torch.Tensor, points: Vector2) -> Vector2:"""Apply Brown-Conrady lens distortion to ideal normalized points.Args:- params: Distortion parameter tensor, typically containing radial- coefficients such as ``k1``, ``k2``, ``k3`` and tangential- coefficients such as ``p1`` and ``p2``.- points: Ideal two-dimensional normalized points before lens- distortion. Leading dimensions may represent a batch.+ params: Camera and distortion parameters ordered as+ ``(fx, fy, cx, cy, k1, k2, p1, p2, k3, k4, k5, k6)``.+ The first four values define the camera intrinsics and the+ trailing eight values follow the Brown-Conrady coefficient+ layout used by :func:`kornia.geometry.calibration.distort_points`.+ points: Ideal two-dimensional points on the normalized+ :math:`z = 1` image plane. Leading dimensions may represent a batch.Returns:- Distorted two-dimensional points in the same coordinate convention.+ Distorted two-dimensional points in pixel coordinates.- Raises:- NotImplementedError: The Brown-Conrady transform interface is- declared here, but the concrete computation is not implemented."""- raise NotImplementedError+ fx, fy, cx, cy = (+ params[..., 0],+ params[..., 1],+ params[..., 2],+ params[..., 3],+ )+ zero = torch.zeros_like(fx)+ one = torch.ones_like(fx)++ K = torch.stack(+ (+ torch.stack((fx, zero, cx), dim=-1),+ torch.stack((zero, fy, cy), dim=-1),+ torch.stack((zero, zero, one), dim=-1),+ ),+ dim=-2,+ )++ identity = torch.eye(3, device=params.device, dtype=params.dtype)++ point_data = points.data+ squeeze_point_dim = point_data.ndim == params.ndim+ if squeeze_point_dim:+ point_data = point_data.unsqueeze(-2)++ distorted = distort_points(+ point_data,+ K,+ params[..., 4:],+ new_K=identity,+ )++ if squeeze_point_dim:+ distorted = distorted.squeeze(-2)++ return Vector2(distorted)def undistort(self, params: torch.Tensor, points: Vector2) -> Vector2:"""Remove Brown-Conrady lens distortion from observed points.Args:- params: Distortion parameter tensor matching the coefficients used- by :meth:`distort`.- points: Distorted two-dimensional points, usually measured in the- normalized image plane.+ params: Camera and distortion parameters ordered as+ ``(fx, fy, cx, cy, k1, k2, p1, p2, k3, k4, k5, k6)``.+ The layout is identical to :meth:`distort`.+ points: Distorted two-dimensional points in pixel coordinates.+ Leading dimensions may represent a batch.Returns:- Undistorted two-dimensional points that approximate the ideal- pinhole projection.+ Undistorted two-dimensional points on the normalized+ :math:`z = 1` image plane.- Raises:- NotImplementedError: The Brown-Conrady inverse transform interface- is declared here, but the concrete computation is not- implemented."""- raise NotImplementedError+ fx, fy, cx, cy = (+ params[..., 0],+ params[..., 1],+ params[..., 2],+ params[..., 3],+ )+ zero = torch.zeros_like(fx)+ one = torch.ones_like(fx)++ K = torch.stack(+ (+ torch.stack((fx, zero, cx), dim=-1),+ torch.stack((zero, fy, cy), dim=-1),+ torch.stack((zero, zero, one), dim=-1),+ ),+ dim=-2,+ )++ identity = torch.eye(3, device=params.device, dtype=params.dtype)++ point_data = points.data+ squeeze_point_dim = point_data.ndim == params.ndim+ if squeeze_point_dim:+ point_data = point_data.unsqueeze(-2)++ undistorted = undistort_points(+ point_data,+ K,+ params[..., 4:],+ new_K=identity,+ )++ if squeeze_point_dim:+ undistorted = undistorted.squeeze(-2)++ return Vector2(undistorted)class KannalaBrandtK3Transform:@@ -159,13 +226,6 @@ class KannalaBrandtK3Transform:This model is specifically designed for fisheye lenses with significantradial distortion, using a polynomial approximation for the projection.- .. warning::- Both methods are placeholders: :meth:`distort` and :meth:`undistort` raise- ``NotImplementedError`` with an empty message, which is what makes- :class:`~kornia.sensors.camera.KannalaBrandtK3` unusable in either direction. Tracked in- `#4284 <https://github.com/kornia/kornia/issues/4284>`_.- :func:`~kornia.geometry.camera.distort_points_kannala_brandt` is the implemented equivalent, on the- same normalized input and the same packed parameter vector."""def distort(self, params: torch.Tensor, points: Vector2) -> Vector2:@@ -179,11 +239,8 @@ class KannalaBrandtK3Transform:Returns:Distorted two-dimensional points following the K3 fisheye model.- Raises:- NotImplementedError: The K3 distortion interface is declared here,- but the concrete computation is not implemented."""- raise NotImplementedError+ return Vector2(distort_points_kannala_brandt(points.data, params))def undistort(self, params: torch.Tensor, points: Vector2) -> Vector2:"""Remove Kannala-Brandt K3 fisheye distortion from observed points.@@ -197,8 +254,5 @@ class KannalaBrandtK3Transform:Undistorted normalized points that approximate ideal pinholecoordinates.- Raises:- NotImplementedError: The K3 inverse distortion interface is- declared here, but the concrete computation is not implemented."""- raise NotImplementedError+ return Vector2(undistort_points_kannala_brandt(points.data, params))diff --git a/kornia/sensors/camera/projection_model.py b/kornia/sensors/camera/projection_model.pyindex 0717c130a..92436ec94 100644--- a/kornia/sensors/camera/projection_model.py+++ b/kornia/sensors/camera/projection_model.py@@ -19,6 +19,10 @@ from __future__ import annotationsimport torch+from kornia.geometry.camera.projection_orthographic import (+ project_points_orthographic,+ unproject_points_orthographic,+)from kornia.geometry.vector import Vector2, Vector3@@ -100,11 +104,6 @@ class OrthographicProjection:This model assumes parallel projection where the $z$ coordinate isdiscarded and no perspective scaling is applied.- .. warning::- Both methods are placeholders: :meth:`project` and :meth:`unproject` raise ``NotImplementedError``- with an empty message, which is what makes :class:`~kornia.sensors.camera.Orthographic` unusable in- either direction. Tracked in `#4284 <https://github.com/kornia/kornia/issues/4284>`_.- :func:`~kornia.geometry.camera.project_points_orthographic` is the implemented equivalent."""def project(self, points: Vector3) -> Vector2:@@ -123,11 +122,8 @@ class OrthographicProjection:Two-dimensional point container containing the projected ``x`` and``y`` coordinates.- Raises:- NotImplementedError: This projection model is declared as an- interface placeholder and is not implemented yet."""- raise NotImplementedError+ return Vector2(project_points_orthographic(points.data))def unproject(self, points: Vector2, depth: torch.Tensor) -> Vector3:"""Lift orthographic image-plane points back into 3D using depth.@@ -142,8 +138,5 @@ class OrthographicProjection:Three-dimensional point container with ``x`` and ``y`` copied from``points`` and ``z`` supplied by ``depth``.- Raises:- NotImplementedError: This projection model is declared as an- interface placeholder and is not implemented yet."""- raise NotImplementedError+ return Vector3(unproject_points_orthographic(points.data, depth))diff --git a/tests/sensors/camera/test_camera_model.py b/tests/sensors/camera/test_camera_model.pyindex d9919a92d..754b786ce 100644--- a/tests/sensors/camera/test_camera_model.py+++ b/tests/sensors/camera/test_camera_model.py@@ -414,53 +414,6 @@ class TestCameraModelTypes(BaseTester):with pytest.raises(ValueError, match=r"params must be of shape .* for KANNALA_BRANDT_K3 Camera"):CameraModel(ImageSize(6, 8), CameraModelType.KANNALA_BRANDT_K3, torch.ones(7, device=device, dtype=dtype))- def test_wart_the_three_non_pinhole_models_construct_and_then_raise_4284(self, device, dtype):- # Wart pin for kornia#4284 (audit labels 5d-sc-14, 5d-sc-16, 5d-sc-17, 5d-sc-19, 5d-sc-20, 5d-sc-22,- # 5d-sc-23): BROWN_CONRADY, KANNALA_BRANDT_K3 and ORTHOGRAPHIC are exported from- # ``kornia.sensors.camera.__all__``, validate their parameter vectors and construct without complaint- # -- and then project, unproject and matrix all raise NotImplementedError with an EMPTY message,- # from THREE different kinds of site. Measured raise sites, as the qualified function name of the- # last frame of each traceback -- ``traceback.extract_tb(exc.__traceback__)[-1]`` -- executed- # 2026-09-06 on this worktree (torch 2.14.0, cpu float32). Names rather than line numbers, because- # a line number in a comment rots the next time either module is edited:- # BROWN_CONRADY project -> BrownConradyTransform.distort- # unproject -> BrownConradyTransform.undistort- # KANNALA_BRANDT_K3 project -> KannalaBrandtK3Transform.distort- # unproject -> KannalaBrandtK3Transform.undistort- # ORTHOGRAPHIC project -> OrthographicProjection.project- # unproject -> OrthographicProjection.unproject- # all three matrix -> CameraModelBase.matrix- # So the two failure modes of project/unproject are a distortion placeholder (BROWN_CONRADY and- # KANNALA_BRANDT_K3, which wire up the working Z1Projection and fail in the distortion) and a- # projection placeholder (ORTHOGRAPHIC, in BOTH directions -- its AffineTransform never fails); those- # placeholders are pinned at their own level in tests/sensors/camera/test_distortion_model.py and- # test_projection_model.py. ``matrix()`` is a THIRD, independent site: the three classes do not- # override ``CameraModelBase.matrix``, which is itself a bare raise, so implementing the distortions- # and the orthographic projection (#4284's Expected option 1) would leave ``matrix()`` raising until- # each class grows its own override the way PinholeModel already has.- # ``project``/``unproject`` are ``CameraModelBase``'s -- the three classes add no overrides -- so this- # pins the base class's behaviour on those models too.- # The empty message is asserted rather than described, because #4284's Expected asks at minimum for a- # message naming the model: a message-only partial fix must flip these pins.- # Snippet used to generate expected: project(Vector3([[1., 2., 4.]])) / unproject(Vector2([[0.5,- # 0.25]]), tensor([2.])) / matrix() on each of the three models executed 2026-09-06 on this worktree- # (torch 2.14.0) -> NotImplementedError('') for all nine calls, on cpu for float32, float64, float16- # and bfloat16 and on mps for float32 and float16.- # Pins the CURRENT behaviour; NOT a contract; delete when #4284 is repaired.- point3 = Vector3(torch.tensor([[1.0, 2.0, 4.0]], device=device, dtype=dtype))- point2 = Vector2(torch.tensor([[0.5, 0.25]], device=device, dtype=dtype))- depth = torch.tensor([2.0], device=device, dtype=dtype)- for model_type, length in self._LENGTHS[1:]:- cam = CameraModel(ImageSize(6, 8), model_type, torch.ones(length, device=device, dtype=dtype))- assert cam.params.shape == (length,)- for call, args in ((cam.project, (point3,)), (cam.unproject, (point2, depth)), (cam.matrix, ())):- with pytest.raises(NotImplementedError) as raised:- call(*args)- assert str(raised.value) == ""- pinhole = CameraModel(ImageSize(6, 8), CameraModelType.PINHOLE, torch.ones(4, device=device, dtype=dtype))- assert isinstance(pinhole.project(point3), Vector2)- assert isinstance(pinhole.matrix(), torch.Tensor)-class TestCameraModelBaseParamsValidation:"""`CameraModelBase` is public and documents a `params` shape it did not check.@@ -535,3 +488,144 @@ class TestCameraModelBaseParamsValidation:AffineTransform(), OrthographicProjection(), self.image_size, torch.ones(4, device=device, dtype=dtype))assert tuple(cam.params.shape) == (4,)+++class TestNonPinholeCameraMatrix(BaseTester):+ @pytest.mark.parametrize(+ ("model_type", "num_params"),+ [+ (CameraModelType.BROWN_CONRADY, 12),+ (CameraModelType.KANNALA_BRANDT_K3, 8),+ (CameraModelType.ORTHOGRAPHIC, 4),+ ],+ )+ def test_matrix_unbatched(self, device, dtype, model_type, num_params):+ params = torch.zeros(num_params, device=device, dtype=dtype)+ params[:4] = torch.tensor(+ [300.0, 320.0, 160.0, 120.0],+ device=device,+ dtype=dtype,+ )++ cam = CameraModel(ImageSize(240, 320), model_type, params)++ expected = torch.tensor(+ [+ [300.0, 0.0, 160.0],+ [0.0, 320.0, 120.0],+ [0.0, 0.0, 1.0],+ ],+ device=device,+ dtype=dtype,+ )++ self.assert_close(cam.matrix(), expected)++ @pytest.mark.parametrize(+ ("model_type", "num_params"),+ [+ (CameraModelType.BROWN_CONRADY, 12),+ (CameraModelType.KANNALA_BRANDT_K3, 8),+ (CameraModelType.ORTHOGRAPHIC, 4),+ ],+ )+ def test_matrix_batched(self, device, dtype, model_type, num_params):+ params = torch.zeros(2, num_params, device=device, dtype=dtype)+ params[:, :4] = torch.tensor(+ [+ [300.0, 320.0, 160.0, 120.0],+ [280.0, 300.0, 150.0, 110.0],+ ],+ device=device,+ dtype=dtype,+ )++ cam = CameraModel(ImageSize(240, 320), model_type, params)++ expected = torch.tensor(+ [+ [+ [300.0, 0.0, 160.0],+ [0.0, 320.0, 120.0],+ [0.0, 0.0, 1.0],+ ],+ [+ [280.0, 0.0, 150.0],+ [0.0, 300.0, 110.0],+ [0.0, 0.0, 1.0],+ ],+ ],+ device=device,+ dtype=dtype,+ )++ self.assert_close(cam.matrix(), expected)+++class TestNonPinholeCameraProjectUnproject(BaseTester):+ @pytest.mark.parametrize(+ ("model_type", "num_params"),+ [+ (CameraModelType.BROWN_CONRADY, 12),+ (CameraModelType.KANNALA_BRANDT_K3, 8),+ (CameraModelType.ORTHOGRAPHIC, 4),+ ],+ )+ def test_project_unproject_unbatched(self, device, dtype, model_type, num_params):+ params = torch.zeros(num_params, device=device, dtype=dtype)+ params[:4] = torch.tensor(+ [300.0, 320.0, 160.0, 120.0],+ device=device,+ dtype=dtype,+ )++ cam = CameraModel(ImageSize(240, 320), model_type, params)++ points = torch.tensor(+ [0.3, -0.2, 2.0],+ device=device,+ dtype=dtype,+ )++ projected = cam.project(Vector3(points))+ unprojected = cam.unproject(projected, points[..., 2])++ self.assert_close(unprojected.data, points)++ @pytest.mark.parametrize(+ ("model_type", "num_params"),+ [+ (CameraModelType.BROWN_CONRADY, 12),+ (CameraModelType.KANNALA_BRANDT_K3, 8),+ (CameraModelType.ORTHOGRAPHIC, 4),+ ],+ )+ def test_project_unproject_batched(self, device, dtype, model_type, num_params):+ params = torch.zeros(2, num_params, device=device, dtype=dtype)+ params[:, :4] = torch.tensor(+ [+ [300.0, 320.0, 160.0, 120.0],+ [280.0, 300.0, 150.0, 110.0],+ ],+ device=device,+ dtype=dtype,+ )++ cam = CameraModel(ImageSize(240, 320), model_type, params)++ points = torch.tensor(+ [+ [0.3, -0.2, 2.0],+ [-0.4, 0.25, 3.0],+ ],+ device=device,+ dtype=dtype,+ )++ projected = cam.project(Vector3(points))+ unprojected = cam.unproject(projected, points[..., 2])++ assert projected.data.shape == (2, 2)+ assert unprojected.data.shape == points.shape++ self.assert_close(unprojected.data, points)diff --git a/tests/sensors/camera/test_distortion_model.py b/tests/sensors/camera/test_distortion_model.pyindex e5956e6b5..8090fa671 100644--- a/tests/sensors/camera/test_distortion_model.py+++ b/tests/sensors/camera/test_distortion_model.py@@ -18,9 +18,18 @@import pytestimport torch-from kornia.geometry.camera import distort_points_affine+from kornia.geometry.calibration import distort_points, undistort_points+from kornia.geometry.camera import (+ distort_points_affine,+ distort_points_kannala_brandt,+ undistort_points_kannala_brandt,+)from kornia.geometry.vector import Vector2-from kornia.sensors.camera.distortion_model import AffineTransform, BrownConradyTransform, KannalaBrandtK3Transform+from kornia.sensors.camera.distortion_model import (+ AffineTransform,+ BrownConradyTransform,+ KannalaBrandtK3Transform,+)from testing.base import BaseTester@@ -108,32 +117,208 @@ class TestAffineTransform(BaseTester):)-class TestUnimplementedDistortions(BaseTester):- def test_wart_brown_conrady_and_kannala_brandt_transforms_are_placeholders_4284(self, device, dtype):- # Wart pin for kornia#4284 (audit labels 5d-sc-24, 5d-sc-25): two of the three distortion models in- # ``kornia.sensors.camera.distortion_model`` are bare ``raise NotImplementedError`` placeholders with- # an EMPTY message, in both directions -- ``distort`` and ``undistort``. They are what makes- # ``CameraModel(..., BROWN_CONRADY, ...)`` and ``CameraModel(..., KANNALA_BRANDT_K3, ...)``- # unusable in BOTH directions (pinned at the model level in- # tests/sensors/camera/test_camera_model.py, whose comment records the measured raise sites as- # qualified function names -- ``BrownConradyTransform.distort`` / ``.undistort`` and- # ``KannalaBrandtK3Transform.distort`` / ``.undistort`` for these four calls). Working equivalents- # already exist next door as ``kornia.geometry.calibration.distort_points`` and- # ``kornia.geometry.camera.distort_points_kannala_brandt``. Parameter vectors of the documented- # lengths (12 and 8) are used, so the raise is not a shape rejection in disguise. The empty message- # is asserted rather than described, because #4284's Expected asks at minimum for a message naming- # the model: a message-only partial fix must flip this pin.- # Snippet used to generate expected: BrownConradyTransform().distort(ones(12), Vector2([[0.5,- # 0.25]])) and the three sibling calls executed 2026-09-06 on this worktree (torch 2.14.0) ->- # NotImplementedError('') for all four, on cpu for float32, float64, float16 and bfloat16 and on mps- # for float32 and float16.- # Pins the CURRENT behaviour; NOT a contract; delete when #4284 is repaired.- points = Vector2(torch.tensor([[0.5, 0.25]], device=device, dtype=dtype))- for transform, length in ((BrownConradyTransform(), 12), (KannalaBrandtK3Transform(), 8)):- params = torch.ones(length, device=device, dtype=dtype)- for call in (transform.distort, transform.undistort):- with pytest.raises(NotImplementedError) as raised:- call(params, points)- assert str(raised.value) == ""- affine_params = torch.ones(4, device=device, dtype=dtype)- assert isinstance(AffineTransform().distort(affine_params, points), Vector2)+class TestKannalaBrandtK3Transform(BaseTester):+ def test_distort_matches_geometry(self, device, dtype):+ distortion = KannalaBrandtK3Transform()+ points = torch.tensor(+ [[0.1, 0.2], [-0.3, 0.25]],+ device=device,+ dtype=dtype,+ )+ params = torch.tensor(+ [300.0, 320.0, 160.0, 120.0, 0.01, -0.001, 0.0001, -0.00001],+ device=device,+ dtype=dtype,+ )++ expected = distort_points_kannala_brandt(points, params)+ actual = distortion.distort(params, Vector2(points)).data++ self.assert_close(actual, expected, atol=0.0, rtol=0.0)++ def test_undistort_matches_geometry(self, device, dtype):+ distortion = KannalaBrandtK3Transform()+ normalized = torch.tensor(+ [[0.1, 0.2], [-0.3, 0.25]],+ device=device,+ dtype=dtype,+ )+ params = torch.tensor(+ [300.0, 320.0, 160.0, 120.0, 0.01, -0.001, 0.0001, -0.00001],+ device=device,+ dtype=dtype,+ )+ distorted = distort_points_kannala_brandt(normalized, params)++ expected = undistort_points_kannala_brandt(distorted, params)+ actual = distortion.undistort(params, Vector2(distorted)).data++ self.assert_close(actual, expected, atol=0.0, rtol=0.0)+++class TestBrownConradyTransform(BaseTester):+ def test_batched_distort_preserves_batch_shape(self, device, dtype):+ distortion = BrownConradyTransform()++ points = torch.tensor(+ [[0.1, 0.2], [-0.2, 0.15]],+ device=device,+ dtype=dtype,+ )++ params = torch.tensor(+ [+ [300.0, 320.0, 160.0, 120.0, 0.01, -0.001, 0.0005, -0.0003, 0.0001, -0.0001, 0.00005, -0.00002],+ [280.0, 300.0, 150.0, 110.0, 0.02, -0.002, 0.0004, -0.0002, 0.0002, -0.0001, 0.00003, -0.00001],+ ],+ device=device,+ dtype=dtype,+ )++ actual = distortion.distort(params, Vector2(points)).data++ assert actual.shape == points.shape++ def test_batched_undistort_preserves_batch_shape(self, device, dtype):+ distortion = BrownConradyTransform()++ normalized = torch.tensor(+ [[0.1, 0.2], [-0.2, 0.15]],+ device=device,+ dtype=dtype,+ )++ params = torch.tensor(+ [+ [300.0, 320.0, 160.0, 120.0, 0.01, -0.001, 0.0005, -0.0003, 0.0001, -0.0001, 0.00005, -0.00002],+ [280.0, 300.0, 150.0, 110.0, 0.02, -0.002, 0.0004, -0.0002, 0.0002, -0.0001, 0.00003, -0.00001],+ ],+ device=device,+ dtype=dtype,+ )++ distorted = distortion.distort(params, Vector2(normalized)).data+ actual = distortion.undistort(params, Vector2(distorted)).data++ assert actual.shape == normalized.shape++ def test_distort_matches_calibration(self, device, dtype):+ distortion = BrownConradyTransform()++ points = torch.tensor(+ [[0.1, 0.2], [-0.2, 0.15]],+ device=device,+ dtype=dtype,+ )++ params = torch.tensor(+ [+ 300.0,+ 320.0,+ 160.0,+ 120.0,+ 0.01,+ -0.001,+ 0.0005,+ -0.0003,+ 0.0001,+ -0.0001,+ 0.00005,+ -0.00002,+ ],+ device=device,+ dtype=dtype,+ )++ fx, fy, cx, cy = params[:4]++ K = torch.stack(+ [+ torch.stack([fx, torch.zeros_like(fx), cx]),+ torch.stack([torch.zeros_like(fy), fy, cy]),+ torch.stack(+ [+ torch.zeros_like(fx),+ torch.zeros_like(fx),+ torch.ones_like(fx),+ ]+ ),+ ]+ )++ identity = torch.eye(3, device=device, dtype=dtype)++ expected = distort_points(+ points,+ K,+ params[4:],+ new_K=identity,+ )++ actual = distortion.distort(params, Vector2(points)).data++ self.assert_close(actual, expected)++ def test_undistort_matches_calibration(self, device, dtype):+ distortion = BrownConradyTransform()++ normalized = torch.tensor(+ [[0.1, 0.2], [-0.2, 0.15]],+ device=device,+ dtype=dtype,+ )++ params = torch.tensor(+ [+ 300.0,+ 320.0,+ 160.0,+ 120.0,+ 0.01,+ -0.001,+ 0.0005,+ -0.0003,+ 0.0001,+ -0.0001,+ 0.00005,+ -0.00002,+ ],+ device=device,+ dtype=dtype,+ )++ fx, fy, cx, cy = params[:4]++ K = torch.stack(+ [+ torch.stack([fx, torch.zeros_like(fx), cx]),+ torch.stack([torch.zeros_like(fy), fy, cy]),+ torch.stack(+ [+ torch.zeros_like(fx),+ torch.zeros_like(fx),+ torch.ones_like(fx),+ ]+ ),+ ]+ )++ identity = torch.eye(3, device=device, dtype=dtype)++ distorted = distort_points(+ normalized,+ K,+ params[4:],+ new_K=identity,+ )++ expected = undistort_points(+ distorted,+ K,+ params[4:],+ new_K=identity,+ )++ actual = distortion.undistort(params, Vector2(distorted)).data++ self.assert_close(actual, expected)diff --git a/tests/sensors/camera/test_projection_model.py b/tests/sensors/camera/test_projection_model.pyindex ba0fa7ec3..5febca796 100644--- a/tests/sensors/camera/test_projection_model.py+++ b/tests/sensors/camera/test_projection_model.py@@ -18,6 +18,7 @@import pytestimport torch+from kornia.geometry.camera import project_points_orthographic, unproject_points_orthographicfrom kornia.geometry.vector import Vector2, Vector3from kornia.sensors.camera.projection_model import OrthographicProjection, Z1Projection@@ -112,40 +113,6 @@ class TestProjection(BaseTester):class TestOrthographicProjection(BaseTester):- def test_wart_orthographic_projection_is_a_placeholder_4284(self, device, dtype):- # Wart pin for kornia#4284 (audit labels 5d-sc-22, 5d-sc-26): ``OrthographicProjection`` is the- # projection half of the ORTHOGRAPHIC camera model and is a bare ``raise NotImplementedError`` with- # an EMPTY message in both directions. It is reachable through the public API --- # ``CameraModel(..., CameraModelType.ORTHOGRAPHIC, ...)`` constructs and wires this class in -- so the- # model-level project AND unproject raises pinned in tests/sensors/camera/test_camera_model.py both- # come from here (the last traceback frame of each is measured as ``OrthographicProjection.project``- # and ``OrthographicProjection.unproject`` -- a name rather than a line number, which would rot on- # the next edit of that module), not from a distortion placeholder: ORTHOGRAPHIC pairs this- # projection with the working ``AffineTransform``, which never fails for it in either direction.- # Its ``matrix()`` raises from a third site again,- # ``CameraModelBase.matrix``. A working equivalent already exists next door as- # ``kornia.geometry.camera.project_points_orthographic``. The empty message is asserted rather than- # described, because #4284's Expected asks at minimum for a message naming the model: a message-only- # partial fix must flip this pin.- # Snippet used to generate expected: OrthographicProjection().project(Vector3(tensor([[1., 2., 4.]])))- # and .unproject(Vector2(tensor([[0.5, 0.25]])), tensor([2.])) executed 2026-09-06 on this worktree- # (torch 2.14.0) -> NotImplementedError('') for both, on cpu for float32, float64, float16 and- # bfloat16 and on mps for float32 and float16.- # Pins the CURRENT behaviour; NOT a contract; delete when #4284 is repaired.- projection = OrthographicProjection()- with pytest.raises(NotImplementedError) as raised:- projection.project(Vector3(torch.tensor([[1.0, 2.0, 4.0]], device=device, dtype=dtype)))- assert str(raised.value) == ""- with pytest.raises(NotImplementedError) as raised:- projection.unproject(- Vector2(torch.tensor([[0.5, 0.25]], device=device, dtype=dtype)),- torch.tensor([2.0], device=device, dtype=dtype),- )- assert str(raised.value) == ""- assert isinstance(- Z1Projection().project(Vector3(torch.tensor([[1.0, 2.0, 4.0]], device=device, dtype=dtype))), Vector2- )-def test_unproject_scalar_depth(self, device, dtype):"""Regression test: scalar depth must preserve device and dtype.@@ -167,3 +134,30 @@ class TestOrthographicProjection(BaseTester):# Also verify a vector depth still works unchangedout_vec = projection.unproject(points, torch.tensor([4.0], device=device, dtype=dtype))self.assert_close(out_vec.data, expected, atol=0.0, rtol=0.0)++ def test_orthographic_project_matches_geometry(self, device, dtype):+ projection = OrthographicProjection()+ points = torch.tensor(+ [[1.0, 2.0, 3.0], [-4.0, 5.0, 7.0]],+ device=device,+ dtype=dtype,+ )++ expected = project_points_orthographic(points)+ actual = projection.project(Vector3(points)).data++ self.assert_close(actual, expected, atol=0.0, rtol=0.0)++ def test_orthographic_unproject_matches_geometry(self, device, dtype):+ projection = OrthographicProjection()+ points = torch.tensor(+ [[1.0, 2.0], [3.0, 4.0]],+ device=device,+ dtype=dtype,+ )+ depth = torch.tensor([5.0, 6.0], device=device, dtype=dtype)++ expected = unproject_points_orthographic(points, depth)+ actual = projection.unproject(Vector2(points), depth).data++ self.assert_close(actual, expected, atol=0.0, rtol=0.0)