π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
docs(sensors): Convention blocks for camera (batch 5d: sensors.camera) (#4318)
Dmytro Mishkin8e1daae456cb
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex d775f312a..af93eb27a 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -10,6 +10,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Added+* Documented the `kornia.sensors.camera` conventions (`Vector`-typed inputs, the per-model `params`+ layout, the shared half-pixel `scale` rule, and the pinhole mapping shared with `kornia.geometry.camera`,+ including its camera-axis broadcasting, projection rounding and zero/near-zero depth differences) and+ added executable pins, with the unimplemented models tracked in a dedicated issue; the three non-pinhole+ models now appear on the sensors documentation page. (#4318)* Documented depth and stereo conventions (the two meanings of depth, the `(B, 3, H, W)` versus`(B, H, W, 3)` layouts, the opposite source/destination naming of `warp_frame_depth` and`DepthWarper`, the rectified stereo `Q` matrix) and added executable pins for `kornia.geometry.depth`diff --git a/docs/source/sensors.camera.rst b/docs/source/sensors.camera.rstindex b562df536..9b58bab95 100644--- a/docs/source/sensors.camera.rst+++ b/docs/source/sensors.camera.rst@@ -2,12 +2,12 @@ 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. While currently supporting only the Pinhole model, the module aims to extend its support to other models like Kannala Brandt and Orthographic. It also enables users to define custom camera models using distortion and projection types.+ :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... currentmodule:: kornia.sensors.camera.. warning::- :mod:`kornia.sensors.camera` is an experimental API and is subject to change. Once finished, it will subsume :mod:`kornia.geometry.camera`+ :mod:`kornia.sensors.camera` is an experimental API and is subject to change. Once finished, it will subsume :mod:`kornia.geometry.camera`, although today the two are kept separate by design -- they share the mathematical Pinhole mapping but differ in input types, camera-axis broadcasting, projection rounding, and zero/near-zero depth handling (see the Convention block on :class:`CameraModelBase`), which is recorded in `#4274 <https://github.com/kornia/kornia/issues/4274>`_.The objective of :mod:`kornia.sensors.camera` is to express well-known camera models such as Pinhole, Kannala Brandt, and others in terms of distortion and projection types while ensuring differentiability.We also aim to equip the user with tools to define custom camera models.@@ -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::- At the moment, the only supported model is Pinhole. We plan to add Kannala-Brandt, orthographic, and other models in the future.+ 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>`_... autoclass:: CameraModelBase:members:@@ -51,6 +51,15 @@ To define a custom camera model based on distortion and projection types, one ca.. autoclass:: PinholeModel:members:+.. autoclass:: BrownConradyModel+ :members:++.. autoclass:: KannalaBrandtK3+ :members:++.. autoclass:: Orthographic+ :members:+Distortions-----------diff --git a/kornia/sensors/camera/camera_model.py b/kornia/sensors/camera/camera_model.pyindex b89e32cf4..a90d1262d 100644--- a/kornia/sensors/camera/camera_model.py+++ b/kornia/sensors/camera/camera_model.py@@ -104,12 +104,72 @@ class CameraModelBase:r"""Base class to represent camera models based on distortion and projection types.Distortion is of 3 types:- - Affine- - Brown Conrady- - Kannala Brandt K3+ - 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``Projection is of 2 types:- - Z1- - Orthographic+ - Z1, implemented by :class:`~kornia.sensors.camera.projection_model.Z1Projection`+ - Orthographic, a placeholder that raises ``NotImplementedError``++ Convention:+ - the API is ``Vector``-typed: :meth:`project` takes a ``Vector3`` and returns a ``Vector2``, and+ :meth:`unproject` takes a ``Vector2`` and returns a ``Vector3``. A raw :class:`torch.Tensor` is not+ accepted -- reading a coordinate off it raises ``AttributeError``.+ - ``params`` is a flat parameter vector whose length is fixed by the :class:`CameraModelType`:+ ``[fx, fy, cx, cy]`` for ``PINHOLE`` and ``ORTHOGRAPHIC``, 12 parameters for ``BROWN_CONRADY`` and+ 8 for ``KANNALA_BRANDT_K3``, laid out as each constructor documents. That length is enforced by+ the typed constructors -- :class:`CameraModel` and the :class:`PinholeModel`,+ :class:`BrownConradyModel`, :class:`KannalaBrandtK3` and :class:`Orthographic` subclasses -- which+ accept an unbatched ``(N,)`` vector and a batched :math:`(B, N)` one and raise ``ValueError`` for+ another length or a rank above 2. ``CameraModelBase.__init__`` applies the same check on the direct+ construction path, reading the length off the distortion type -- 4 for+ :class:`~kornia.sensors.camera.distortion_model.AffineTransform`, 12 for ``BrownConradyTransform``+ and 8 for ``KannalaBrandtK3Transform``.+ - :meth:`matrix` and its alias :meth:`K` return the :math:`(*, 3, 3)` intrinsics+ ``[[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``.+ - :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+ the camera-frame ``z``: :class:`~kornia.sensors.camera.projection_model.Z1Projection` multiplies+ the :math:`z = 1` point by it, so the third coordinate of the result is the ``depth`` that was+ passed in, and not a Euclidean ray length.+ - with shared intrinsics ``params.shape == (4,)``, or one point per camera with ``params`` of shape+ ``(B, 4)`` and points of shape ``(B, 3)`` / ``(B, 2)``, the Pinhole path uses the same mathematical+ camera mapping as :doc:`kornia.geometry.camera </geometry.camera>` with ``K`` built from the same+ ``[fx, fy, cx, cy]``.+ However, :meth:`project` divides directly by ``z``, whereas+ :func:`~kornia.geometry.camera.perspective.project_points` multiplies by its reciprocal and skips+ the divide when ``abs(z) <= 1e-8`` (compared in the working dtype). Results can differ by rounding+ away from that threshold and differ substantially at or below it: ``[1, 2, 0]`` yields infinities+ here but finite pixels there. See `#4267 <https://github.com/kornia/kornia/issues/4267>`_.+ :meth:`unproject` corresponds to :func:`~kornia.geometry.camera.perspective.unproject_points`+ with ``normalize=False`` and depth shaped as ``(*, 1)`` there instead of ``(*,)`` here.+ - for point clouds shaped ``(B, N, 3)`` / ``(B, N, 2)``, batched ``(B, 4)`` intrinsics broadcast+ differently: this API applies each ``(B,)`` intrinsic component directly to ``(B, N)`` coordinates,+ aligning it with the point axis. The geometry functions insert a singleton point axis and apply+ intrinsics along the camera batch axis. When ``B == N > 1``, both APIs run but associate the+ intrinsics with different points; with ``B = 2, N = 3``, both :meth:`project` and :meth:`unproject`+ here raise ``RuntimeError`` while the geometry functions support those shapes. Changing only the+ point container and depth shape is therefore insufficient for batched point clouds.+ - pixels use the integer-centre grid described in+ the Convention block on :class:`~kornia.geometry.camera.pinhole.PinholeCamera`. The two type systems+ are kept separate by design -- this one takes ``Vector`` objects, that one plain tensors -- which is+ recorded 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 and pinned by+ ``test_wart_the_three_non_pinhole_models_construct_and_then_raise_4284`` in+ ``tests/sensors/camera/test_camera_model.py``.Example:>>> params = torch.Tensor([328., 328., 320., 240.])@@ -191,16 +251,24 @@ class CameraModelBase:return self._params[..., 3]def matrix(self) -> torch.Tensor:- """Return the camera matrix."""+ """Return the camera matrix.++ See the Convention block on :class:`~kornia.sensors.camera.CameraModelBase`.+ """raise NotImplementedErrordef K(self) -> torch.Tensor:- """Return the camera matrix."""+ """Return the camera matrix.++ See the Convention block on :class:`~kornia.sensors.camera.CameraModelBase`.+ """return self.matrix()def project(self, points: Vector3) -> Vector2:"""Projects 3D points to 2D camera plane.+ See the Convention block on :class:`~kornia.sensors.camera.CameraModelBase`.+Args:points: Vector3 representing 3D points.@@ -220,6 +288,8 @@ class CameraModelBase:def unproject(self, points: Vector2, depth: torch.Tensor) -> Vector3:"""Unprojects 2D points from camera plane to 3D.+ See the Convention block on :class:`~kornia.sensors.camera.CameraModelBase`.+Args:points: Vector2 representing 2D points.depth: Depth of the points.@@ -242,6 +312,8 @@ class CameraModelBase:class PinholeModel(CameraModelBase):r"""Class to represent Pinhole Camera Model.+ See the Convention block on :class:`~kornia.sensors.camera.CameraModelBase`.+The pinhole camera model describes the mathematical relationship betweenthe coordinates of a point in three-dimensional space and its projectiononto the image plane of an ideal pinhole camera,@@ -270,6 +342,8 @@ class PinholeModel(CameraModelBase):def matrix(self) -> torch.Tensor:r"""Return the camera matrix.+ See the Convention block on :class:`~kornia.sensors.camera.CameraModelBase`.+The matrix is of the form:.. math::@@ -296,6 +370,22 @@ class PinholeModel(CameraModelBase):def scale(self, scale_factor: torch.Tensor) -> PinholeModel:"""Scales the camera model by a scale factor.+ Convention:+ - returns a **new** model whose focal lengths, principal point and image size are multiplied by+ ``scale_factor``: ``fx' = s * fx`` and ``cx' = s * cx``, the half-pixel rule, which is the rule+ :meth:`~kornia.geometry.camera.pinhole.PinholeCamera.scale` applies as well.++ .. warning::+ ``cx' = s * cx`` disagrees with the integer pixel centres the rest of the library enumerates, and+ a tensor ``scale_factor`` rebuilds ``image_size`` with 0-dim tensors in the promoted dtype+ (floating for a floating-point factor) where the constructor took python integers -- a python+ ``int`` keeps ``int`` fields and a python ``float`` gives ``float`` ones. Both are tracked in+ `#4263 <https://github.com/kornia/kornia/issues/4263>`_, the second in its comment thread; they+ are documented as they are and pinned by+ ``test_wart_scale_rescales_the_principal_point_by_the_half_pixel_rule_4263`` and+ ``test_wart_scale_turns_the_image_size_fields_into_tensors_4263`` in+ ``tests/sensors/camera/test_camera_model.py``.+Args:scale_factor: Scale factor to scale the camera model.@@ -319,7 +409,17 @@ class PinholeModel(CameraModelBase):class BrownConradyModel(CameraModelBase):- """Brown Conrady Camera Model."""+ """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>`_ and+ pinned by ``test_wart_the_three_non_pinhole_models_construct_and_then_raise_4284`` in+ ``tests/sensors/camera/test_camera_model.py``.+ """def __init__(self, image_size: ImageSize, params: torch.Tensor) -> None:"""Construct BrownConradyModel class.@@ -336,7 +436,17 @@ class BrownConradyModel(CameraModelBase):class KannalaBrandtK3(CameraModelBase):- """Kannala Brandt K3 Camera Model."""+ """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>`_ and+ pinned by ``test_wart_the_three_non_pinhole_models_construct_and_then_raise_4284`` in+ ``tests/sensors/camera/test_camera_model.py``.+ """def __init__(self, image_size: ImageSize, params: torch.Tensor) -> None:"""Construct KannalaBrandtK3 class.@@ -352,7 +462,17 @@ class KannalaBrandtK3(CameraModelBase):class Orthographic(CameraModelBase):- """Orthographic Camera Model."""+ """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>`_ and+ pinned by ``test_wart_the_three_non_pinhole_models_construct_and_then_raise_4284`` in+ ``tests/sensors/camera/test_camera_model.py``.+ """def __init__(self, image_size: ImageSize, params: torch.Tensor) -> None:"""Construct Orthographic class.@@ -373,6 +493,8 @@ CameraModelVariants = Union[PinholeModel, BrownConradyModel, KannalaBrandtK3, Orclass CameraModel:r"""Class to represent camera models.+ See the Convention block on :class:`~kornia.sensors.camera.CameraModelBase`.+Example:>>> # Pinhole Camera Model>>> cam = CameraModel(ImageSize(480, 640), CameraModelType.PINHOLE, torch.Tensor([328., 328., 320., 240.]))diff --git a/kornia/sensors/camera/distortion_model.py b/kornia/sensors/camera/distortion_model.pyindex 03233992a..696b68103 100644--- a/kornia/sensors/camera/distortion_model.py+++ b/kornia/sensors/camera/distortion_model.py@@ -31,6 +31,18 @@ class AffineTransform:def distort(self, params: torch.Tensor, points: Vector2) -> Vector2:"""Distort one or more Vector2 points using the affine transform.+ Convention:+ - ``points`` is on the **normalized** :math:`z = 1` plane and the result is in **pixels**:+ ``u = fx * x + cx`` and ``v = fy * y + cy``, with ``params`` laid out as ``[fx, fy, cx, cy]``.+ Those pixels are on the integer-centre grid described in the Convention block on+ :class:`~kornia.geometry.camera.pinhole.PinholeCamera`.+ - it computes the same values as :func:`~kornia.geometry.camera.distort_points_affine`, which+ takes plain tensors where this method takes ``Vector2``; the two camera type systems are kept+ separate by design, which is recorded in+ `#4274 <https://github.com/kornia/kornia/issues/4274>`_.+ - :meth:`undistort` is the closed-form inverse, one subtraction and one division per axis with no+ iteration.+Args:params: torch.Tensor representing the affine transform parameters.points: Vector2 representing the points to distort.@@ -54,6 +66,11 @@ class AffineTransform:def undistort(self, params: torch.Tensor, points: Vector2) -> Vector2:"""Undistort one or more Vector2 points using the affine transform.+ Convention:+ - ``points`` is in **pixels** and the result is on the normalized :math:`z = 1` plane:+ ``x = (u - cx) / fx`` and ``y = (v - cy) / fy``, the closed-form inverse of :meth:`distort`+ with the same ``params`` layout -- see the Convention block there.+Args:params: torch.Tensor representing the affine transform parameters.points: Vector2 representing the points to undistort.@@ -82,6 +99,16 @@ 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>`_ and pinned by+ ``test_wart_brown_conrady_and_kannala_brandt_transforms_are_placeholders_4284`` in+ ``tests/sensors/camera/test_distortion_model.py``.+ :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).@@ -133,6 +160,16 @@ 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>`_ and pinned by+ ``test_wart_brown_conrady_and_kannala_brandt_transforms_are_placeholders_4284`` in+ ``tests/sensors/camera/test_distortion_model.py``.+ :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:diff --git a/kornia/sensors/camera/projection_model.py b/kornia/sensors/camera/projection_model.pyindex fdf543633..02cacde47 100644--- a/kornia/sensors/camera/projection_model.py+++ b/kornia/sensors/camera/projection_model.py@@ -32,6 +32,19 @@ class Z1Projection:def project(self, points: Vector3) -> Vector2:"""Project one or more Vector3 from the camera frame into the canonical z=1 plane through perspective division.+ Convention:+ - ``points`` is in the **camera frame** and the result is on the normalized :math:`z = 1` plane,+ not in pixels: the map is ``xy / z``, with no epsilon and no validation. A point on the camera+ plane (:math:`z = 0`) therefore projects to an infinity instead of raising -- to ``nan`` on an+ axis whose numerator is zero as well -- and a point behind the camera to a finite coordinate.++ .. warning::+ That :math:`z = 0` answer is one of several that the projection entry points of kornia give for+ the same input; they are collected in `#4267 <https://github.com/kornia/kornia/issues/4267>`_.+ The behaviour above is documented as it is and pinned by+ ``test_wart_project_divides_by_z_with_no_guard_4267`` in+ ``tests/sensors/camera/test_projection_model.py``.+Args:points: Vector3 representing the points to project.@@ -57,6 +70,12 @@ class Z1Projection:def unproject(self, points: Vector2, depth: torch.Tensor | float) -> Vector3:"""Unproject one or more Vector2 from the canonical z=1 plane into the camera frame.+ Convention:+ - ``depth`` is the camera-frame ``z``: the :math:`z = 1` point is multiplied by it, so the third+ coordinate of the result is the ``depth`` that was passed in, and not a Euclidean ray length.+ - a python ``float`` or ``int`` ``depth`` is promoted to a one-element tensor on the device and in+ the dtype of ``points``, so it gives the same result as the tensor spelling of the same value.+Args:points: Vector2 representing the points to unproject.depth: a :class:`torch.Tensor` of shape ``(B,)``, or a python scalar for a single point.@@ -82,6 +101,14 @@ 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>`_ and pinned by+ ``test_wart_orthographic_projection_is_a_placeholder_4284`` in+ ``tests/sensors/camera/test_projection_model.py``.+ :func:`~kornia.geometry.camera.project_points_orthographic` is the implemented equivalent."""def project(self, points: Vector3) -> Vector2:diff --git a/tests/sensors/camera/test_camera_model.py b/tests/sensors/camera/test_camera_model.pyindex 43b450be9..d9919a92d 100644--- a/tests/sensors/camera/test_camera_model.py+++ b/tests/sensors/camera/test_camera_model.py@@ -18,7 +18,8 @@import pytestimport torch-from kornia.geometry.vector import Vector3+from kornia.geometry.camera import project_points, unproject_points+from kornia.geometry.vector import Vector2, Vector3from kornia.image import ImageSizefrom kornia.sensors.camera import CameraModel, CameraModelBase, CameraModelTypefrom kornia.sensors.camera.camera_model import Orthographic@@ -31,6 +32,21 @@ from kornia.sensors.camera.projection_model import OrthographicProjection, Z1Profrom testing.base import BaseTester+# Asymmetric fixture shared by the convention/wart pins below: fx = 100 != fy = 50 and cx = 4 != cy = 3 on a+# non-square 6 x 8 image, so a transposed or swapped reading of the parameter vector changes the literals.+_PARAMS = (100.0, 50.0, 4.0, 3.0)+++def _pinhole(device, dtype, params=_PARAMS):+ """Build the asymmetric PINHOLE ``CameraModel`` the pins below share."""+ return CameraModel(ImageSize(6, 8), CameraModelType.PINHOLE, torch.tensor(params, device=device, dtype=dtype))+++def _k3(device, dtype, params=_PARAMS):+ """Build the (1, 3, 3) ``kornia.geometry.camera`` intrinsics matrix for the same parameters."""+ fx, fy, cx, cy = params+ return torch.tensor([[[fx, 0.0, cx], [0.0, fy, cy], [0.0, 0.0, 1.0]]], device=device, dtype=dtype)+class TestPinholeCamera(BaseTester):def _make_rand_data(self, batch_size, device, dtype):@@ -119,6 +135,332 @@ class TestPinholeCamera(BaseTester):self.assert_close(cam.width * scale, scaled_cam.width)self.assert_close(cam.height * scale, scaled_cam.height)+ def test_convention_projection_matches_geometry_camera_project_points(self, device, dtype):+ # Convention pin (audit labels 5d-sc-01, 5d-sc-02; duplication-ledger row "geometry.camera /+ # sensors.camera", KEEP SEPARATE, kornia#4274): kornia ships two camera type systems and their Pinhole+ # paths share the mathematical mapping through different types. On the shared-intrinsics,+ # exactly representable z=4 fixture below, ``PinholeModel.project`` returns a Vector2 whose data is+ # byte-identical to ``project_points`` with the same K; general depths can differ through rounding.+ # A raw Tensor is rejected with AttributeError rather than accepted (the request in the closed #2708).+ # fx = 100 != fy = 50, cx = 4 != cy = 3 and the point is off-axis, so a transposed reading of the+ # parameter vector moves both components; the second arm changes ONE parameter (fy 50 -> 100) and the+ # v coordinate alone moves, which is what fixes fy as the y-axis scale rather than a shared focal.+ # Snippet used to generate expected: CameraModel(ImageSize(6, 8), CameraModelType.PINHOLE,+ # tensor([100., 50., 4., 3.])).project(Vector3(tensor([[1., 2., 4.]]))).data executed 2026-09-06 on+ # this worktree (torch 2.14.0) -> [[29.0, 28.0]] with torch.equal against project_points True, on cpu+ # for float32, float64, float16 and bfloat16 and on mps for float32 and float16. With fy = 100 the+ # same call gives the audit's [[29.0, 53.0]].+ cam = _pinhole(device, dtype)+ points = torch.tensor([[1.0, 2.0, 4.0]], device=device, dtype=dtype)+ projected = cam.project(Vector3(points))+ assert isinstance(projected, Vector2)+ self.assert_close(projected.data, torch.tensor([[29.0, 28.0]], device=device, dtype=dtype), atol=0.0, rtol=0.0)+ assert torch.equal(projected.data, project_points(points, _k3(device, dtype)))+ symmetric = (100.0, 100.0, 4.0, 3.0)+ square = _pinhole(device, dtype, symmetric).project(Vector3(points))+ self.assert_close(square.data, torch.tensor([[29.0, 53.0]], device=device, dtype=dtype), atol=0.0, rtol=0.0)+ assert torch.equal(square.data, project_points(points, _k3(device, dtype, symmetric)))+ with pytest.raises(AttributeError, match="has no attribute 'z'"):+ cam.project(points)++ # A non-power-of-two depth exposes direct division versus reciprocal multiplication. On CPU+ # float32 at 3ced4c71 (torch 2.14.0), x is 170.66665649414062 here versus 170.6666717529297+ # in project_points. Numerical agreement is approximate; bit identity is not the contract.+ points = torch.tensor([[5.0, 2.0, 3.0]], device=device, dtype=dtype)+ projected = cam.project(Vector3(points)).data+ expected = torch.tensor([[512.0 / 3.0, 109.0 / 3.0]], device=device, dtype=dtype)+ self.assert_close(projected, expected)+ self.assert_close(projected, project_points(points, _k3(device, dtype)))++ @pytest.mark.parametrize("z", [0.0, 1e-9, -1e-9, 1e-8, -1e-8])+ def test_wart_projection_differs_from_geometry_at_small_depth_4267(self, device, dtype, z):+ # Pin the current #4267 policy difference, including the threshold boundary. Retire or update+ # this pin when that policy is repaired. Geometry skips division at abs(z) <= 1e-8; sensors+ # divides unconditionally. In float16 these depths underflow to zero, so expect infinities.+ cam = _pinhole(device, dtype)+ points = torch.tensor([[1.0, 2.0, z]], device=device, dtype=dtype)+ projected = cam.project(Vector3(points)).data+ geometry = project_points(points, _k3(device, dtype))+ expected_geometry = torch.tensor([[104.0, 103.0]], device=device, dtype=dtype)+ self.assert_close(geometry, expected_geometry, atol=0.0, rtol=0.0)+ assert not torch.equal(projected, geometry)+ if points[0, 2] == 0:+ assert torch.isinf(projected).all()+ else:+ assert torch.isfinite(projected).all()+ assert (projected.abs() > 1e9).all()+ assert (projected.sign() == points[0, 2].sign()).all()++ def test_convention_unproject_takes_the_camera_frame_z_as_depth(self, device, dtype):+ # Convention pin (audit labels 5d-sc-03, 5d-sc-40; pre-finding P6): the ``depth`` argument of+ # ``CameraModelBase.unproject`` is the camera-frame z, not a ray length -- it multiplies the z = 1+ # point, so the third component of the result IS the depth that was passed in. On this shared-intrinsics+ # fixture, the result is byte-identical to ``kornia.geometry.camera.unproject_points`` (whose ``normalize``+ # flag would give the ray-length reading instead, and which takes depth as (B, 1) where the sensors API takes+ # it as (B,)). The round trip through project() is not the identity map on the fixture: the projected+ # pixel [[29.0, 28.0]] differs from the first two coordinates [[1.0, 2.0]] of the input, so the+ # equality below is not vacuously true of any pair of inverse functions.+ # Snippet used to generate expected: cam.unproject(Vector2(tensor([[29., 28.]])), tensor([2.])).data+ # and cam.unproject(cam.project(Vector3(X)), X[..., 2]).data executed 2026-09-06 on this worktree+ # (torch 2.14.0) -> [[0.5, 1.0, 2.0]] and [[1.0, 2.0, 4.0]], both torch.equal against+ # unproject_points / against the input, on cpu for float32, float64, float16 and bfloat16 and on mps+ # for float32 and float16.+ cam = _pinhole(device, dtype)+ pixels = torch.tensor([[29.0, 28.0]], device=device, dtype=dtype)+ depth = torch.tensor([2.0], device=device, dtype=dtype)+ unprojected = cam.unproject(Vector2(pixels), depth)+ assert isinstance(unprojected, Vector3)+ expected = torch.tensor([[0.5, 1.0, 2.0]], device=device, dtype=dtype)+ self.assert_close(unprojected.data, expected, atol=0.0, rtol=0.0)+ assert torch.equal(unprojected.data, unproject_points(pixels, depth[:, None], _k3(device, dtype)))+ points = torch.tensor([[1.0, 2.0, 4.0]], device=device, dtype=dtype)+ projected = cam.project(Vector3(points))+ assert not torch.equal(projected.data, points[..., :2])+ assert torch.equal(cam.unproject(projected, points[..., 2]).data, points)++ @pytest.mark.parametrize("shared_intrinsics", [True, False])+ def test_convention_shared_or_paired_intrinsics_match_geometry(self, device, dtype, shared_intrinsics):+ # Shared intrinsics support a point cloud; batched intrinsics agree for one point per camera.+ # These asymmetric values keep both projection and unprojection exactly representable in all dtypes.+ params = torch.tensor([[8.0, 4.0, 1.0, 2.0], [4.0, 8.0, 3.0, 4.0]], device=device, dtype=dtype)+ point_shape = (2, 3) if shared_intrinsics else (2,)+ cam = CameraModel(ImageSize(6, 8), CameraModelType.PINHOLE, params[0] if shared_intrinsics else params)+ points = torch.tensor([1.0, 2.0, 4.0], device=device, dtype=dtype).expand(*point_shape, 3)+ pixels = torch.tensor([9.0, 10.0], device=device, dtype=dtype).expand(*point_shape, 2)+ depth = torch.ones(point_shape, device=device, dtype=dtype)+ expected_projected = torch.tensor([[3.0, 4.0], [4.0, 8.0]], device=device, dtype=dtype)+ expected_unprojected = torch.tensor([[1.0, 2.0, 1.0], [1.5, 0.75, 1.0]], device=device, dtype=dtype)+ if shared_intrinsics:+ expected_projected = expected_projected[0].expand(*point_shape, 2)+ expected_unprojected = expected_unprojected[0].expand(*point_shape, 3)+ projected = cam.project(Vector3(points)).data+ unprojected = cam.unproject(Vector2(pixels), depth).data+ self.assert_close(projected, expected_projected, atol=0.0, rtol=0.0)+ self.assert_close(unprojected, expected_unprojected, atol=0.0, rtol=0.0)+ self.assert_close(projected, project_points(points, cam.matrix()), atol=0.0, rtol=0.0)+ self.assert_close(unprojected, unproject_points(pixels, depth[..., None], cam.matrix()), atol=0.0, rtol=0.0)++ @pytest.mark.parametrize("num_points", [2, 3])+ def test_wart_batched_intrinsics_differ_from_geometry_4274(self, device, dtype, num_points):+ # The two camera APIs discussed in #4274 also differ in broadcasting (PR #4318 review).+ # Sensors aligns (B,) intrinsic components with the trailing axis of (B, N) coordinates;+ # geometry inserts a singleton point axis. With B == N this silently changes camera associations;+ # B = 2, N = 3 instead raises. Pin CURRENT behavior; retire/update if this distinction is repaired.+ # Hand-computed at z=4: camera 0 projects [1, 2, 4] to [3, 4], camera 1 to [4, 8].+ # At unit depth, [9, 10] unprojects to [1, 2, 1] / [1.5, .75, 1], respectively.+ params = torch.tensor([[8.0, 4.0, 1.0, 2.0], [4.0, 8.0, 3.0, 4.0]], device=device, dtype=dtype)+ cam = CameraModel(ImageSize(6, 8), CameraModelType.PINHOLE, params)+ points = torch.tensor([1.0, 2.0, 4.0], device=device, dtype=dtype).expand(2, num_points, 3)+ pixels = torch.tensor([9.0, 10.0], device=device, dtype=dtype).expand(2, num_points, 2)+ depth = torch.ones(2, num_points, device=device, dtype=dtype)+ per_camera_projected = torch.tensor([[3.0, 4.0], [4.0, 8.0]], device=device, dtype=dtype)+ per_camera_unprojected = torch.tensor([[1.0, 2.0, 1.0], [1.5, 0.75, 1.0]], device=device, dtype=dtype)+ geometry_projected = project_points(points, cam.matrix())+ geometry_unprojected = unproject_points(pixels, depth[..., None], cam.matrix())+ self.assert_close(+ geometry_projected, per_camera_projected[:, None].expand(2, num_points, 2), atol=0.0, rtol=0.0+ )+ self.assert_close(+ geometry_unprojected, per_camera_unprojected[:, None].expand(2, num_points, 3), atol=0.0, rtol=0.0+ )+ if num_points == 2:+ projected = cam.project(Vector3(points)).data+ unprojected = cam.unproject(Vector2(pixels), depth).data+ self.assert_close(projected, per_camera_projected[None].expand(2, 2, 2), atol=0.0, rtol=0.0)+ self.assert_close(unprojected, per_camera_unprojected[None].expand(2, 2, 3), atol=0.0, rtol=0.0)+ assert not torch.equal(projected, geometry_projected)+ assert not torch.equal(unprojected, geometry_unprojected)+ else:+ with pytest.raises(RuntimeError, match="size of tensor"):+ cam.project(Vector3(points))+ with pytest.raises(RuntimeError, match="size of tensor"):+ cam.unproject(Vector2(pixels), depth)++ def test_convention_matrix_is_the_three_by_three_intrinsics(self, device, dtype):+ # Convention pin (audit labels 5d-sc-04, 5d-sc-05): ``matrix()`` returns the 3x3 pinhole intrinsics+ # [[fx, 0, cx], [0, fy, cy], [0, 0, 1]] -- the same K that ``kornia.geometry.camera`` takes as an+ # argument, byte-identical, and NOT the 4x4 layout ``kornia.geometry.camera.PinholeCamera`` stores.+ # ``K()`` is an alias of ``matrix()``. Unbatched (4,) params give (3, 3) and (1, 4) params give+ # (1, 3, 3), so the batch axis of the parameters is carried through. fx != fy and cx != cy, so the+ # transpose of this matrix is a different matrix and torch.equal discriminates it.+ # Snippet used to generate expected: cam.matrix() executed 2026-09-06 on this worktree (torch 2.14.0)+ # -> [[100.0, 0.0, 4.0], [0.0, 50.0, 3.0], [0.0, 0.0, 1.0]] with torch.equal against the hand-built K+ # True and shapes (3, 3) / (1, 3, 3), on cpu for float32, float64, float16 and bfloat16 and on mps for+ # float32 and float16.+ cam = _pinhole(device, dtype)+ expected = _k3(device, dtype)+ assert cam.matrix().shape == (3, 3)+ assert torch.equal(cam.matrix(), expected[0])+ assert torch.equal(cam.K(), cam.matrix())+ assert not torch.equal(cam.matrix(), expected[0].transpose(-2, -1))+ batched = CameraModel(+ ImageSize(6, 8), CameraModelType.PINHOLE, torch.tensor([_PARAMS], device=device, dtype=dtype)+ )+ assert batched.matrix().shape == (1, 3, 3)+ assert torch.equal(batched.matrix(), expected)++ def test_wart_scale_rescales_the_principal_point_by_the_half_pixel_rule_4263(self, device, dtype):+ # Wart pin for kornia#4263 (audit labels 5d-sc-06, 5d-sc-07, 5a-al-16; pre-finding P1):+ # ``PinholeModel.scale(s)`` gives cx' = s * cx (2.0 for cx = 4, s = 0.5), the half-pixel / COLMAP+ # rule, although every pixel grid in the library enumerates integer pixel CENTRES, under which the+ # grid-consistent value is s * cx + (s - 1) / 2 = 1.75 for cx and 1.25 for cy. This is one of the four+ # sites #4263 lists; ``PinholeCamera.scale``, ``PinholeCamera.scale_`` and ``scale_pinhole`` apply the+ # same rule and are pinned by the 5a PR (#4294) in tests/geometry/camera/test_pinhole.py -- those+ # pins are not on this branch. cx = 4 != cy = 3 and s = 0.5 != 1, so the two candidate rules differ+ # in both components and by different amounts.+ # Snippet used to generate expected: cam.scale(tensor(0.5)).params executed 2026-09-06 on this+ # worktree (torch 2.14.0) -> [50.0, 25.0, 2.0, 1.5], and the integer-centre rule 0.5 * 4 - 0.25 = 1.75+ # / 0.5 * 3 - 0.25 = 1.25; on cpu for float32, float64, float16 and bfloat16 and on mps for float32+ # and float16.+ # Pins the CURRENT rescale rule; NOT a contract; delete when #4263 is repaired.+ cam = _pinhole(device, dtype)+ scaled = cam.scale(torch.tensor(0.5, device=device, dtype=dtype))+ expected = torch.tensor([50.0, 25.0, 2.0, 1.5], device=device, dtype=dtype)+ self.assert_close(scaled.params, expected, atol=0.0, rtol=0.0)+ integer_centre = torch.tensor([50.0, 25.0, 1.75, 1.25], device=device, dtype=dtype)+ assert not torch.equal(scaled.params, integer_centre)++ def test_wart_scale_turns_the_image_size_fields_into_tensors_4263(self, device, dtype):+ # Wart pin for kornia#4263 (audit label 5d-sc-38): ``PinholeModel.scale`` rebuilds the ImageSize as+ # ``ImageSize(height * scale_factor, width * scale_factor)``, so the python ``int`` height and width+ # that the constructor accepted come back as 0-dim floating tensors on the model's device -- and 3.0+ # / 4.0 rather than the integer pixel counts an ImageSize is meant to hold. #4263's body covers only+ # the principal-point rule of the same method; #4263 records THIS observation in its comment thread+ # (issuecomment-5556356093), where it is stated as a question the repair of that method has to answer+ # -- whether ImageSize keeps python ints -- because both of #4263's Expected outcomes change only+ # what cx' is. So the pin is named for #4263 and is deleted with it, like the sibling pin above.+ # Snippet used to generate expected: (type(cam.image_size.height).__name__,+ # type(cam.scale(tensor(0.5)).image_size.height).__name__, cam.scale(tensor(0.5)).image_size) executed+ # 2026-09-06 on this worktree (torch 2.14.0, cpu float32) -> ('int', 'Tensor',+ # ImageSize(height=tensor(3.), width=tensor(4.))); on mps the two fields carry device='mps:0'.+ # Pins the CURRENT types and values; NOT a contract; delete when #4263 is repaired.+ cam = _pinhole(device, dtype)+ assert isinstance(cam.image_size.height, int)+ assert isinstance(cam.image_size.width, int)+ scaled = cam.scale(torch.tensor(0.5, device=device, dtype=dtype))+ assert isinstance(scaled.image_size.height, torch.Tensor)+ assert isinstance(scaled.image_size.width, torch.Tensor)+ assert scaled.image_size.height.shape == ()+ assert scaled.image_size.height.is_floating_point()+ assert scaled.image_size.height.device == cam.params.device+ self.assert_close(scaled.image_size.height, torch.tensor(3.0, device=device, dtype=dtype), atol=0.0, rtol=0.0)+ self.assert_close(scaled.image_size.width, torch.tensor(4.0, device=device, dtype=dtype), atol=0.0, rtol=0.0)+ # The conversion is a property of the ARGUMENT TYPE, not of ``scale``: ``image_size`` is rebuilt by+ # multiplying the stored fields, so a python number multiplies python numbers and keeps them. The+ # counterexample is in this method's own docstring, whose doctest calls ``cam.scale(2)``. Without+ # these two arms the assertions above would read as "scale() turns the fields into tensors", which is+ # false. Snippet used to generate expected: cam.scale(2).image_size and cam.scale(2.0).image_size+ # executed 2026-09-06 on this worktree (torch 2.14.0) -> ImageSize(height=12, width=16) with int+ # fields and ImageSize(height=12.0, width=16.0) with float fields, on cpu for float32, float64,+ # float16 and bfloat16 and on mps for float32 and float16.+ from_int = cam.scale(2)+ assert isinstance(from_int.image_size.height, int)+ assert isinstance(from_int.image_size.width, int)+ assert (from_int.image_size.height, from_int.image_size.width) == (12, 16)+ from_float = cam.scale(2.0)+ assert isinstance(from_float.image_size.height, float)+ assert isinstance(from_float.image_size.width, float)+ assert (from_float.image_size.height, from_float.image_size.width) == (12.0, 16.0)+ from_tensor = cam.scale(torch.tensor(2.0, device=device, dtype=dtype))+ assert isinstance(from_tensor.image_size.height, torch.Tensor)+ assert isinstance(from_tensor.image_size.width, torch.Tensor)+++class TestCameraModelTypes(BaseTester):+ # The four CameraModelType members and the parameter-vector contract each one enforces. Only PINHOLE is+ # usable; see test_wart_the_three_non_pinhole_models_construct_and_then_raise_4284 below.+ _LENGTHS = (+ (CameraModelType.PINHOLE, 4),+ (CameraModelType.BROWN_CONRADY, 12),+ (CameraModelType.KANNALA_BRANDT_K3, 8),+ (CameraModelType.ORTHOGRAPHIC, 4),+ )++ def test_convention_params_length_is_fixed_per_camera_model_type(self, device, dtype):+ # Convention pin (audit labels 5d-sc-12, 5d-sc-13, 5d-sc-14, 5d-sc-15, 5d-sc-17, 5d-sc-18, 5d-sc-20,+ # 5d-sc-21, 5d-sc-35): ``params`` is a (B, N) tensor whose LAST axis is fixed by the model type --+ # 4 for PINHOLE (fx, fy, cx, cy), 12 for BROWN_CONRADY, 8 for KANNALA_BRANDT_K3 and 4 for ORTHOGRAPHIC+ # -- and any other length raises ValueError. The guard is ``params.shape[-1] != N or+ # len(params.shape) > 2``, so an unbatched (N,) vector and a batched (B, N) one are both accepted+ # while a (B, 1, N) one is rejected with the same message: there is no (B, N, 4) multi-camera form.+ # The rejected lengths are N - 1, one parameter away from the accepted one, rather than a wildly+ # wrong shape. The four enum members and their values are part of the contract because+ # ``CameraModelType`` is what a caller passes.+ # Snippet used to generate expected: CameraModel(ImageSize(6, 8), t, ones(n)) / ones(2, n) /+ # ones(n - 1) / ones(1, 1, n) for each (t, n) executed 2026-09-06 on this worktree (torch 2.14.0) ->+ # shapes (n,) and (2, n) accepted, and ValueError "params must be of shape (B, 4) for PINHOLE Camera",+ # "params must be of shape (B, 12) for BROWN_CONRADY Camera", "params must be of shape B, 8 for+ # KANNALA_BRANDT_K3 Camera", "params must be of shape B, 4 for ORTHOGRAPHIC Camera" for both rejected+ # shapes; on cpu for float32, float64, float16 and bfloat16 and on mps for float32 and float16.+ assert [(m.name, m.value) for m in CameraModelType] == [+ ("PINHOLE", 0),+ ("BROWN_CONRADY", 1),+ ("KANNALA_BRANDT_K3", 2),+ ("ORTHOGRAPHIC", 3),+ ]+ for model_type, length in self._LENGTHS:+ unbatched = CameraModel(ImageSize(6, 8), model_type, torch.ones(length, device=device, dtype=dtype))+ assert unbatched.params.shape == (length,)+ batched = CameraModel(ImageSize(6, 8), model_type, torch.ones(2, length, device=device, dtype=dtype))+ assert batched.params.shape == (2, length)+ with pytest.raises(ValueError, match="params must be of shape"):+ CameraModel(ImageSize(6, 8), model_type, torch.ones(length - 1, device=device, dtype=dtype))+ with pytest.raises(ValueError, match="params must be of shape"):+ CameraModel(ImageSize(6, 8), model_type, torch.ones(1, 1, length, device=device, dtype=dtype))+ # The message names the model type; its shape spelling ("(B, 4)" versus "B, 8") is not part of the+ # contract and is not pinned.+ with pytest.raises(ValueError, match=r"params must be of shape .* for PINHOLE Camera"):+ CameraModel(ImageSize(6, 8), CameraModelType.PINHOLE, torch.ones(1, 1, 4, device=device, dtype=dtype))+ 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.diff --git a/tests/sensors/camera/test_distortion_model.py b/tests/sensors/camera/test_distortion_model.pyindex 74637f95e..e5956e6b5 100644--- a/tests/sensors/camera/test_distortion_model.py+++ b/tests/sensors/camera/test_distortion_model.py@@ -18,8 +18,9 @@import pytestimport torch+from kornia.geometry.camera import distort_points_affinefrom kornia.geometry.vector import Vector2-from kornia.sensors.camera.distortion_model import AffineTransform+from kornia.sensors.camera.distortion_model import AffineTransform, BrownConradyTransform, KannalaBrandtK3Transformfrom testing.base import BaseTester@@ -66,3 +67,73 @@ class TestAffineTransform(BaseTester):params = torch.tensor([[328.0, 328.0, 150.0, 150.0]], device=device, dtype=dtype)expected = torch.tensor([[1.0, 1.0], [1.0, 5.0], [2.0, 4.0], [3.0, 9.0]], device=device, dtype=dtype)self.assert_close(distortion.undistort(params, Vector2(points)).data, expected)++ def test_convention_distort_is_the_affine_map_and_undistort_is_its_exact_inverse(self, device, dtype):+ # Convention pin (audit label 5d-sc-32): ``AffineTransform`` is the pinhole "distortion" -- it is the+ # map from NORMALIZED (z = 1 plane) coordinates to PIXELS, u = fx * x + cx and v = fy * y + cy, with+ # ``params`` laid out as (fx, fy, cx, cy). It agrees byte-for-byte with+ # ``kornia.geometry.camera.distort_points_affine`` (the duplication-ledger row "geometry.camera /+ # sensors.camera", KEEP SEPARATE, kornia#4274), and ``undistort`` is its closed-form inverse -- one+ # subtraction and one division per axis, no iteration. The "exact inverse" in this method's name is+ # scoped to the literals pinned below: on THESE representable points the round trip returns the input+ # bit-for-bit, so atol = rtol = 0 is the right assertion here rather than a rounded one. It is NOT+ # bit-exact in general: over 2000 random float32 draws 1456 differ from the input, by up to 3.9e-06.+ # What the docstring claims, and what this pin checks, is the algebraic inverse, not float exactness.+ # The round trip is non-trivial -- the distorted point [[54.0, 15.5]] is not the input [[0.5, 0.25]]+ # -- and fx = 100 != fy = 50, cx = 4 != cy = 3 with an off-axis point, so swapping either pair+ # changes both components.+ # Snippet used to generate expected: AffineTransform().distort(tensor([100., 50., 4., 3.]),+ # Vector2(tensor([[0.5, 0.25]]))).data and the undistort of that executed 2026-09-06 on this worktree+ # (torch 2.14.0) -> [[54.0, 15.5]] and [[0.5, 0.25]], both torch.equal against distort_points_affine+ # and against the input, on cpu for float32, float64, float16 and bfloat16 and on mps for float32 and+ # float16. With the audit's symmetric fy = 100 the distorted point is [[54.0, 28.0]].+ # Snippet used for the "not in general" figures: 2000 iterations of params = rand(4) * 200 + 1,+ # points = (rand(1, 2) - 0.5) * 4, both float32 from torch.Generator().manual_seed(0), comparing+ # torch.equal(undistort(params, distort(params, points)).data, points) -- executed 2026-09-06 on this+ # worktree (torch 2.14.0, cpu) -> 544 bit-exact, 1456 differing, max abs error 3.934e-06.+ transform = AffineTransform()+ points = torch.tensor([[0.5, 0.25]], device=device, dtype=dtype)+ params = torch.tensor([100.0, 50.0, 4.0, 3.0], device=device, dtype=dtype)+ distorted = transform.distort(params, Vector2(points))+ self.assert_close(distorted.data, torch.tensor([[54.0, 15.5]], device=device, dtype=dtype), atol=0.0, rtol=0.0)+ assert not torch.equal(distorted.data, points)+ assert torch.equal(distorted.data, distort_points_affine(points, params))+ assert torch.equal(transform.undistort(params, distorted).data, points)+ square = torch.tensor([100.0, 100.0, 4.0, 3.0], device=device, dtype=dtype)+ self.assert_close(+ transform.distort(square, Vector2(points)).data,+ torch.tensor([[54.0, 28.0]], device=device, dtype=dtype),+ atol=0.0,+ rtol=0.0,+ )+++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)diff --git a/tests/sensors/camera/test_projection_model.py b/tests/sensors/camera/test_projection_model.pyindex 5843ac862..ba0fa7ec3 100644--- a/tests/sensors/camera/test_projection_model.py+++ b/tests/sensors/camera/test_projection_model.py@@ -19,7 +19,7 @@ import pytestimport torchfrom kornia.geometry.vector import Vector2, Vector3-from kornia.sensors.camera.projection_model import Z1Projection+from kornia.sensors.camera.projection_model import OrthographicProjection, Z1Projectionfrom testing.base import BaseTester@@ -75,6 +75,77 @@ class TestProjection(BaseTester):expected,)+ def test_wart_project_divides_by_z_with_no_guard_4267(self, device, dtype):+ # Wart pin for kornia#4267 (audit labels 5d-sc-27, 5d-sc-28, Y4-05; pre-finding P2):+ # ``Z1Projection.project`` is a plain perspective division ``xy / z`` with no epsilon and no+ # validation, so a point ON the camera plane projects to inf rather than raising, and a point BEHIND+ # the camera projects to a finite pixel with no warning. This is one of the five z-divide entry+ # points #4267 lists, and one of the four different answers the five give at (x, y, z) = (1, 2, 0).+ # For the audit's K = (fx, fy, cx, cy) = (100, 100, 4, 3), which the pixel-space members of the family+ # need and this normalized-space one does not: ``project_points`` masks the divide and returns+ # [[104.0, 203.0]], ``PinholeCamera.project`` masks it on the other side of K and returns+ # [[100.0, 200.0]], ``cam2pixel`` adds 1e-12 to z and returns ~[[1e14, 2e14]], while+ # ``project_points_z1`` and this method return inf. The x and y components of the input differ+ # (1 vs 2) so a swapped reading of the pair is visible in the z = -4 arm.+ # Snippet used to generate expected: Z1Projection().project(Vector3(tensor([[1., 2., 0.]]))).data and+ # the same at z = -4 executed 2026-09-06 on this worktree (torch 2.14.0) -> [[inf, inf]] and+ # [[-0.25, -0.5]], on cpu for float32, float64, float16 and bfloat16 and on mps for float32 and+ # float16.+ # Pins the CURRENT policy; NOT a contract; delete when #4267 is repaired.+ projection = Z1Projection()+ on_plane = projection.project(Vector3(torch.tensor([[1.0, 2.0, 0.0]], device=device, dtype=dtype)))+ assert torch.isinf(on_plane.data).all()+ assert (on_plane.data > 0).all()+ behind = projection.project(Vector3(torch.tensor([[1.0, 2.0, -4.0]], device=device, dtype=dtype)))+ assert torch.isfinite(behind.data).all()+ self.assert_close(behind.data, torch.tensor([[-0.25, -0.5]], device=device, dtype=dtype), atol=0.0, rtol=0.0)+ # The infinity is not the whole answer at z = 0: an axis whose NUMERATOR is also zero computes 0 / 0+ # and comes back nan, so a caller that tests the result with ``isinf`` misses that component. The+ # arm above uses x = 1 != 0 and y = 2 != 0, which is exactly the case that hides this.+ # Snippet used to generate expected: Z1Projection().project(Vector3(tensor([[0., 2., 0.]]))).data+ # executed 2026-09-06 on this worktree (torch 2.14.0) -> [[nan, inf]], on cpu for float32, float64,+ # float16 and bfloat16 and on mps for float32 and float16.+ zero_numerator = projection.project(Vector3(torch.tensor([[0.0, 2.0, 0.0]], device=device, dtype=dtype)))+ assert torch.isnan(zero_numerator.data[..., 0]).all()+ assert torch.isinf(zero_numerator.data[..., 1]).all()+ assert (zero_numerator.data[..., 1] > 0).all()+++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.