Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

docs(geometry): Convention blocks for camera (batch 5a: projection core) (#4294)

Dmytro Mishkin748950799366
diff --git a/CHANGELOG.md b/CHANGELOG.md
index c746a4146..1616aaa42 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -10,6 +10,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Added
+* Documented camera projection-core conventions (`PinholeCamera` frames, integer pixel centres, the two
+ meanings of depth, the `z = 0` policies) and added executable pins for `kornia.geometry.camera`'s
+ projection core, with the known scale-rule, aliasing, guard and legacy-API limitations tracked in
+ dedicated issues. (#4294)
* API reference entries now carry a **Try in browser** badge that links a function, its
`nn.Module` counterpart or a browser model to its interactive page on the kornia.org
playground, so readers can run the operator on a sample image without installing anything.
diff --git a/docs/source/geometry.camera.perspective.rst b/docs/source/geometry.camera.perspective.rst
index 2195ca1a2..7e7d3af55 100644
--- a/docs/source/geometry.camera.perspective.rst
+++ b/docs/source/geometry.camera.perspective.rst
@@ -2,7 +2,7 @@ Perspective Camera
------------------
.. meta::
- :description: The kornia.geometry.camera.perspective module provides functions for 3D point projection and unprojection in perspective camera models. These functions are essential for transforming 3D world coordinates into 2D image plane coordinates and vice versa, enabling advanced computer vision applications like depth estimation and 3D scene reconstruction.
+ :description: The kornia.geometry.camera.perspective module provides functions for 3D point projection and unprojection in perspective camera models. These functions are essential for transforming 3D camera-frame coordinates into 2D image plane coordinates and vice versa, enabling advanced computer vision applications like depth estimation and 3D scene reconstruction.
.. currentmodule:: kornia.geometry.camera.perspective
diff --git a/kornia/geometry/camera/perspective.py b/kornia/geometry/camera/perspective.py
index a111e8f17..e58546ef5 100644
--- a/kornia/geometry/camera/perspective.py
+++ b/kornia/geometry/camera/perspective.py
@@ -29,6 +29,20 @@ from kornia.geometry.conversions import (
def project_points(point_3d: torch.Tensor, camera_matrix: torch.Tensor) -> torch.Tensor:
r"""Project a 3d point onto the 2d camera plane.
+ See the Convention block on :class:`~kornia.geometry.camera.pinhole.PinholeCamera`.
+
+ Convention:
+ - ``point_3d`` is a **camera-frame** point and ``camera_matrix`` the :math:`(*, 3, 3)` ``K``; the
+ function takes no extrinsics, so it does not move between frames.
+ - the input must be at least rank 2: an unbatched :math:`(3,)` point raises :class:`ValueError`
+ although the shape below reads :math:`(*, 3)`.
+ - a point with ``z = 0`` does not raise: the perspective divide is skipped and ``K`` is applied to the
+ undivided point, giving ``fx x + cx``. A point behind the camera is projected just as silently.
+
+ .. warning::
+ The unbatched-input contract is `#4266 <https://github.com/kornia/kornia/issues/4266>`_ and the ``z = 0`` answer
+ `#4267 <https://github.com/kornia/kornia/issues/4267>`_.
+
Args:
point_3d: tensor containing the 3d points to be projected
to the camera plane. The shape of the tensor can be :math:`(*, 3)`.
@@ -61,9 +75,18 @@ def unproject_points(
Transform coordinates in the pixel frame to the camera frame.
+ See the Convention block on :class:`~kornia.geometry.camera.pinhole.PinholeCamera`.
+
+ Convention:
+ - ``point_2d`` is a pixel coordinate and the result is in the **camera** frame: the function takes no
+ extrinsics, so it cannot return world coordinates.
+ :meth:`~kornia.geometry.camera.pinhole.PinholeCamera.unproject` is the world-frame counterpart.
+ - ``depth`` is the camera-frame ``z`` of the result. With ``normalize=True`` it is read as the
+ Euclidean ray length instead, so the result has that norm and a smaller ``z``.
+
Args:
- point_2d: tensor containing the 2d to be projected to
- world coordinates. The shape of the tensor can be :math:`(*, 2)`.
+ point_2d: tensor containing the 2d points to be projected to
+ the camera frame. The shape of the tensor can be :math:`(*, 2)`.
depth: tensor containing the depth value of each 2d
points. The tensor shape must be equal to point2d :math:`(*, 1)`.
camera_matrix: tensor containing the intrinsics camera
@@ -73,7 +96,7 @@ def unproject_points(
ray length from the camera position.
Returns:
- tensor of (x, y, z) world coordinates with shape :math:`(*, 3)`.
+ tensor of (x, y, z) camera coordinates with shape :math:`(*, 3)`.
Example:
>>> _ = torch.manual_seed(0)
diff --git a/kornia/geometry/camera/pinhole.py b/kornia/geometry/camera/pinhole.py
index a05276ed6..6191bad5b 100644
--- a/kornia/geometry/camera/pinhole.py
+++ b/kornia/geometry/camera/pinhole.py
@@ -28,11 +28,52 @@ from kornia.geometry.linalg import inverse_transformation, transform_points
class PinholeCamera:
r"""Class that represents a Pinhole Camera model.
+ Convention:
+ - ``intrinsics`` is the :math:`(B, 4, 4)` calibration matrix whose top-left :math:`3 \times 3` block is
+ ``[[fx, 0, cx], [0, fy, cy], [0, 0, 1]]``, and ``extrinsics`` the :math:`(B, 4, 4)` **world-to-camera**
+ transform ``[R | t]`` (OpenCV / COLMAP semantics): :meth:`project` takes **world** points, computes
+ ``K (R X + t)`` and returns pixels, while :meth:`unproject` inverts that step -- it takes pixels and a
+ camera-frame depth and returns **world** points. The functional API takes a ``K`` and no
+ extrinsics, so it works in the **camera** frame:
+ :func:`~kornia.geometry.camera.perspective.project_points` and
+ :func:`~kornia.geometry.camera.perspective.unproject_points` take a :math:`(*, 3, 3)` ``K``, while
+ :func:`~kornia.geometry.depth.depth_to_3d`, :func:`~kornia.geometry.depth.depth_to_3d_v2`,
+ :func:`~kornia.geometry.depth.unproject_meshgrid` and
+ :func:`~kornia.geometry.depth.depth_to_normals` need it **batched**, :math:`(B, 3, 3)`.
+ - pixel coordinates are ``(u, v)`` = ``(x, y)`` = (column, row) with **integer pixel centres**: pixel
+ ``(0, 0)`` is centred at ``(0, 0)``, which is what :func:`~kornia.geometry.grid.create_meshgrid`
+ enumerates, so a centred image has its principal point at ``cx = (W - 1) / 2``, ``cy = (H - 1) / 2``.
+ A half-pixel convention, which places the pixel *corner* at the origin (COLMAP), reports the same
+ principal point half a pixel larger on each axis. See :doc:`/get-started/conventions`.
+ - ``depth`` is the camera-frame ``z`` coordinate. The ``normalize`` argument of
+ :func:`~kornia.geometry.camera.perspective.unproject_points` and the ``normalize_points`` flags of
+ :func:`~kornia.geometry.depth.depth_to_3d` and :func:`~kornia.geometry.depth.depth_to_3d_v2` read it
+ as the Euclidean ray length instead, so the unprojected point has that norm rather than that ``z``.
+ - the class stores the tensors it is constructed from instead of copying them: :meth:`scale` returns a
+ new camera that **shares** ``extrinsics`` with the source, and :meth:`scale_` and the ``tx`` / ``ty``
+ / ``tz`` setters write into the caller's tensors. :meth:`clone` is the only deep copy.
+
+ .. warning::
+ :meth:`scale` and :meth:`scale_` rescale the principal point as ``cx' = s * cx`` β€” the half-pixel rule β€”
+ which disagrees with the integer pixel centres above; it is tracked as a coordinated repair in
+ `#4263 <https://github.com/kornia/kornia/issues/4263>`_. The shared storage is
+ `#4264 <https://github.com/kornia/kornia/issues/4264>`_, the in-place :meth:`scale_` failure on an
+ integer ``height`` / ``width`` with a floating-point scale factor
+ `#4265 <https://github.com/kornia/kornia/issues/4265>`_, the shape
+ guards that admit an ``intrinsics`` whose projection is meaningless
+ `#4266 <https://github.com/kornia/kornia/issues/4266>`_, and the rejection of an empty batch
+ (:math:`B = 0`) `#4281 <https://github.com/kornia/kornia/issues/4281>`_. The behaviour described here is
+ documented as it is and pinned by the ``test_convention_*`` / ``test_wart_*`` tests in
+ ``tests/geometry/camera/test_pinhole.py``.
+
Args:
intrinsics: torch.Tensor with shape :math:`(B, 4, 4)`
- containing the full 4x4 camera calibration matrix.
+ containing the full 4x4 camera calibration matrix. The constructor rejects it when it is neither
+ rank 3 nor rank 4 **and** its last two dimensions are not 4x4, so a :math:`(B, 3, 3)` matrix is
+ accepted, as is an unbatched :math:`(4, 4)` matrix, although :meth:`project` needs
+ the documented :math:`(B, 4, 4)`.
extrinsics: torch.Tensor with shape :math:`(B, 4, 4)`
- containing the full 4x4 rotation-translation matrix.
+ containing the full 4x4 rotation-translation matrix, checked by the same predicate.
height: torch.Tensor with shape :math:`(B)` containing the image height.
width: torch.Tensor with shape :math:`(B)` containing the image width.
@@ -253,7 +294,10 @@ class PinholeCamera:
return self.extrinsics[..., :3, -1:]
def clone(self) -> "PinholeCamera":
- r"""Return a deep copy of the current object instance."""
+ r"""Return a deep copy of the current object instance.
+
+ See the Convention block on :class:`~kornia.geometry.camera.pinhole.PinholeCamera`.
+ """
height: torch.Tensor = self.height.clone()
width: torch.Tensor = self.width.clone()
intrinsics: torch.Tensor = self.intrinsics.clone()
@@ -261,7 +305,9 @@ class PinholeCamera:
return PinholeCamera(intrinsics, extrinsics, height, width)
def intrinsics_inverse(self) -> torch.Tensor:
- r"""Return the inverse of the 4x4 instrisics matrix.
+ r"""Return the inverse of the 4x4 intrinsics matrix.
+
+ See the Convention block on :class:`~kornia.geometry.camera.pinhole.PinholeCamera`.
Returns:
torch.Tensor of shape :math:`(B, 4, 4)`.
@@ -272,6 +318,20 @@ class PinholeCamera:
def scale(self, scale_factor: torch.Tensor) -> "PinholeCamera":
r"""Scale the pinhole model.
+ Convention:
+ - returns a **new** camera whose focal lengths, principal point and image size are multiplied by
+ ``scale_factor``: ``fx' = s * fx`` and ``cx' = s * cx``, the half-pixel rule.
+ - the new camera **shares** its ``extrinsics`` tensor with the source, so writing ``tx`` / ``ty`` /
+ ``tz`` on either camera moves both; the intrinsics are cloned. :meth:`clone` is the deep copy.
+ - with a floating-point ``scale_factor``, an integer ``height`` / ``width`` is promoted to floating
+ point, unlike :meth:`scale_`. An integer factor preserves the integer image-size dtype.
+
+ .. warning::
+ The ``cx' = s * cx`` rule disagrees with the integer pixel centres the rest of the library
+ enumerates; it is tracked as a coordinated repair in
+ `#4263 <https://github.com/kornia/kornia/issues/4263>`_. The shared ``extrinsics`` are
+ `#4264 <https://github.com/kornia/kornia/issues/4264>`_.
+
Args:
scale_factor: a torch.Tensor with the scale factor. It has
to be broadcastable with class members. The expected shape is
@@ -295,6 +355,23 @@ class PinholeCamera:
def scale_(self, scale_factor: Union[float, torch.Tensor]) -> "PinholeCamera":
r"""Scale the pinhole model in-place.
+ Convention:
+ - applies the same rescaling as :meth:`scale` in place and returns ``self``. The camera stores the
+ tensors it was constructed from, so the caller's ``intrinsics``, ``height`` and ``width`` are
+ written into as well.
+ - with a floating-point ``scale_factor``, writing back into an integer ``height`` / ``width`` raises
+ :class:`RuntimeError` where :meth:`scale` promotes it to floating point. An integer factor
+ succeeds. The focal lengths and principal point have already been scaled when the error is
+ raised, including in the caller's intrinsics tensor: the camera is left partially scaled.
+ If ``height`` is integer, both image dimensions are unchanged; if only ``width`` is integer,
+ ``height`` has already been scaled too.
+
+ .. warning::
+ The failure on an integer image size with a floating-point scale factor is tracked in
+ `#4265 <https://github.com/kornia/kornia/issues/4265>`_, the write-through to the caller's tensors
+ in `#4264 <https://github.com/kornia/kornia/issues/4264>`_, and the principal-point rule shared
+ with :meth:`scale` in `#4263 <https://github.com/kornia/kornia/issues/4263>`_.
+
Args:
scale_factor: a torch.Tensor with the scale factor. It has
to be broadcastable with class members. The expected shape is
@@ -317,6 +394,18 @@ class PinholeCamera:
def project(self, point_3d: torch.Tensor) -> torch.Tensor:
r"""Project a 3d point in world coordinates onto the 2d camera plane.
+ See the Convention block on :class:`~kornia.geometry.camera.pinhole.PinholeCamera`.
+
+ Convention:
+ - ``point_3d`` must be at least rank 2: an unbatched :math:`(3,)` point raises :class:`IndexError`
+ although the shape below reads :math:`(*, 3)`. An empty point set returns an empty result.
+ - a point whose **camera-frame** ``z`` is 0 does not raise: ``K`` is applied first and the
+ perspective divide is then skipped, so the result is the undivided ``K (R X + t)``.
+
+ .. warning::
+ The unbatched-input contract is `#4266 <https://github.com/kornia/kornia/issues/4266>`_ and the
+ ``z = 0`` answer `#4267 <https://github.com/kornia/kornia/issues/4267>`_.
+
Args:
point_3d: torch.Tensor containing the 3d points to be projected
to the camera plane. The shape of the torch.Tensor can be :math:`(*, 3)`.
@@ -344,6 +433,8 @@ class PinholeCamera:
Transform coordinates in the pixel frame to the world frame.
+ See the Convention block on :class:`~kornia.geometry.camera.pinhole.PinholeCamera`.
+
Args:
point_2d: torch.Tensor containing the 2d to be projected to
world coordinates. The shape of the torch.Tensor can be :math:`(*, 2)`.
@@ -389,10 +480,17 @@ class PinholeCamera:
) -> "PinholeCamera":
r"""Construct a batched pinhole camera from scalar parameter tensors.
+ See the Convention block on :class:`~kornia.geometry.camera.pinhole.PinholeCamera`.
+
This helper allocates batched :math:`4 \times 4` intrinsic and
extrinsic matrices, fills focal lengths/principal point/translation,
and wraps them into a :class:`PinholeCamera` instance.
+ Convention:
+ - every parameter, including ``height`` and ``width``, is broadcast over ``batch_size``.
+ - ``height`` and ``width`` are stored as floating-point tensors of the requested ``dtype``, so the
+ camera it builds can be scaled in place.
+
Args:
fx: Horizontal focal length per batch element.
fy: Vertical focal length per batch element.
@@ -490,9 +588,24 @@ class PinholeCamerasList(PinholeCamera):
def pinhole_matrix(pinholes: torch.Tensor, eps: float = 1e-6) -> torch.Tensor:
r"""Return the pinhole matrix from a pinhole model.
+ See the Convention block on :class:`~kornia.geometry.camera.pinhole.PinholeCamera`.
+
+ Convention:
+ - ``pinholes`` is the legacy 12-vector layout
+ ``(fx, fy, cx, cy, height, width, rx, ry, rz, tx, ty, tz)``, where ``(rx, ry, rz)`` is an angle-axis
+ rotation and ``(tx, ty, tz)`` a translation; only the first four entries are read here.
+ - an input that is not :math:`(N, 12)` raises :class:`AssertionError` carrying the offending shape,
+ not a :class:`~kornia.core.exceptions.ShapeError`.
+
.. note::
- This method is going to be deprecated in version 0.2 in favour of
- :attr:`kornia.PinholeCamera.camera_matrix`.
+ Superseded by :class:`~kornia.geometry.camera.pinhole.PinholeCamera` and its ``camera_matrix`` property.
+
+ .. warning::
+ The output is built as ``eye(4) + eps`` before the parameters are written, so in ``float32`` and
+ ``float64`` every remaining entry β€” the structural zeros and ones alike β€” carries ``eps``; ``eps=0.0``
+ returns the exact matrix. This legacy 12-vector API is also exported nowhere and appears on no
+ API-reference page, so this docstring renders nowhere. Tracked in
+ `#4268 <https://github.com/kornia/kornia/issues/4268>`_.
Args:
pinholes: torch.Tensor of pinhole models.
@@ -533,9 +646,24 @@ def pinhole_matrix(pinholes: torch.Tensor, eps: float = 1e-6) -> torch.Tensor:
def inverse_pinhole_matrix(pinhole: torch.Tensor, eps: float = 1e-6) -> torch.Tensor:
r"""Return the inverted pinhole matrix from a pinhole model.
+ See the Convention block on :class:`~kornia.geometry.camera.pinhole.PinholeCamera`.
+
+ Convention:
+ - ``pinhole`` is the legacy 12-vector layout
+ ``(fx, fy, cx, cy, height, width, rx, ry, rz, tx, ty, tz)``, where ``(rx, ry, rz)`` is an angle-axis
+ rotation and ``(tx, ty, tz)`` a translation; only the first four entries are read here.
+ - an input that is not :math:`(N, 12)` raises :class:`AssertionError` carrying the offending shape,
+ not a :class:`~kornia.core.exceptions.ShapeError`.
+
.. note::
- This method is going to be deprecated in version 0.2 in favour of
- :attr:`kornia.PinholeCamera.intrinsics_inverse()`.
+ Superseded by :meth:`~kornia.geometry.camera.pinhole.PinholeCamera.intrinsics_inverse`.
+
+ .. warning::
+ The focal lengths are inverted as ``1 / (fx + eps)``, which inverts a perturbed matrix rather than the
+ one ``pinhole_matrix`` returns. With the default ``eps``, a zero focal length gives a large finite
+ number in ``float32``, ``float64`` and ``bfloat16``, or ``inf`` in ``float16``, rather than raising.
+ This legacy 12-vector API is also exported nowhere and appears on no API-reference page, so
+ this docstring renders nowhere. Tracked in `#4268 <https://github.com/kornia/kornia/issues/4268>`_.
Args:
pinhole: torch.Tensor with pinhole models.
@@ -577,8 +705,8 @@ def scale_pinhole(pinholes: torch.Tensor, scale: torch.Tensor) -> torch.Tensor:
r"""Scale the pinhole matrix for each pinhole model.
.. note::
- This method is going to be deprecated in version 0.2 in favour of
- :attr:`kornia.PinholeCamera.scale()`.
+ Superseded by :meth:`~kornia.geometry.camera.pinhole.PinholeCamera.scale`.
+ This legacy 12-vector API is tracked in `#4268 <https://github.com/kornia/kornia/issues/4268>`_.
Args:
pinholes: torch.Tensor with the pinhole model.
@@ -612,6 +740,11 @@ def scale_pinhole(pinholes: torch.Tensor, scale: torch.Tensor) -> torch.Tensor:
def get_optical_pose_base(pinholes: torch.Tensor) -> torch.Tensor:
"""Compute extrinsic transformation matrices for pinholes.
+ .. warning::
+ This function validates its input and then always raises :class:`NotImplementedError`: the
+ ``rtvec_to_pose`` helper it needs does not exist in kornia. Tracked in
+ `#4283 <https://github.com/kornia/kornia/issues/4283>`_.
+
Args:
pinholes: torch.Tensor of form [fx fy cx cy h w rx ry rz tx ty tz]
of size (N, 12).
@@ -651,6 +784,11 @@ def homography_i_H_ref(pinhole_i: torch.Tensor, pinhole_ref: torch.Tensor) -> to
H_{ref}^{i} = K_{i} * T_{ref}^{i} * K_{ref}^{-1}
+ .. warning::
+ This function validates its input and then always raises :class:`NotImplementedError`: it calls
+ ``get_optical_pose_base``, which is unimplemented. Tracked in
+ `#4283 <https://github.com/kornia/kornia/issues/4283>`_.
+
Args:
pinhole_i: torch.Tensor with pinhole model for ith frame.
pinhole_ref: torch.Tensor with pinhole model for reference frame.
@@ -686,6 +824,22 @@ def homography_i_H_ref(pinhole_i: torch.Tensor, pinhole_ref: torch.Tensor) -> to
def pixel2cam(depth: torch.Tensor, intrinsics_inv: torch.Tensor, pixel_coords: torch.Tensor) -> torch.Tensor:
r"""Transform coordinates in the pixel frame to the camera frame.
+ See the Convention block on :class:`~kornia.geometry.camera.pinhole.PinholeCamera`.
+
+ Convention:
+ - ``intrinsics_inv`` is a :math:`(B, 4, 4)` inverse calibration matrix β€” the layout of
+ :class:`~kornia.geometry.camera.pinhole.PinholeCamera`, not the :math:`(*, 3, 3)` ``K`` the functional API
+ takes β€” and ``depth`` is the camera-frame ``z`` at each pixel of the ``(u, v, 1)`` grid.
+ - ``intrinsics_inv`` is checked for rank 3 alone, so a :math:`(B, 3, 3)` inverse passes the check and
+ fails further in with an unrelated message.
+ - ``depth`` must have shape ``Bx1xHxW``; multi-channel depth raises :class:`ValueError`.
+ The ``pixel_coords`` guard raises when the input is not rank 4 **and** its fourth dimension is 3;
+ for lower ranks, accessing that dimension can itself raise :class:`IndexError`.
+
+ .. warning::
+ The rank-only ``intrinsics_inv`` check and the incorrect ``pixel_coords`` predicate are tracked in
+ `#4266 <https://github.com/kornia/kornia/issues/4266>`_.
+
Args:
depth: the source depth maps. Shape must be Bx1xHxW.
intrinsics_inv: the inverse intrinsics camera matrix. Shape must be Bx4x4.
@@ -712,6 +866,26 @@ def pixel2cam(depth: torch.Tensor, intrinsics_inv: torch.Tensor, pixel_coords: t
def cam2pixel(cam_coords_src: torch.Tensor, dst_proj_src: torch.Tensor, eps: float = 1e-12) -> torch.Tensor:
r"""Transform coordinates in the camera frame to the pixel frame.
+ See the Convention block on :class:`~kornia.geometry.camera.pinhole.PinholeCamera`.
+
+ Convention:
+ - ``dst_proj_src`` is a :math:`(B, 4, 4)` projection matrix β€” the layout of
+ :class:`~kornia.geometry.camera.pinhole.PinholeCamera`, not the :math:`(*, 3, 3)` ``K`` the functional API
+ takes β€” and the result is ``(u, v)`` pixel coordinates in the destination frame.
+ - the projection guard raises exactly when ``dst_proj_src`` is not rank 3 **and** its trailing
+ dimensions are :math:`(4, 4)`. Thus an unbatched :math:`(4, 4)` matrix raises at the guard, while
+ a :math:`(B, 3, 3)` matrix passes and fails later inside ``transform_points``. The coordinate guard
+ similarly raises when the input is not rank 4 **and** its fourth dimension is 3; for lower ranks,
+ accessing that dimension can itself raise :class:`IndexError`.
+ - the perspective division is ``x / (z + eps)`` rather than a guarded divide. With the default ``eps``,
+ a projected coordinate ``x = 100, z = 0`` gives about ``1e14`` in ``float32``, ``float64`` and
+ ``bfloat16``, and ``inf`` in ``float16`` (where ``eps`` rounds to zero). A zero numerator then gives
+ zero in the former dtypes and ``nan`` in ``float16``; ``eps`` also biases small nonzero depths.
+
+ .. warning::
+ The incorrect shape predicates are tracked in `#4266 <https://github.com/kornia/kornia/issues/4266>`_, and the
+ ``z = 0`` answer in `#4267 <https://github.com/kornia/kornia/issues/4267>`_.
+
Args:
cam_coords_src: (x, y, z) coordinates defined in the first camera coordinates system. Shape must be BxHxWx3.
dst_proj_src: the projection matrix between the
diff --git a/kornia/geometry/camera/projection_orthographic.py b/kornia/geometry/camera/projection_orthographic.py
index 1551d3533..829c0190e 100644
--- a/kornia/geometry/camera/projection_orthographic.py
+++ b/kornia/geometry/camera/projection_orthographic.py
@@ -54,6 +54,10 @@ def unproject_points_orthographic(points_in_camera: torch.Tensor, extension: tor
\begin{bmatrix} x \\ y \\ z \end{bmatrix} =
\begin{bmatrix} u \\ v \\ w \end{bmatrix}
+ Convention:
+ - ``extension`` becomes the ``z`` component of the result, and the guard compares its rank with the
+ rank of the points, so both a ``(N,)`` and a ``(N, 1)`` extension are accepted.
+
Args:
points_in_camera: torch.Tensor representing the points to unproject with shape (..., 2).
extension: torch.Tensor representing the extension of the points to unproject with shape (..., 1).
diff --git a/kornia/geometry/camera/projection_z1.py b/kornia/geometry/camera/projection_z1.py
index 3df297dfb..b3f7d41ec 100644
--- a/kornia/geometry/camera/projection_z1.py
+++ b/kornia/geometry/camera/projection_z1.py
@@ -41,6 +41,21 @@ def project_points_z1(points_in_camera: torch.Tensor) -> torch.Tensor:
If this is not the case, the points will be projected to the canonical plane, but the resulting
points will be behind the camera and causing numerical issues for z == 0.
+ Convention:
+ - the input is a **camera-frame** point and the output its position on the canonical ``z = 1`` plane,
+ which is a normalized coordinate rather than a pixel. Well away from the ``1e-8`` homogeneous-depth
+ threshold, applying a ``K`` to it with
+ :func:`~kornia.geometry.conversions.denormalize_points_with_intrinsics` approximately gives the pixel
+ that :func:`~kornia.geometry.camera.perspective.project_points` returns. At ``abs(z) <= 1e-8``,
+ :func:`~kornia.geometry.camera.perspective.project_points` skips its divide while this function does not.
+ - the ``z > 0`` precondition above is not validated. At ``z = 0``, each output component is ``inf``,
+ ``-inf``, or ``nan`` according to its numerator; in particular, a zero numerator gives ``nan``.
+
+ .. warning::
+ Returning component-dependent infinities or ``nan`` is one of several answers this namespace gives at
+ ``z = 0``. Tracked in
+ `#4267 <https://github.com/kornia/kornia/issues/4267>`_.
+
Args:
points_in_camera: torch.Tensor representing the points to project with shape (..., 3).
@@ -66,6 +81,14 @@ def unproject_points_z1(
\begin{bmatrix} x \\ y \\ z \end{bmatrix} =
\begin{bmatrix} u \\ v \end{bmatrix} \cdot w
+ Convention:
+ - ``extension`` is the camera-frame ``z`` of the unprojected point: the canonical point is multiplied
+ by it and it becomes the third component.
+ :meth:`~kornia.sensors.camera.projection_model.Z1Projection.unproject` names the same argument
+ ``depth``.
+ - the guard compares the rank of ``extension`` with the rank of the points. Both ``(...,)`` and
+ ``(..., 1)`` extensions are accepted when their leading dimensions match those of the points.
+
Args:
points_in_cam_canonical: torch.Tensor representing the points to unproject with shape (..., 2).
extension: torch.Tensor representing the extension (depth) of the points to unproject with shape
@@ -112,6 +135,13 @@ def dx_project_points_z1(points_in_camera: torch.Tensor) -> torch.Tensor:
If this is not the case, the points will be projected to the canonical plane, but the resulting
points will be behind the camera and causing numerical issues for z == 0.
+ Convention:
+ - the result is the full Jacobian of :func:`~kornia.geometry.camera.project_points_z1` with shape
+ ``(..., 2, 3)``, laid out row-major in the output index: the ``u`` row then the ``v`` row, each
+ holding the derivatives with respect to ``x``, ``y`` and ``z``. It agrees with
+ :func:`torch.autograd.functional.jacobian`.
+ - the same ``z > 0`` precondition applies, and it is not validated either.
+
Args:
points_in_camera: torch.Tensor representing the points to project with shape (..., 3).
diff --git a/tests/geometry/camera/test_perspective.py b/tests/geometry/camera/test_perspective.py
index 2c2bd6d60..efe47606e 100644
--- a/tests/geometry/camera/test_perspective.py
+++ b/tests/geometry/camera/test_perspective.py
@@ -66,6 +66,64 @@ class TestProjectPoints(BaseTester):
op_jit = torch.jit.script(op)
self.assert_close(op(points_3d, camera_matrix), op_jit(points_3d, camera_matrix))
+ def test_wart_project_points_skips_the_divide_at_z_zero_4267(self, device, dtype):
+ # Wart pin for kornia#4267: convert_points_from_homogeneous masks
+ # |z| <= 1e-8 to a divisor of 1 and project_points applies K AFTER that divide, so a point on the camera
+ # plane projects to fx*x + cx = 104, fy*y + cy = 203 instead of raising or returning inf. Four other
+ # entry points answer differently at the same input: PinholeCamera.project gives [[100, 200]],
+ # project_points_z1 and Z1Projection.project give inf, cam2pixel gives a finite 1e14.
+ # A point BEHIND the camera is projected just as silently: z = -4 gives [[-21, -47]].
+ # Snippet used to generate expected: project_points([[1., 2., 0.]], K3) executed 2026-09-05 (torch 2.14.0,
+ # cpu and mps, every dtype). Pins the CURRENT value; NOT a contract; delete when #4267 is repaired.
+ camera_matrix = torch.tensor(
+ [[[100.0, 0.0, 4.0], [0.0, 100.0, 3.0], [0.0, 0.0, 1.0]]], device=device, dtype=dtype
+ )
+ singular = torch.tensor([[1.0, 2.0, 0.0]], device=device, dtype=dtype)
+ out = kornia.geometry.camera.project_points(singular, camera_matrix)
+ self.assert_close(out, torch.tensor([[104.0, 203.0]], device=device, dtype=dtype), atol=0.0, rtol=0.0)
+ behind = kornia.geometry.camera.project_points(
+ torch.tensor([[1.0, 2.0, -4.0]], device=device, dtype=dtype), camera_matrix
+ )
+ self.assert_close(behind, torch.tensor([[-21.0, -47.0]], device=device, dtype=dtype), atol=0.0, rtol=0.0)
+
+ def test_convention_integer_pixel_centres_put_the_principal_point_at_w_minus_one_half(self, device, dtype):
+ # Convention pin for the anchor block on PinholeCamera: pixel
+ # coordinates are (u, v) = (column, row) with INTEGER pixel centres -- create_meshgrid enumerates
+ # [0, 0] for the first pixel and [W - 1, H - 1] for the last -- so a centred image has its principal
+ # point at cx = (W - 1) / 2, cy = (H - 1) / 2, and NOT at (W / 2, H / 2), the half-pixel/COLMAP value.
+ # The pin uses H = 2 != W = 3 so a transposed reading of the convention changes every literal, and
+ # checks the definition of "centred" directly: under cx = 1, cy = 0.5 the first and the last pixel
+ # unproject to exact negatives of each other, and the principal point itself is where the optical axis
+ # (0, 0, 1) lands. A half-pixel cx = 1.5, cy = 1.0 would put neither of those where they are here.
+ # Snippet used to generate expected: create_meshgrid(2, 3, normalized_coordinates=False) and the three
+ # calls below executed 2026-09-05 (torch 2.14.0, cpu and mps, every dtype)
+ # -> grid [[0, 0], [1, 0], [2, 0], [0, 1], [1, 1], [2, 1]], unproject [[-1, -0.5, 1]] and [[1, 0.5, 1]],
+ # project [[1.0, 0.5]]. Every literal is a dyadic rational, so the comparisons are exact.
+ grid = kornia.geometry.create_meshgrid(2, 3, normalized_coordinates=False, device=device, dtype=dtype)
+ assert grid.shape == (1, 2, 3, 2)
+ flat = grid.reshape(-1, 2)
+ first, last = flat[0][None], flat[-1][None]
+ self.assert_close(first, torch.tensor([[0.0, 0.0]], device=device, dtype=dtype), atol=0.0, rtol=0.0)
+ self.assert_close(last, torch.tensor([[2.0, 1.0]], device=device, dtype=dtype), atol=0.0, rtol=0.0)
+ # cx = (3 - 1) / 2 = 1, cy = (2 - 1) / 2 = 0.5, fx = fy = 1.
+ camera_matrix = torch.tensor([[[1.0, 0.0, 1.0], [0.0, 1.0, 0.5], [0.0, 0.0, 1.0]]], device=device, dtype=dtype)
+ depth = torch.tensor([[1.0]], device=device, dtype=dtype)
+ unprojected_first = kornia.geometry.camera.unproject_points(first, depth, camera_matrix)
+ unprojected_last = kornia.geometry.camera.unproject_points(last, depth, camera_matrix)
+ self.assert_close(
+ unprojected_first, torch.tensor([[-1.0, -0.5, 1.0]], device=device, dtype=dtype), atol=0.0, rtol=0.0
+ )
+ self.assert_close(
+ unprojected_last, torch.tensor([[1.0, 0.5, 1.0]], device=device, dtype=dtype), atol=0.0, rtol=0.0
+ )
+ # The two are exact negatives in x and y, which is what "centred" means under integer pixel centres.
+ self.assert_close(unprojected_first[..., :2], -unprojected_last[..., :2], atol=0.0, rtol=0.0)
+ # The optical axis lands exactly on the principal point.
+ on_axis = kornia.geometry.camera.project_points(
+ torch.tensor([[0.0, 0.0, 1.0]], device=device, dtype=dtype), camera_matrix
+ )
+ self.assert_close(on_axis, torch.tensor([[1.0, 0.5]], device=device, dtype=dtype), atol=0.0, rtol=0.0)
+
class TestUnprojectPoints(BaseTester):
def test_smoke(self, device, dtype):
@@ -129,3 +187,21 @@ class TestUnprojectPoints(BaseTester):
op = kornia.geometry.camera.unproject_points
op_jit = torch.jit.script(op)
self.assert_close(op(*args), op_jit(*args))
+
+ def test_convention_normalize_makes_depth_the_ray_length(self, device, dtype):
+ # Convention pin: ``depth`` is the CAMERA-frame z by default, so pixel
+ # (29, 53) at depth 2 unprojects to (0.5, 1, 2); with ``normalize=True`` the same depth is the length of
+ # the ray instead, so the result has norm 2 and its z component is strictly below 2. The pixel is off the
+ # principal point (cx = 4 != cy = 3) so the two readings differ; a centred pixel would not discriminate.
+ # Snippet used to generate expected: hand arithmetic ((29-4)/100*2, (53-3)/100*2, 2), re-executed
+ # 2026-09-05 (torch 2.14.0, cpu and mps) -> [[0.5, 1.0, 2.0]] and [[0.43643576, 0.87287152, 1.74574304]].
+ camera_matrix = torch.tensor(
+ [[[100.0, 0.0, 4.0], [0.0, 100.0, 3.0], [0.0, 0.0, 1.0]]], device=device, dtype=dtype
+ )
+ points_2d = torch.tensor([[29.0, 53.0]], device=device, dtype=dtype)
+ depth = torch.tensor([[2.0]], device=device, dtype=dtype)
+ z_depth = kornia.geometry.camera.unproject_points(points_2d, depth, camera_matrix)
+ ray_depth = kornia.geometry.camera.unproject_points(points_2d, depth, camera_matrix, normalize=True)
+ self.assert_close(z_depth, torch.tensor([[0.5, 1.0, 2.0]], device=device, dtype=dtype))
+ self.assert_close(ray_depth.norm(dim=-1), torch.tensor([2.0], device=device, dtype=dtype))
+ assert bool(ray_depth[0, 2] < 2.0)
diff --git a/tests/geometry/camera/test_pinhole.py b/tests/geometry/camera/test_pinhole.py
index dbad42ead..131a2dc3a 100644
--- a/tests/geometry/camera/test_pinhole.py
+++ b/tests/geometry/camera/test_pinhole.py
@@ -21,10 +21,41 @@ import pytest
import torch
import kornia
+from kornia.geometry.camera.pinhole import (
+ get_optical_pose_base,
+ homography_i_H_ref,
+ inverse_pinhole_matrix,
+ pinhole_matrix,
+)
from testing.base import BaseTester
+def _k44(device, dtype, fx=100.0, fy=100.0, cx=4.0, cy=3.0):
+ """Build a (1, 4, 4) intrinsics matrix in ``PinholeCamera``'s layout.
+
+ ``cx != cy`` on purpose so a transposed reading of the matrix changes every literal below. Built from a
+ nested list rather than by item assignment into ``torch.eye`` so the signs survive on ``mps``.
+ """
+ return torch.tensor(
+ [[[fx, 0.0, cx, 0.0], [0.0, fy, cy, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]]],
+ device=device,
+ dtype=dtype,
+ )
+
+
+def _e44(device, dtype, tx=0.0, ty=0.0, tz=0.0):
+ """Build a (1, 4, 4) extrinsics matrix with rotation ``I`` and translation ``(tx, ty, tz)``.
+
+ An identity pose is frame-invariant, so every frame/direction pin below passes a non-zero translation.
+ """
+ return torch.tensor(
+ [[[1.0, 0.0, 0.0, tx], [0.0, 1.0, 0.0, ty], [0.0, 0.0, 1.0, tz], [0.0, 0.0, 0.0, 1.0]]],
+ device=device,
+ dtype=dtype,
+ )
+
+
class TestCam2Pixel(BaseTester):
def _create_intrinsics(self, batch_size, fx, fy, cx, cy, device, dtype):
temp = torch.eye(4, device=device, dtype=dtype)
@@ -133,6 +164,44 @@ class TestCam2Pixel(BaseTester):
self.gradcheck(kornia.geometry.camera.cam2pixel, (cam_coords_src, proj_mat, eps), atol=atol, rtol=rtol)
+ def test_wart_cam2pixel_epsilon_makes_the_singular_divide_finite_4267(self, device, dtype):
+ # Wart pin for kornia#4267: cam2pixel divides by ``z + 1e-12`` instead
+ # of guarding the singularity, so the camera-plane point (1, 2, 0) yields a finite 1e14-scale pixel rather
+ # than inf (project_points_z1) or [[104, 203]] (project_points). The epsilon enters the arithmetic, so it
+ # also biases every finite result below z ~ 1e-10.
+ # Snippet used to generate expected: cam2pixel([[[[1., 2., 0.]]]], _k44(...)) executed 2026-09-05
+ # (torch 2.14.0, cpu and mps) -> float32 [[[[1.00000000376832e14, 2.00000000753664e14]]]].
+ # Pins the CURRENT value; NOT a contract; delete when #4267 is repaired.
+ cam_coords = torch.tensor([[[[1.0, 2.0, 0.0], [1.0, 2.0, 1.0e-12]]]], device=device, dtype=dtype)
+ uv = kornia.geometry.camera.cam2pixel(cam_coords, _k44(device, dtype))
+ if dtype == torch.float16:
+ assert bool(torch.isposinf(uv).all())
+ else:
+ assert bool(torch.isfinite(uv).all())
+ # At z = eps the additive denominator halves the result; a guarded divide would not.
+ expected = torch.tensor([[[[1.0e14, 2.0e14], [5.0e13, 1.0e14]]]], device=device, dtype=dtype)
+ self.assert_close(uv, expected)
+
+ def test_wart_cam2pixel_guard_admits_a_3x3_projection_4266(self, device, dtype):
+ # Wart pin for kornia#4266: cam2pixel's second guard is written
+ # ``if not len(dst_proj_src.shape) == 3 and dst_proj_src.shape[-2:] == (4, 4)``, so the shape clause is
+ # live: it rejects a wrong rank only when the trailing shape is (4, 4). A (B, 3, 3) projection has
+ # the accepted rank, passes the guard whose message promises Bx4x4, and fails much later inside
+ # transform_points with a message about homogeneous dimensions rather than at the guard.
+ # Snippet used to generate expected: cam2pixel([[[[1., 2., 4.]]]], _k44(...)[:, :3, :3]) executed
+ # 2026-09-05 (torch 2.14.0, cpu and mps, every dtype)
+ # -> ValueError("Last input dimensions must differ by one unit Got...").
+ # Pins the CURRENT behavior; NOT a contract; delete when #4266 is repaired.
+ cam_coords = torch.tensor([[[[1.0, 2.0, 4.0]]]], device=device, dtype=dtype)
+ proj_3x3 = _k44(device, dtype)[:, :3, :3].contiguous()
+ with pytest.raises(ValueError, match="Last input dimensions must differ by one unit"):
+ kornia.geometry.camera.cam2pixel(cam_coords, proj_3x3)
+ with pytest.raises(ValueError, match="Input dst_proj_src has to be in the shape of Bx4x4"):
+ kornia.geometry.camera.cam2pixel(cam_coords, torch.eye(4, device=device, dtype=dtype))
+ # An unbatched 3x3 passes this guard and instead reaches transform_points' rank check.
+ with pytest.raises(ValueError, match="Input batch size must be the same for both tensors"):
+ kornia.geometry.camera.cam2pixel(cam_coords, torch.eye(3, device=device, dtype=dtype))
+
class TestPixel2Cam(BaseTester):
@pytest.mark.parametrize("depth_shape", [(), (2,), (2, 1, 3), (2, 2, 3, 4), (2, 3, 3, 4), (2, 1, 3, 4, 1)])
@@ -251,6 +320,56 @@ class TestPixel2Cam(BaseTester):
self.gradcheck(kornia.geometry.camera.pixel2cam, (depth, intrinsics_inv, pixel_coords_input), fast_mode=False)
+ def test_wart_pixel2cam_guard_admits_a_3x3_inverse_4266(self, device, dtype):
+ # Wart pin for kornia#4266: pixel2cam's ``intrinsics_inv`` guard is written
+ # ``if not len(intrinsics_inv.shape) == 3``, so it checks the RANK alone and never inspects the trailing
+ # 4x4 its own message promises. A (B, 3, 3) inverse -- the shape every free function on this surface
+ # takes -- has rank 3, passes the guard, and the failure surfaces much later, from transform_points.
+ # Snippet used to generate expected: pixel2cam(ones(1,1,2,3), (1,3,3) inverse, zeros(1,2,3,3)) executed
+ # 2026-09-05 (torch 2.14.0) -> ValueError("Last input dimensions must differ by one unit Got...").
+ # Pins the CURRENT behavior; NOT a contract; delete when #4266 is repaired.
+ depth = torch.ones(1, 1, 2, 3, device=device, dtype=dtype)
+ pixel_coords = torch.zeros(1, 2, 3, 3, device=device, dtype=dtype)
+ intrinsics_inv_3x3 = torch.tensor(
+ [[[0.01, 0.0, -0.04], [0.0, 0.01, -0.03], [0.0, 0.0, 1.0]]], device=device, dtype=dtype
+ )
+ with pytest.raises(ValueError, match="Last input dimensions must differ by one unit"):
+ kornia.geometry.camera.pixel2cam(depth, intrinsics_inv_3x3, pixel_coords)
+
+ def test_convention_pixel2cam_rejects_multi_channel_depth_4266(self, device, dtype):
+ # Regression pin for kornia#4266: multi-channel depth must be rejected instead of scaling
+ # each camera coordinate by a different channel. Single-channel depth scales the whole ray.
+ # An exact inverse of fx = fy = 1, cx = 4, cy = 3, so every literal below is exact in every dtype.
+ intrinsics_inv = torch.tensor(
+ [[[1.0, 0.0, -4.0, 0.0], [0.0, 1.0, -3.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]]],
+ device=device,
+ dtype=dtype,
+ )
+ # (1, H = 3, W = 4, 3) grid of (u, v, 1): u = 5 + col, v = 5 + row, so the camera point is
+ # (1 + col, 2 + row, 1).
+ pixel_coords = torch.tensor(
+ [
+ [
+ [[5.0, 5.0, 1.0], [6.0, 5.0, 1.0], [7.0, 5.0, 1.0], [8.0, 5.0, 1.0]],
+ [[5.0, 6.0, 1.0], [6.0, 6.0, 1.0], [7.0, 6.0, 1.0], [8.0, 6.0, 1.0]],
+ [[5.0, 7.0, 1.0], [6.0, 7.0, 1.0], [7.0, 7.0, 1.0], [8.0, 7.0, 1.0]],
+ ]
+ ],
+ device=device,
+ dtype=dtype,
+ )
+ depth_3ch = torch.tensor([2.0, 3.0, 5.0], device=device, dtype=dtype).reshape(1, 3, 1, 1).expand(1, 3, 3, 4)
+ with pytest.raises(ValueError, match="Input depth has to be in the shape of Bx1xHxW"):
+ kornia.geometry.camera.pixel2cam(depth_3ch.contiguous(), intrinsics_inv, pixel_coords)
+ depth_1ch = torch.full((1, 1, 3, 4), 2.0, device=device, dtype=dtype)
+ out_1ch = kornia.geometry.camera.pixel2cam(depth_1ch, intrinsics_inv, pixel_coords)
+ self.assert_close(
+ out_1ch[0, 2, 3], torch.tensor([8.0, 8.0, 2.0], device=device, dtype=dtype), atol=0.0, rtol=0.0
+ )
+ depth_2ch = torch.tensor([2.0, 3.0], device=device, dtype=dtype).reshape(1, 2, 1, 1).expand(1, 2, 3, 4)
+ with pytest.raises(ValueError, match="Input depth has to be in the shape of Bx1xHxW"):
+ kornia.geometry.camera.pixel2cam(depth_2ch.contiguous(), intrinsics_inv, pixel_coords)
+
class TestPinholeCamera(BaseTester):
def _create_intrinsics(self, batch_size, fx, fy, cx, cy, device, dtype):
@@ -521,3 +640,336 @@ class TestPinholeCamera(BaseTester):
pinhole = kornia.geometry.camera.PinholeCamera(intrinsics, extrinsics, height, width)
assert pinhole.device() == intrinsics.device
+
+ def test_convention_extrinsics_are_world_to_camera(self, device, dtype):
+ # Convention pin: project() computes K (R X + t) -- the extrinsics map WORLD points INTO the camera frame
+ # (OpenCV / COLMAP semantics). With R = I and t = (1, 0, 0) the world point (1, 2, 4) becomes (2, 2, 4) in
+ # the camera frame and projects to u = 100*2/4 + 4 = 54, v = 100*2/4 + 3 = 53. A cam-to-world reading would
+ # move the point to (0, 2, 4) and give (4, 53); cx != cy also breaks a transposed reading.
+ # Snippet used to generate expected: hand arithmetic, re-executed 2026-09-05 (torch 2.14.0, cpu and mps,
+ # every dtype): [[54., 53.]].
+ cam = kornia.geometry.camera.PinholeCamera(
+ _k44(device, dtype),
+ _e44(device, dtype, tx=1.0),
+ torch.tensor([6], device=device),
+ torch.tensor([8], device=device),
+ )
+ uv = cam.project(torch.tensor([[1.0, 2.0, 4.0]], device=device, dtype=dtype))
+ self.assert_close(uv, torch.tensor([[54.0, 53.0]], device=device, dtype=dtype), atol=0.0, rtol=0.0)
+
+ def test_convention_unproject_returns_the_world_point(self, device, dtype):
+ # Convention pin: unproject(uv, depth) inverts project() back into the WORLD frame (it applies the inverse
+ # of K @ E), and ``depth`` is the CAMERA-frame z, not the ray length. Same tx = 1 extrinsics as above, so a
+ # camera-frame result (2, 2, 4) fails this pin. Contrast the free function unproject_points, which takes no
+ # extrinsics and therefore necessarily returns a camera-frame point.
+ # Snippet used to generate expected: cam.unproject(cam.project(X), 4.) executed 2026-09-05 (torch 2.14.0)
+ # -> float32 [[0.99999988, 1.9999999, 4.0]], max abs error 1.19e-07.
+ cam = kornia.geometry.camera.PinholeCamera(
+ _k44(device, dtype),
+ _e44(device, dtype, tx=1.0),
+ torch.tensor([6], device=device),
+ torch.tensor([8], device=device),
+ )
+ X = torch.tensor([[1.0, 2.0, 4.0]], device=device, dtype=dtype)
+ back = cam.unproject(cam.project(X), torch.tensor([[4.0]], device=device, dtype=dtype))
+ self.assert_close(back, X)
+
+ def test_convention_clone_is_a_deep_copy(self, device, dtype):
+ # Convention pin: clone() is the ONLY deep copy on PinholeCamera -- a new
+ # object, new intrinsics and extrinsics tensors with different storage, and mutating the clone leaves the
+ # source untouched. Contrast scale(), which hands the SAME extrinsics to the new camera (kornia#4264).
+ # Snippet used to generate expected: build a tx = 2 camera, clone it, set clone.tx = 9; executed
+ # 2026-09-05 (torch 2.14.0, every dtype) -> source tx [2.0], clone tx [9.0].
+ cam = kornia.geometry.camera.PinholeCamera(
+ _k44(device, dtype),
+ _e44(device, dtype, tx=2.0),
+ torch.tensor([6.0], device=device, dtype=dtype),
+ torch.tensor([8.0], device=device, dtype=dtype),
+ )
+ cloned = cam.clone()
+ assert cloned is not cam
+ assert cloned.intrinsics is not cam.intrinsics
+ assert cloned.extrinsics is not cam.extrinsics
+ assert cloned.intrinsics.data_ptr() != cam.intrinsics.data_ptr()
+ assert cloned.extrinsics.data_ptr() != cam.extrinsics.data_ptr()
+ cloned.tx = torch.tensor([9.0], device=device, dtype=dtype)
+ self.assert_close(cam.tx, torch.tensor([2.0], device=device, dtype=dtype), atol=0.0, rtol=0.0)
+ self.assert_close(cloned.tx, torch.tensor([9.0], device=device, dtype=dtype), atol=0.0, rtol=0.0)
+
+ def test_convention_intrinsics_inverse_is_the_exact_inverse(self, device, dtype):
+ # Convention pin: intrinsics_inverse() @ intrinsics is byte-exact eye(4) on an
+ # asymmetric fx = 100, fy = 50, cx = 4, cy = 3 intrinsics -- this is the pair DepthWarper feeds pixel2cam.
+ # The legacy 12-vector twins are NOT exact: inverse_pinhole_matrix @ pinhole_matrix is 1e-06 off
+ # (kornia#4268, pinned in TestPinholeMatrix below).
+ # Snippet used to generate expected: torch.equal(inv @ K, eye(4)[None]) executed 2026-09-05 (torch 2.14.0)
+ # -> True for float32/float64/bfloat16 on cpu and float32 on mps.
+ if dtype == torch.float16:
+ pytest.skip("float16 cannot round-trip 1/fx: inv @ K differs from eye(4) by 1.5e-05 (2026-09-05)")
+ cam = kornia.geometry.camera.PinholeCamera(
+ _k44(device, dtype, fy=50.0),
+ _e44(device, dtype, tx=1.0),
+ torch.tensor([6.0], device=device, dtype=dtype),
+ torch.tensor([8.0], device=device, dtype=dtype),
+ )
+ product = cam.intrinsics_inverse() @ cam.intrinsics
+ self.assert_close(product, torch.eye(4, device=device, dtype=dtype)[None], atol=0.0, rtol=0.0)
+
+ def test_wart_scale_rescales_the_principal_point_by_the_half_pixel_rule_4263(self, device, dtype):
+ # Wart pin for kornia#4263: scale(s) gives cx' = s * cx (2.0 for cx = 4,
+ # s = 0.5) -- the half-pixel / COLMAP convention -- although create_meshgrid and every unprojection path in
+ # the library enumerate integer pixel CENTRES, under which the grid-consistent value is
+ # cx' = s * cx + (s - 1) / 2 = 1.75. Pins the CURRENT value so the window's repair flips this loudly.
+ # Snippet used to generate expected: cam.scale(0.5) executed 2026-09-05 (torch 2.14.0, every dtype)
+ # -> cx [2.0], cy [1.5], fx [50.0]. NOT a contract; delete when #4263 is repaired.
+ cam = kornia.geometry.camera.PinholeCamera(
+ _k44(device, dtype),
+ _e44(device, dtype, tx=1.0),
+ torch.tensor([6.0], device=device, dtype=dtype),
+ torch.tensor([8.0], device=device, dtype=dtype),
+ )
+ scaled = cam.scale(torch.tensor([0.5], device=device, dtype=dtype))
+ self.assert_close(scaled.cx, torch.tensor([2.0], device=device, dtype=dtype), atol=0.0, rtol=0.0)
+ self.assert_close(scaled.cy, torch.tensor([1.5], device=device, dtype=dtype), atol=0.0, rtol=0.0)
+ self.assert_close(scaled.fx, torch.tensor([50.0], device=device, dtype=dtype), atol=0.0, rtol=0.0)
+
+ def test_wart_scale_shares_extrinsics_with_the_source_4264(self, device, dtype):
+ # Wart pin for kornia#4264: the class stores the tensors it is constructed from
+ # instead of copying them, so every mutating accessor writes into the CALLER's tensors, and scale()
+ # clones the intrinsics but passes ``self.extrinsics`` straight through, so the returned camera aliases
+ # the source's pose -- writing ``scaled.tx = 7`` (the tx setter writes into extrinsics) changes the
+ # SOURCE camera too. The second half below pins the three other legs of the same sentence: the
+ # constructor keeps the caller's ``intrinsics`` / ``extrinsics`` objects, the ``tx`` setter writes into
+ # the caller's extrinsics, and the in-place ``scale_`` rewrites the caller's intrinsics and image size.
+ # Snippet used to generate expected: scaled.extrinsics is cam.extrinsics -> True; after scaled.tx = 7 the
+ # source tx reads [7.0]; cam.intrinsics is K and cam.extrinsics is E -> True; after ``cam.tx = 5.0``
+ # E[0, 0, 3] reads 5.0; after ``cam.scale_(0.5)`` K[0, 0, 2] reads 2.0 (from 4.0), K[0, 0, 0] reads 50.0
+ # and the caller's height/width read [3.0] / [4.0] (from [6.0] / [8.0]); executed 2026-09-05
+ # (torch 2.14.0, cpu and mps, every dtype).
+ # Pins the CURRENT behavior; NOT a contract; delete when #4264 is repaired.
+ cam = kornia.geometry.camera.PinholeCamera(
+ _k44(device, dtype),
+ _e44(device, dtype, tx=1.0),
+ torch.tensor([6.0], device=device, dtype=dtype),
+ torch.tensor([8.0], device=device, dtype=dtype),
+ )
+ scaled = cam.scale(torch.tensor([2.0], device=device, dtype=dtype))
+ assert scaled.extrinsics is cam.extrinsics
+ assert scaled.intrinsics is not cam.intrinsics
+ scaled.tx = torch.tensor([7.0], device=device, dtype=dtype)
+ self.assert_close(cam.tx, torch.tensor([7.0], device=device, dtype=dtype), atol=0.0, rtol=0.0)
+ # The constructor stores, rather than copies, all four arguments.
+ K = _k44(device, dtype)
+ E = _e44(device, dtype, tx=1.0)
+ height = torch.tensor([6.0], device=device, dtype=dtype)
+ width = torch.tensor([8.0], device=device, dtype=dtype)
+ source = kornia.geometry.camera.PinholeCamera(K, E, height, width)
+ assert source.intrinsics is K
+ assert source.extrinsics is E
+ # The tx setter writes into the caller's extrinsics tensor.
+ source.tx = 5.0
+ self.assert_close(E[0, 0, 3], torch.tensor(5.0, device=device, dtype=dtype), atol=0.0, rtol=0.0)
+ # scale_ rewrites the caller's intrinsics and image-size tensors in place.
+ source.scale_(torch.tensor([0.5], device=device, dtype=dtype))
+ self.assert_close(K[0, 0, 2], torch.tensor(2.0, device=device, dtype=dtype), atol=0.0, rtol=0.0)
+ self.assert_close(K[0, 0, 0], torch.tensor(50.0, device=device, dtype=dtype), atol=0.0, rtol=0.0)
+ self.assert_close(height, torch.tensor([3.0], device=device, dtype=dtype), atol=0.0, rtol=0.0)
+ self.assert_close(width, torch.tensor([4.0], device=device, dtype=dtype), atol=0.0, rtol=0.0)
+
+ def test_wart_scale_inplace_rejects_integer_image_size_4265(self, device, dtype):
+ # Wart pin for kornia#4265: the constructor accepts int64 height/width --
+ # that is what the class docstring's own example builds -- and a floating factor promotes them, but the
+ # in-place twin scale_() writes the float result back into the int64 storage and raises.
+ # Snippet used to generate expected: cam.scale_(0.5) on an int64 height executed 2026-09-05 (torch 2.14.0,
+ # every dtype) -> RuntimeError("result type Float can't be cast to the desired output type Long").
+ # Pins the CURRENT behavior; NOT a contract; delete when #4265 is repaired.
+ K = _k44(device, dtype)
+ cam = kornia.geometry.camera.PinholeCamera(
+ K,
+ _e44(device, dtype, tx=1.0),
+ torch.tensor([6], device=device),
+ torch.tensor([8], device=device),
+ )
+ for factor in (2, torch.tensor([2], device=device)):
+ scaled = cam.scale(factor)
+ assert scaled.height.dtype == scaled.width.dtype == torch.int64
+ self.assert_close(scaled.height, torch.tensor([12], device=device))
+ self.assert_close(scaled.width, torch.tensor([16], device=device))
+ inplace = cam.clone()
+ assert inplace.scale_(factor) is inplace
+ self.assert_close(inplace.height, scaled.height)
+ self.assert_close(inplace.width, scaled.width)
+ self.assert_close(inplace.intrinsics, scaled.intrinsics)
+ assert cam.scale(torch.tensor([0.5], device=device, dtype=dtype)).height.is_floating_point()
+ with pytest.raises(RuntimeError, match="can't be cast to the desired output type"):
+ cam.scale_(0.5)
+ expected_K = _k44(device, dtype)
+ expected_K[:, :2, :3] *= 0.5
+ self.assert_close(K, expected_K, atol=0.0, rtol=0.0)
+ self.assert_close(cam.intrinsics, expected_K, atol=0.0, rtol=0.0)
+ self.assert_close(cam.height, torch.tensor([6], device=device))
+ self.assert_close(cam.width, torch.tensor([8], device=device))
+
+ def test_wart_constructor_accepts_3x3_intrinsics_whose_projection_is_garbage_4266(self, device, dtype):
+ # Wart pin for kornia#4266: _check_valid_params uses ``and`` where ``or``
+ # was meant (the source even carries the author's "Shouldn't this be an OR logic than AND?"), so a
+ # (1, 3, 3) intrinsics with a (1, 3, 4) extrinsics passes a validator whose message promises Bx4x4, and
+ # .project returns a (1, 1) tensor of nonsense instead of a (1, 2) pixel.
+ # Snippet used to generate expected: PinholeCamera(K[:, :3, :3], E[:, :3, :]).project([[1., 2., 4.]])
+ # executed 2026-09-05 (torch 2.14.0) -> shape (1, 1), float32 value [[0.5471698]] (dtype-dependent, so
+ # only the cardinality is pinned). NOT a contract; delete when #4266 is repaired.
+ K = _k44(device, dtype)[:, :3, :3].contiguous()
+ E = _e44(device, dtype, tx=1.0)[:, :3, :].contiguous()
+ cam = kornia.geometry.camera.PinholeCamera(
+ K, E, torch.tensor([6], device=device), torch.tensor([8], device=device)
+ )
+ assert cam.project(torch.tensor([[1.0, 2.0, 4.0]], device=device, dtype=dtype)).shape == (1, 1)
+
+ def test_wart_project_rejects_an_unbatched_point_with_indexerror_4266(self, device, dtype):
+ # Wart pin for kornia#4266: PinholeCamera.project documents ``(*, 3)``
+ # and raises a bare IndexError("tuple index out of range") on a (3,) point, while the free function
+ # project_points raises ValueError("Input must be at least a 2D tensor") on the same input -- two
+ # exception types for one documented contract, and neither is the documented shape.
+ # Snippet used to generate expected: both calls executed 2026-09-05 (torch 2.14.0, every dtype).
+ # Pins the CURRENT behavior; NOT a contract; delete when #4266 is repaired.
+ cam = kornia.geometry.camera.PinholeCamera(
+ _k44(device, dtype),
+ _e44(device, dtype, tx=1.0),
+ torch.tensor([6], device=device),
+ torch.tensor([8], device=device),
+ )
+ point = torch.tensor([1.0, 2.0, 4.0], device=device, dtype=dtype)
+ with pytest.raises(IndexError, match="tuple index out of range"):
+ cam.project(point)
+ with pytest.raises(ValueError, match="at least a 2D tensor"):
+ kornia.geometry.camera.project_points(point, _k44(device, dtype)[:, :3, :3].contiguous())
+
+ def test_wart_constructor_rejects_an_empty_batch_4281(self, device, dtype):
+ # Mixed pin. The FIRST assertion is a wart pin for kornia#4281: _check_valid is
+ # ``all(data.shape[0] for ...)``, which tests that each batch size is non-zero rather than that they are
+ # EQUAL, so a perfectly consistent B = 0 camera is rejected with a message about mismatched shapes. It
+ # pins the CURRENT behavior, is NOT a contract, and is the only assertion here that is deleted when
+ # #4281 is repaired. The SECOND assertion is the CONVENTION the repair has to converge on and SURVIVES
+ # it: the free functions on the same surface already follow kornia's empty-in/empty-out rule, so
+ # project_points on a (0, 1, 3) input returns a (0, 1, 2) tensor rather than raising.
+ # Snippet used to generate expected: both calls executed 2026-09-05 (torch 2.14.0, every dtype)
+ # -> ValueError("Arguments shapes must match") and shape (0, 1, 2).
+ with pytest.raises(ValueError, match="Arguments shapes must match"):
+ kornia.geometry.camera.PinholeCamera(
+ torch.zeros(0, 4, 4, device=device, dtype=dtype),
+ torch.zeros(0, 4, 4, device=device, dtype=dtype),
+ torch.zeros(0, device=device, dtype=dtype),
+ torch.zeros(0, device=device, dtype=dtype),
+ )
+ empty = kornia.geometry.camera.project_points(
+ torch.zeros(0, 1, 3, device=device, dtype=dtype), _k44(device, dtype)[:, :3, :3].contiguous()
+ )
+ assert empty.shape == (0, 1, 2)
+
+ def test_wart_project_and_project_points_disagree_at_z_zero_4267(self, device, dtype):
+ # Wart pin for kornia#4267: PinholeCamera.project and the free function
+ # project_points are documented as the same projection and agree exactly away from the singularity, but
+ # they apply K on OPPOSITE sides of the masked |z| <= 1e-8 divide, so at z = 0 they return different
+ # answers -- K @ [1, 2, 0] = [100, 200] for the method and fx*x + cx = [104, 203] for the function.
+ # The divergence is the defect, not either value.
+ # Snippet used to generate expected: both calls at (1, 2, 0) and (1, 2, 4) executed 2026-09-05
+ # (torch 2.14.0, cpu and mps, every dtype). NOT a contract; delete when #4267 is repaired.
+ cam = kornia.geometry.camera.PinholeCamera(
+ _k44(device, dtype),
+ _e44(device, dtype),
+ torch.tensor([6], device=device),
+ torch.tensor([8], device=device),
+ )
+ K3 = _k44(device, dtype)[:, :3, :3].contiguous()
+ singular = torch.tensor([[1.0, 2.0, 0.0]], device=device, dtype=dtype)
+ self.assert_close(
+ cam.project(singular), torch.tensor([[100.0, 200.0]], device=device, dtype=dtype), atol=0.0, rtol=0.0
+ )
+ self.assert_close(
+ kornia.geometry.camera.project_points(singular, K3),
+ torch.tensor([[104.0, 203.0]], device=device, dtype=dtype),
+ atol=0.0,
+ rtol=0.0,
+ )
+ regular = torch.tensor([[1.0, 2.0, 4.0]], device=device, dtype=dtype)
+ self.assert_close(cam.project(regular), kornia.geometry.camera.project_points(regular, K3))
+
+ def test_convention_from_parameters_fills_every_batch_element_4279(self, device, dtype):
+ # Regression pin for #4279: image size must be filled for every camera in the batch.
+ cam = self._from_parameters_batch2(device, dtype)
+ self.assert_close(cam.height, torch.tensor([6.0, 6.0], device=device, dtype=dtype), atol=0.0, rtol=0.0)
+ self.assert_close(cam.width, torch.tensor([8.0, 8.0], device=device, dtype=dtype), atol=0.0, rtol=0.0)
+ self.assert_close(cam.fx, torch.tensor([100.0, 200.0], device=device, dtype=dtype), atol=0.0, rtol=0.0)
+ self.assert_close(cam.tx, torch.tensor([1.0, 2.0], device=device, dtype=dtype), atol=0.0, rtol=0.0)
+
+ def _from_parameters_batch2(self, device, dtype):
+ # Asymmetric per-element parameters (fx 100/200, fy 100/50, cx 4/6, cy 3/2, tx 1/2) so a pin that reads the
+ # wrong batch element, or transposes fx and fy, changes the literal.
+ return kornia.geometry.camera.PinholeCamera.from_parameters(
+ fx=torch.tensor([100.0, 200.0], device=device, dtype=dtype),
+ fy=torch.tensor([100.0, 50.0], device=device, dtype=dtype),
+ cx=torch.tensor([4.0, 6.0], device=device, dtype=dtype),
+ cy=torch.tensor([3.0, 2.0], device=device, dtype=dtype),
+ height=6,
+ width=8,
+ tx=torch.tensor([1.0, 2.0], device=device, dtype=dtype),
+ ty=torch.tensor([0.0, 0.0], device=device, dtype=dtype),
+ tz=torch.tensor([0.0, 0.0], device=device, dtype=dtype),
+ batch_size=2,
+ device=device,
+ dtype=dtype,
+ )
+
+
+class TestPinholeMatrix(BaseTester):
+ """Pins for the legacy 12-vector pinhole API in ``kornia.geometry.camera.pinhole``.
+
+ None of these names is in ``kornia.geometry.camera.__all__`` or reachable as ``kornia.geometry.camera.X``,
+ so they are imported from the module directly.
+ """
+
+ def _vec12(self, device, dtype):
+ # (fx, fy, cx, cy, height, width, rx, ry, rz, tx, ty, tz); cx != cy and height != width so a swapped
+ # reading of the vector changes the matrix.
+ return torch.tensor(
+ [[100.0, 100.0, 4.0, 3.0, 6.0, 8.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]], device=device, dtype=dtype
+ )
+
+ def test_wart_pinhole_matrix_perturbs_every_entry_4268(self, device, dtype):
+ # Wart pin for kornia#4268: pinhole_matrix
+ # adds its eps to the WHOLE identity before writing the parameters, so every entry is perturbed -- the
+ # structural zero at [0, 0, 1] is 1e-06 and the structural one at [0, 3, 3] is 1.000001. Passing eps=0.0
+ # gives the exact matrix, so the default is the only thing wrong. inverse_pinhole_matrix divides by
+ # fx + eps, so the legacy pair is never an exact inverse (contrast PinholeCamera.intrinsics_inverse, which
+ # is byte-exact). A (1, 4, 4) input raises a bare AssertionError carrying only a shape, not a ShapeError.
+ # Snippet used to generate expected: pinhole_matrix(vec12) executed 2026-09-05 (torch 2.14.0) -> float32
+ # [0, 0, 1] = 9.999999974752427e-07, [0, 3, 3] = 1.0000009536743164, inv[0, 0, 0] * 100 = 0.99999998.
+ # Pins the CURRENT values; NOT a contract; delete when #4268 is repaired.
+ if dtype in (torch.float16, torch.bfloat16):
+ pytest.skip("half precision cannot hold 1 + 1e-06: [0, 3, 3] reads exactly 1.0 (executed 2026-09-05)")
+ vec = self._vec12(device, dtype)
+ matrix = pinhole_matrix(vec)
+ assert matrix[0, 0, 1].item() != 0.0
+ assert matrix[0, 3, 3].item() != 1.0
+ self.assert_close(matrix[0, 0, 1], torch.tensor(1e-06, device=device, dtype=dtype), atol=0.0, rtol=0.0)
+ self.assert_close(matrix[0, 3, 3], torch.tensor(1.000001, device=device, dtype=dtype), atol=0.0, rtol=0.0)
+ exact = pinhole_matrix(vec, eps=0.0)
+ assert exact[0, 0, 1].item() == 0.0
+ assert exact[0, 3, 3].item() == 1.0
+ residual = (inverse_pinhole_matrix(vec) @ matrix - torch.eye(4, device=device, dtype=dtype)).abs().max()
+ assert residual.item() > 0.0
+ with pytest.raises(AssertionError, match=r"torch\.Size\(\[1, 4, 4\]\)"):
+ inverse_pinhole_matrix(torch.eye(4, device=device, dtype=dtype)[None])
+
+ def test_wart_dead_legacy_functions_always_raise_4283(self, device, dtype):
+ # Wart pin for kornia#4283: get_optical_pose_base and homography_i_H_ref
+ # carry full docstrings, Args/Returns blocks and a .. math:: block, validate their input, and then always
+ # raise NotImplementedError -- get_optical_pose_base's dependency was removed from torchgeometry years ago
+ # ("# TODO: where is rtvec_to_pose?"), and homography_i_H_ref is dead because it calls it.
+ # Snippet used to generate expected: both calls on the documented (N, 12) vector executed 2026-09-05
+ # (torch 2.14.0, every dtype) -> NotImplementedError('').
+ # Pins the CURRENT behavior; NOT a contract; delete when #4283 is repaired.
+ vec = self._vec12(device, dtype)
+ with pytest.raises(NotImplementedError):
+ get_optical_pose_base(vec)
+ with pytest.raises(NotImplementedError):
+ homography_i_H_ref(vec, vec)
diff --git a/tests/geometry/camera/test_projections.py b/tests/geometry/camera/test_projections.py
index dbf9245a9..75c494e6b 100644
--- a/tests/geometry/camera/test_projections.py
+++ b/tests/geometry/camera/test_projections.py
@@ -18,6 +18,7 @@
import pytest
import torch
+from kornia.geometry.camera.perspective import project_points
from kornia.geometry.camera.projection_orthographic import (
dx_project_points_orthographic,
project_points_orthographic,
@@ -172,6 +173,49 @@ class TestProjectionZ1(BaseTester):
self._test_jit_project(device, dtype)
self._test_jit_unproject(device, dtype)
+ def test_wart_project_points_z1_zero_depth_is_component_dependent_4267(self, device, dtype):
+ # project_points_z1 divides plainly. Snippet used to generate expected: project_points_z1 applied to the
+ # four points below -> [[inf, -inf], [-inf, inf], [nan, inf], [inf, nan]].
+ points = torch.tensor(
+ [[1.0, -2.0, 0.0], [-1.0, 2.0, 0.0], [0.0, 2.0, 0.0], [1.0, 0.0, 0.0]],
+ device=device,
+ dtype=dtype,
+ )
+ actual = project_points_z1(points)
+ expected_posinf = torch.tensor([[True, False], [False, True], [False, True], [True, False]], device=device)
+ expected_neginf = torch.tensor([[False, True], [True, False], [False, False], [False, False]], device=device)
+ expected_nan = torch.tensor([[False, False], [False, False], [True, False], [False, True]], device=device)
+ assert torch.equal(torch.isposinf(actual), expected_posinf)
+ assert torch.equal(torch.isneginf(actual), expected_neginf)
+ assert torch.equal(torch.isnan(actual), expected_nan)
+
+ def test_convention_project_points_z1_differs_below_perspective_epsilon(self, device, dtype):
+ # Snippet used to generate expected: project_points_z1([[1., 2., 1e-9]]) -> [[1e9, 2e9]], while
+ # project_points(..., eye(3)) -> [[1., 2.]] because its homogeneous conversion does not divide when
+ # abs(z) <= 1e-8. float16 is skipped because 1e-9 underflows to zero in that dtype.
+ if dtype == torch.float16:
+ pytest.skip("1e-9 underflows to zero in float16")
+ points = torch.tensor([[1.0, 2.0, 1e-9]], device=device, dtype=dtype)
+ camera_matrix = torch.eye(3, device=device, dtype=dtype).unsqueeze(0)
+ expected_z1 = torch.tensor([[1e9, 2e9]], device=device, dtype=dtype)
+ expected_perspective = torch.tensor([[1.0, 2.0]], device=device, dtype=dtype)
+ self.assert_close(project_points_z1(points), expected_z1)
+ self.assert_close(project_points(points, camera_matrix), expected_perspective)
+
+ def test_convention_dx_project_points_z1_matches_autograd(self, device, dtype):
+ # Convention pin: dx_project_points_z1 returns the (..., 2, 3) Jacobian
+ # of project_points_z1, laid out d(u, v) / d(x, y, z) -- row-major in the OUTPUT index. Checked against
+ # torch.autograd.functional.jacobian at an off-axis point (1, 2, 3) where all six entries differ, so a
+ # transposed layout or a swapped (u, v) row fails.
+ # Snippet used to generate expected: autograd.functional.jacobian(project_points_z1, [1., 2., 3.])
+ # executed 2026-09-05 (torch 2.14.0, cpu and mps) -> max abs difference 1.49e-08 in float32, 0.0 in
+ # float64/float16/bfloat16.
+ points = torch.tensor([1.0, 2.0, 3.0], device=device, dtype=dtype)
+ analytic = dx_project_points_z1(points)
+ numeric = torch.autograd.functional.jacobian(project_points_z1, points)
+ assert analytic.shape == (2, 3)
+ self.assert_close(analytic, numeric)
+
class TestProjectionOrthographic(BaseTester):
def test_smoke(self, device, dtype):
@@ -234,6 +278,41 @@ class TestProjectionOrthographic(BaseTester):
with pytest.raises(ShapeError):
unproject_points_orthographic(points, extension)
+ def test_convention_dx_orthographic_is_the_scalar_du_dx_not_the_full_jacobian(self, device, dtype):
+ # Convention pin: dx_project_points_orthographic returns the single
+ # partial derivative its docstring math states, du/dx = 1, with shape (..., 1) -- NOT the (2, 3)
+ # Jacobian of project_points_orthographic, and NOT the shape its same-named z1 sibling returns. The two
+ # ``dx_*`` functions on this surface therefore mean different things, so the pin asserts the shapes
+ # apart and checks each against torch.autograd.functional.jacobian of the projection it differentiates.
+ # An off-axis point (x != y != z, one negative) is used so a transposed or wrongly indexed Jacobian
+ # changes a literal. Snippet used to generate expected: the four calls below on [1., -2., 4.] executed
+ # 2026-09-05 (torch 2.14.0, cpu and mps, float16/bfloat16/float32/float64) ->
+ # dx_orthographic [1.] shape (1,); jacobian(project_points_orthographic) [[1, 0, 0], [0, 1, 0]] shape
+ # (2, 3); dx_z1 == jacobian(project_points_z1) == [[0.25, 0, -0.0625], [0, 0.25, 0.125]] shape (2, 3).
+ # Every literal is a dyadic rational and matched exactly in every dtype and device tested.
+ points = torch.tensor([1.0, -2.0, 4.0], device=device, dtype=dtype)
+ dx_ortho = dx_project_points_orthographic(points)
+ assert dx_ortho.shape == (1,)
+ self.assert_close(dx_ortho, torch.tensor([1.0], device=device, dtype=dtype), atol=0.0, rtol=0.0)
+ jacobian_ortho = torch.autograd.functional.jacobian(project_points_orthographic, points)
+ assert jacobian_ortho.shape == (2, 3)
+ self.assert_close(
+ jacobian_ortho,
+ torch.tensor([[1.0, 0.0, 0.0], [0.0, 1.0, 0.0]], device=device, dtype=dtype),
+ atol=0.0,
+ rtol=0.0,
+ )
+ # dx_project_points_z1, by contrast, IS the full Jacobian of its projection.
+ dx_z1 = dx_project_points_z1(points)
+ assert dx_z1.shape == (2, 3)
+ self.assert_close(dx_z1, torch.autograd.functional.jacobian(project_points_z1, points), atol=0.0, rtol=0.0)
+ self.assert_close(
+ dx_z1,
+ torch.tensor([[0.25, 0.0, -0.0625], [0.0, 0.25, 0.125]], device=device, dtype=dtype),
+ atol=0.0,
+ rtol=0.0,
+ )
+
def _test_gradcheck_project(self, device):
points = torch.tensor([1.0, 2.0, 3.0], device=device, dtype=torch.float64)
self.gradcheck(project_points_orthographic, (points,))
@@ -265,3 +344,30 @@ class TestProjectionOrthographic(BaseTester):
def test_jit(self, device, dtype) -> None:
self._test_jit_project(device, dtype)
self._test_jit_unproject(device, dtype)
+
+ def test_convention_orthographic_drops_and_restores_the_z_axis(self, device, dtype):
+ # Convention pin: the orthographic projection drops z and keeps (x, y)
+ # in order -- (1, 2, 3) -> (1, 2), never (1, 3) or (2, 1) -- and the unprojection appends the extension as
+ # the z component, so (1, 2) with extension 3 restores (1, 2, 3) exactly. Distinct x, y and z so every
+ # axis permutation changes the literal.
+ # Snippet used to generate expected: both calls executed 2026-09-05 (torch 2.14.0, cpu and mps, every
+ # dtype) -> [1., 2.] and [1., 2., 3.]; exact, no divide is involved.
+ points_3d = torch.tensor([1.0, 2.0, 3.0], device=device, dtype=dtype)
+ projected = project_points_orthographic(points_3d)
+ self.assert_close(projected, torch.tensor([1.0, 2.0], device=device, dtype=dtype), atol=0.0, rtol=0.0)
+ restored = unproject_points_orthographic(projected, torch.tensor([3.0], device=device, dtype=dtype))
+ self.assert_close(restored, points_3d, atol=0.0, rtol=0.0)
+
+ def test_convention_unproject_points_orthographic_accepts_both_extension_shapes(self, device, dtype):
+ # Convention pin: unproject_points_orthographic compares the
+ # extension's RANK with the points' rank -- the right predicate -- so a (N,) and a (N, 1) extension are
+ # both accepted for N > 1 and give the same answer. Its sibling unproject_points_z1 uses the same
+ # rank-based guard after f4532f39.
+ # Snippet used to generate expected: points [[1, 2], [3, 4]] with extensions [5, 6] and [[5], [6]]
+ # executed 2026-09-05 (torch 2.14.0, cpu and mps, every dtype) -> [[1., 2., 5.], [3., 4., 6.]] for both.
+ points = torch.tensor([[1.0, 2.0], [3.0, 4.0]], device=device, dtype=dtype)
+ expected = torch.tensor([[1.0, 2.0, 5.0], [3.0, 4.0, 6.0]], device=device, dtype=dtype)
+ flat = unproject_points_orthographic(points, torch.tensor([5.0, 6.0], device=device, dtype=dtype))
+ column = unproject_points_orthographic(points, torch.tensor([[5.0], [6.0]], device=device, dtype=dtype))
+ self.assert_close(flat, expected, atol=0.0, rtol=0.0)
+ self.assert_close(column, expected, atol=0.0, rtol=0.0)