π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
docs(camera): trim convention blocks and pins to kornia scope (#4790)
Dmytro Mishkin9dbd11f52b1d
diff --git a/changelog.d/4790.fixed.md b/changelog.d/4790.fixed.mdnew file mode 100644index 000000000..4452d2eaf--- /dev/null+++ b/changelog.d/4790.fixed.md@@ -0,0 +1 @@+`solve_pnp_dlt`'s point-count, dtype and `svd_eps` checks now name the offending argument (for example "world_points must hold at least 6 points (N >= 6), got N = 5.") instead of a bare "Validation condition failed". The convention blocks of `kornia.geometry.bbox`, `kornia.geometry.boxes`, `kornia.geometry.depth`, `kornia.geometry.camera`, `kornia.geometry.calibration` and `kornia.sensors.camera` are trimmed to kornia's own contract, with the pixel-centre convention stated once on `PinholeCamera`, and a `torch.where:` typo for "where:" is fixed in the docstrings of `harris_response`, `gftt_response`, `hessian_response`, `BinaryFocalLossWithLogits`, `ssim3d`, `SSIM3D`, `solve_pnp_dlt` and `homography_i_H_ref`.diff --git a/docs/source/geometry.camera.stereo.rst b/docs/source/geometry.camera.stereo.rstindex 746350b44..80548ca5d 100644--- a/docs/source/geometry.camera.stereo.rst+++ b/docs/source/geometry.camera.stereo.rst@@ -125,9 +125,9 @@ where :math:`Q` is0 & 0 & -fy & fy * (cx_{left} -cx_{right})\end{bmatrix}-The point cloud is obtained by a homogeneous transform by :math:`Q` followed by the division by :math:`W`. When :math:`|W| > 10^{-8}`, an overall sign on :math:`Q` cancels in that divide, so :math:`Q` and :math:`-Q` give the same points. When :math:`|W| \leq 10^{-8}`, Kornia's homogeneous conversion returns the numerator unchanged, so the two matrices give opposing values. :class:`StereoCamera` builds exactly the matrix above, with :math:`tx = P_1[0, 3] / fx` as :math:`P_1` defines it; its constructor requires that product to be strictly negative for every rig in the batch, so :math:`tx` here is negative on every rig it accepts. The class's ``tx`` attribute is the negation of this symbol, :math:`-P_1[0, 3] / fx`. Substituting the attribute's value for :math:`tx` above gives neither the class's :math:`Q` nor its negation, because the last row carries no :math:`tx` and does not flip.+The :math:`Q` that :class:`StereoCamera` builds is exactly this matrix with :math:`tx = P_1[0, 3] / fx`, which the constructor requires to be strictly negative (a zero baseline or swapped cameras raise). The class's ``tx`` attribute is the positive baseline :math:`-P_1[0, 3] / fx`, so do not substitute it for :math:`tx` above.-The :math:`Q[3, 3]` term carries :math:`fy * (cx_{left} - cx_{right})` for a setup whose principal points differ in :math:`cx`, but :class:`StereoCamera` rejects such a pair today: its constructor requires the two projection matrices to be equal outside the last column, so :math:`cx_{left} = cx_{right}` and that factor is zero. This is tracked in `#4270 <https://github.com/kornia/kornia/issues/4270>`_.+The :math:`Q[3, 3]` term is zero on every rig :class:`StereoCamera` accepts outside ``torch.export``: the constructor rejects differing :math:`cx_{left}` and :math:`cx_{right}` (`#4270 <https://github.com/kornia/kornia/issues/4270>`_).Assuming :math:`fx = fy` you can further reduce this to:diff --git a/docs/source/get-started/camera-conventions.rst b/docs/source/get-started/camera-conventions.rstindex 4b514bb26..a540925db 100644--- a/docs/source/get-started/camera-conventions.rst+++ b/docs/source/get-started/camera-conventions.rst@@ -79,8 +79,7 @@ rest of the functional camera API assume.:meth:`kornia.geometry.camera.pinhole.PinholeCamera.scale` (and ``scale_``, and:meth:`kornia.sensors.camera.PinholeModel.scale`) rescale the principal point as ``cx' = s * cx`` β the COLMAP- rule β which disagrees with the integer pixel centres the rest of the library uses. It is documented as it- is and tracked as a coordinated repair in+ rule β which disagrees with the integer pixel centres the rest of the library uses:`#4263 <https://github.com/kornia/kornia/issues/4263>`_.Camera and world frames@@ -188,7 +187,7 @@ Intrinsics layoutand ``intrinsics[3, 3]`` rescales every unprojected point. The layout is not validated: a ``3x3`` ``K`` zero-paddedwithout ``intrinsics[3, 3] = 1`` still projects, but ``unproject`` fails on a singular matrix(`#4771 <https://github.com/kornia/kornia/issues/4771>`_). Its class docstring documents the layout and the- deviations.+ zero-padded case.- **Depth means two different things.** It is the camera-frame ``z`` by default, and the Euclidean ray lengthwhen :func:`kornia.geometry.camera.perspective.unproject_points` is called with ``normalize=True`` (the``normalize_points`` flags of :func:`kornia.geometry.depth.depth_to_3d` anddiff --git a/docs/source/sensors.camera.rst b/docs/source/sensors.camera.rstindex 891df11df..27747882b 100644--- a/docs/source/sensors.camera.rst+++ b/docs/source/sensors.camera.rst@@ -7,7 +7,7 @@ kornia.sensors.camera.. 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`, 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>`_.+ :mod:`kornia.sensors.camera` is an experimental API and is subject to change. Once finished, it will subsume :mod:`kornia.geometry.camera`, although the two are kept separate by design -- they share the mathematical Pinhole mapping but differ in input types, camera-axis broadcasting and zero-depth handling (see the Convention block and warning 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.diff --git a/kornia/feature/responses.py b/kornia/feature/responses.pyindex 5e8ee8d4a..f1c5ad672 100644--- a/kornia/feature/responses.py+++ b/kornia/feature/responses.py@@ -51,7 +51,7 @@ def harris_response(.. math::R = max(0, det(M) - k \cdot trace(M)^2)- torch.where:+ where:.. math::M = \sum_{(x,y) \in W}@@ -137,7 +137,7 @@ def gftt_response(.. math::R = min(eig(M))- torch.where:+ where:.. math::M = \sum_{(x,y) \in W}@@ -213,7 +213,7 @@ def hessian_response(.. math::R = det(H)- torch.where:+ where:.. math::M = \sum_{(x,y) \in W}diff --git a/kornia/geometry/bbox.py b/kornia/geometry/bbox.pyindex 9854f301a..cde87224f 100644--- a/kornia/geometry/bbox.py+++ b/kornia/geometry/bbox.py@@ -44,21 +44,14 @@ def validate_bbox(boxes: torch.Tensor) -> bool:"""Validate whether a 2D box has matching top and bottom edge vectors.Convention:- Vertices use inclusive coordinates in clockwise top-left, top-right, bottom-right, bottom-left order.- The function accepts :math:`(B, 4, 2)` tensors and :math:`(B, N, 4, 2)` tensors. It returns ``False`` for an- invalid shape or when corresponding components of the top and bottom edge vectors differ by more than- ``1e-4``; it does not raise for those inputs. It does not check right angles, positive area, or clockwise- direction. A parallelogram whose- vertices follow a cyclic order passes, including cyclic rotations, either direction, rotated rectangles,- and zero-area boxes; other vertex relabelings can fail. The inclusive ``+1`` terms, tracked in- `#3934 <https://github.com/kornia/kornia/issues/3934>`_, cancel in exact arithmetic, but finite-precision- rounding can make the result differ from exclusive arithmetic, particularly for low-precision dtypes.- Rank-4 input is flattened with ``reshape``, so any stride layout is accepted, matching the shape the- docstring documents.+ Vertices are inclusive, in clockwise top-left, top-right, bottom-right, bottom-left order (see+ :func:`infer_bbox_shape`). Accepts :math:`(B, 4, 2)` and :math:`(B, N, 4, 2)`. Returns ``False``, without+ raising, for an invalid shape or when the top and bottom edge vectors differ by more than ``1e-4``. Right+ angles, positive area and direction are not checked, so any parallelogram in cyclic vertex order passes... warning::- :func:`validate_bbox3d` raises ``AssertionError`` where this function returns ``False``. That- inconsistency is tracked in `#4013 <https://github.com/kornia/kornia/issues/4013>`_.+ :func:`validate_bbox3d` raises ``AssertionError`` where this function returns ``False``:+ `#4013 <https://github.com/kornia/kornia/issues/4013>`_.Args:boxes: a tensor containing the coordinates of the bounding boxes to be extracted. The tensor must have the shape@@ -102,21 +95,15 @@ def validate_bbox3d(boxes: torch.Tensor) -> bool:r"""Validate that a 3D box has equal inclusive edge extents along each axis, raising when it does not.Convention:- Vertices use inclusive coordinates in the order front-top-left, front-top-right, front-bottom-right,- front-bottom-left, then the same four back vertices. The function accepts :math:`(B, 8, 3)` and- :math:`(B, N, 8, 3)` tensors and raises ``AssertionError`` for any other shape. It compares the inclusive- ``+1`` extents of the four edges parallel to each axis and raises ``AssertionError`` when they differ, so a- sheared parallelepiped with equal edge lengths and a zero-extent box both pass; it does not check right- angles or positive extent. A box with a non-finite coordinate returns ``False``. Under graph capture- the extent checks are skipped and the shape check alone returns ``True``. The ``+1`` terms cancel- in exact arithmetic and are tracked in- `#3934 <https://github.com/kornia/kornia/issues/3934>`_.+ Vertices are inclusive, front-top-left, front-top-right, front-bottom-right, front-bottom-left, then the+ same four back vertices. Accepts :math:`(B, 8, 3)` and :math:`(B, N, 8, 3)`; another shape, or unequal+ extents of the four edges parallel to an axis, raises ``AssertionError``. Right angles and positive+ extent are not checked. A non-finite coordinate returns ``False``. Under graph capture only the shape is+ checked... warning::- :func:`validate_bbox` returns ``False`` where this function raises; that inconsistency is tracked in- `#4013 <https://github.com/kornia/kornia/issues/4013>`_. Rank-4 input passes this check, but- :func:`infer_bbox_shape3d` and :func:`bbox_to_mask3d` reject it with- :class:`~kornia.core.exceptions.ShapeError`: flatten to :math:`(B \cdot N, 8, 3)` before calling them.+ :func:`validate_bbox` returns ``False`` where this function raises:+ `#4013 <https://github.com/kornia/kornia/issues/4013>`_.Args:boxes: a tensor containing the coordinates of the bounding boxes to be extracted. The tensor must have the shape@@ -168,19 +155,18 @@ def infer_bbox_shape(boxes: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:r"""Auto-infer the output sizes for the given 2D bounding boxes.Convention:- Vertices use inclusive coordinates in clockwise top-left, top-right, bottom-right, bottom-left order.- The returned tuple is ``(heights, widths)``, in that order. Both extents are read from fixed vertex- indices, as ``width = boxes[:, 1, 0] - boxes[:, 0, 0] + 1`` and- ``height = boxes[:, 2, 1] - boxes[:, 0, 1] + 1``, rather than from a ``maximum - minimum`` reduction.- The two agree for an axis-aligned box in the documented order; for any other vertex order, including the- rotated quadrilaterals that :func:`transform_bbox` produces for polygon input, they can diverge and the- result can be negative.- :meth:`kornia.geometry.boxes.Boxes.get_boxes_shape` is reduction based and does not share that behavior.- The fixed-index reading also lets zero-width boxes emitted by :func:`bbox_generator` report width ``0``- rather than ``2`` under a reduction; :class:`~kornia.augmentation.RandomCutMixV2` relies on that behavior.+ Vertices are **inclusive**: a box covering pixels ``0..9`` has corners at ``0`` and ``9`` and width+ ``10``. The vertex-based helpers of this module share it, except :func:`bbox_generator3d`+ (`#4018 <https://github.com/kornia/kornia/issues/4018>`_); :func:`nms` takes exclusive ``xyxy`` and+ :func:`transform_bbox` converts ``'xywh'`` exclusively (``xmax = xmin + width``).+ The order is clockwise top-left, top-right, bottom-right, bottom-left. The result is+ ``(heights, widths)``, read from fixed vertex indices, ``width = boxes[:, 1, 0] - boxes[:, 0, 0] + 1`` and+ ``height = boxes[:, 2, 1] - boxes[:, 0, 1] + 1``, not from a ``max - min`` reduction, so a box in+ another vertex order (such as a rotated polygon from :func:`transform_bbox`) can give a negative extent.+ :meth:`kornia.geometry.boxes.Boxes.get_boxes_shape` is reduction based... warning::- The inclusive ``+1`` arithmetic differs from torchvision, COCO, and albumentations and is tracked in+ The inclusive ``+1`` arithmetic differs from torchvision, COCO and albumentations, which are exclusive:`#3934 <https://github.com/kornia/kornia/issues/3934>`_.Args:@@ -222,24 +208,18 @@ def infer_bbox_shape3d(boxes: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor,r"""Auto-infer the output sizes for the given 3D bounding boxes.Convention:- Vertices use inclusive coordinates in the order front-top-left, front-top-right, front-bottom-right,- front-bottom-left, then the same four back vertices. The returned tuple is ``(depths, heights, widths)``,- in that order, each read as ``max - min + 1`` along one edge of the box after :func:`validate_bbox3d`- has established that the edges parallel to each axis have equal extent. Like :func:`infer_bbox_shape`,- the function adds one per axis, so pass the ``'vertices_plus'`` export of- :class:`~kornia.geometry.boxes.Boxes3D` rather than ``'vertices'``, which it reads as one larger per axis.+ Vertices are inclusive (see :func:`infer_bbox_shape`), in :func:`validate_bbox3d` order. The result is+ ``(depths, heights, widths)``, each read from fixed vertex indices like :func:`infer_bbox_shape` (for+ example ``width = boxes[:, 1, 0] - boxes[:, 0, 0] + 1``), so another vertex order can give a negative+ extent. Pass the ``'vertices_plus'``+ export of :class:`~kornia.geometry.boxes.Boxes3D`; ``'vertices'`` reads one larger per axis.+ :math:`(B, N, 8, 3)` input raises :class:`~kornia.core.exceptions.ShapeError`; flatten it first... warning::- The inclusive ``+1`` arithmetic differs from torchvision, COCO, and albumentations and is tracked in- `#3934 <https://github.com/kornia/kornia/issues/3934>`_; the exclusive-export trap is- `#4009 <https://github.com/kornia/kornia/issues/4009>`_. Validation raises ``AssertionError`` rather than- returning ``False`` for a shape or extent failure, see- `#4013 <https://github.com/kornia/kornia/issues/4013>`_; a non-finite coordinate is the one case- :func:`validate_bbox3d` reports as ``False``, and this function raises ``AssertionError`` for it too.- Batched :math:`(B, N, 8, 3)` input is rejected with :class:`~kornia.core.exceptions.ShapeError`, as- the 2D helpers reject :math:`(B, N, 4, 2)`; flatten to :math:`(B \cdot N, 8, 3)` first.- :func:`validate_bbox3d` still accepts the rank-4 form and reshapes internally, which is why the- rejection lives here rather than there.+ The ``+1`` is `#3934 <https://github.com/kornia/kornia/issues/3934>`_ and the exclusive-export trap+ `#4009 <https://github.com/kornia/kornia/issues/4009>`_. An invalid box, including a non-finite+ coordinate, raises ``AssertionError`` rather than being reported:+ `#4013 <https://github.com/kornia/kornia/issues/4013>`_.Args:boxes: a tensor containing the coordinates of the bounding boxes to be extracted. The tensor must have the shape@@ -299,22 +279,18 @@ def bbox_to_mask(boxes: torch.Tensor, width: int, height: int) -> torch.Tensor:"""Convert 2D bounding boxes to masks. Covered area is 1. and the remaining is 0.Convention:- The image size is given as ``(width, height)`` while the mask comes back as :math:`(B, height, width)`;- :meth:`kornia.geometry.boxes.Boxes.to_mask` takes ``(height, width)`` for the same result. Only the top-left- (index 0) and bottom-right (index 2) vertices are read and the other two are ignored, so a non-rectangular- quadrilateral is masked by the axis-aligned box those two vertices span. A pixel is covered when its integer- coordinates satisfy ``xmin <= x <= xmax`` and ``ymin <= y <= ymax`` on the raw, unrounded values, which- reads the vertices as inclusive: pass the ``'vertices_plus'`` export of- :class:`~kornia.geometry.boxes.Boxes`, not ``'vertices'``. The mask has the input dtype, including integer- dtypes, and no gradient path. Input must be unbatched :math:`(B, 4, 2)`; :math:`(B, N, 4, 2)` raises- :class:`~kornia.core.exceptions.ShapeError`.+ The size is ``(width, height)`` and the mask :math:`(B, height, width)`;+ :meth:`kornia.geometry.boxes.Boxes.to_mask` takes ``(height, width)``. Only vertices 0 (top-left) and 2+ (bottom-right) are read. A pixel is covered when ``xmin <= x <= xmax`` and ``ymin <= y <= ymax`` on the+ unrounded values, i.e. inclusively: pass the ``'vertices_plus'`` export of+ :class:`~kornia.geometry.boxes.Boxes`. The mask has the input dtype and no gradient path.+ :math:`(B, N, 4, 2)` raises :class:`~kornia.core.exceptions.ShapeError`... warning::- The ``(width, height)`` argument order is tracked in `#4014 <https://github.com/kornia/kornia/issues/4014>`_.- The inclusive raw-float comparison differs from the rounding in- :meth:`~kornia.geometry.boxes.Boxes.to_mask` and the truncation in :func:`bbox_to_mask3d` for fractional- coordinates and is tracked in `#4015 <https://github.com/kornia/kornia/issues/4015>`_; the exclusive-export- trap is `#4009 <https://github.com/kornia/kornia/issues/4009>`_.+ The ``(width, height)`` order is `#4014 <https://github.com/kornia/kornia/issues/4014>`_. For fractional+ coordinates the raw comparison differs from the rounding of :meth:`~kornia.geometry.boxes.Boxes.to_mask`+ and the truncation of :func:`bbox_to_mask3d`: `#4015 <https://github.com/kornia/kornia/issues/4015>`_.+ The exclusive-export trap is `#4009 <https://github.com/kornia/kornia/issues/4009>`_.Args:boxes: a tensor containing the coordinates of the bounding boxes to be extracted. The tensor must have the shape@@ -387,25 +363,17 @@ def bbox_to_mask3d(boxes: torch.Tensor, size: tuple[int, int, int]) -> torch.Tenr"""Convert 3D bounding boxes to masks. Covered area is 1. and the remaining is 0.Convention:- ``size`` is ``(depth, height, width)`` and the mask comes back as :math:`(B, 1, depth, height, width)` in the- input dtype, like :func:`bbox_to_mask`, which keeps the input dtype and has no channel axis, and- :meth:`kornia.geometry.boxes.Boxes3D.to_mask`, which keeps the box dtype and returns- :math:`(N, depth, height, width)`. After :func:`validate_bbox3d`, which raises ``AssertionError`` for an- invalid box, the bounds are read from fixed vertex positions, truncated toward zero with ``.long()``, and- compared inclusively, which reads the vertices as inclusive: pass the ``'vertices_plus'`` export. The- intersection of the three axis ranges is always recovered, including when a box covers or overhangs a- whole output axis. There is no gradient path.+ ``size`` is ``(depth, height, width)`` and the mask :math:`(B, 1, depth, height, width)` in the input+ dtype, with a channel axis that :func:`bbox_to_mask` does not have+ (:meth:`kornia.geometry.boxes.Boxes3D.to_mask` returns :math:`(N, depth, height, width)`). The bounds are+ truncated toward zero and compared inclusively: pass the ``'vertices_plus'`` export. There is no+ gradient path. :math:`(B, N, 8, 3)` input raises :class:`~kornia.core.exceptions.ShapeError`... warning::- The truncation differs from the inclusive- raw-float comparison of :func:`bbox_to_mask` and the rounding of- :meth:`~kornia.geometry.boxes.Boxes3D.to_mask` for fractional coordinates and is tracked in- `#4015 <https://github.com/kornia/kornia/issues/4015>`_. Validation raises rather than returning- ``False`` for a shape or extent failure, `#4013 <https://github.com/kornia/kornia/issues/4013>`_; a- non-finite coordinate is reported as ``False`` by :func:`validate_bbox3d` and raised here too.- Batched :math:`(B, N, 8, 3)` input passes- :func:`validate_bbox3d` but is rejected here with :class:`~kornia.core.exceptions.ShapeError`; flatten to- :math:`(B \cdot N, 8, 3)` first.+ For fractional coordinates the truncation differs from :func:`bbox_to_mask` and+ :meth:`~kornia.geometry.boxes.Boxes3D.to_mask`: `#4015 <https://github.com/kornia/kornia/issues/4015>`_.+ An invalid box, including a non-finite coordinate, raises ``AssertionError``:+ `#4013 <https://github.com/kornia/kornia/issues/4013>`_.Args:boxes: a tensor containing the coordinates of the bounding boxes to be extracted. The tensor must have the shape@@ -492,15 +460,13 @@ def bbox_generator("""Generate 2D bounding boxes according to the provided start coords, width and height.Convention:- The far corner is placed at ``start + size - 1`` on each axis, so the generated box is inclusive:- :func:`infer_bbox_shape` reads back exactly ``width`` and ``height``, and a zero size places the far- corner one before the start. The vertex order is top-left, top-right, bottom-right, bottom-left. A scalar- input produces a batch of one. All four tensors must share dtype and device, otherwise ``AssertionError``- is raised; the output has that dtype and device and keeps a gradient path to the inputs.+ The far corner is at ``start + size - 1`` (inclusive, see :func:`infer_bbox_shape`), so+ :func:`infer_bbox_shape` reads back ``width`` and ``height``; a zero size puts the far corner one before+ the start. A scalar input gives a batch of one. The four tensors must share dtype and device, otherwise+ ``AssertionError``; the output keeps a gradient path... warning::- The inclusive arithmetic is tracked in `#3934 <https://github.com/kornia/kornia/issues/3934>`_.- :func:`bbox_generator3d` places its far corner at ``start + size`` instead, see+ :func:`bbox_generator3d` places its far corner at ``start + size`` instead:`#4018 <https://github.com/kornia/kornia/issues/4018>`_.Args:@@ -576,16 +542,13 @@ def bbox_generator3d("""Generate 3D bounding boxes according to the provided start coords, width, height and depth.Convention:- The far corner is placed at ``start + size`` on each axis, one further than :func:`bbox_generator`, so- :func:`infer_bbox_shape3d` reads back ``size + 1`` on every axis; the example below shows it. The four- front vertices precede the four back vertices. A scalar input produces a batch of one. All six tensors- must share dtype and device, otherwise ``AssertionError`` is raised; the output has that dtype and device- and keeps a gradient path to the inputs.+ The four front vertices precede the four back vertices. A scalar input gives a batch of one. The six+ tensors must share dtype and device, otherwise ``AssertionError``; the output keeps a gradient path... warning::- The extra unit of extent relative to :func:`bbox_generator` and to the inclusive- :func:`infer_bbox_shape3d` is tracked as a coordinated repair in- `#4018 <https://github.com/kornia/kornia/issues/4018>`_ and is documented as it is.+ The far corner is at ``start + size``, one further than :func:`bbox_generator`, so+ :func:`infer_bbox_shape3d` reads back ``size + 1`` on every axis:+ `#4018 <https://github.com/kornia/kornia/issues/4018>`_.Args:x_start: a tensor containing the x coordinates of the bounding boxes to be extracted. Shape must be a scalardiff --git a/kornia/geometry/boxes.py b/kornia/geometry/boxes.pyindex 1b2e7c18b..2bf101a47 100644--- a/kornia/geometry/boxes.py+++ b/kornia/geometry/boxes.py@@ -196,74 +196,39 @@ class Boxes:convert ``boxes``; use :meth:`from_tensor` to import another representation.Convention:- - A box is a quadrilateral of four floating-point ``(x, y)`` vertices, stored as :math:`(N, 4, 2)` or- :math:`(B, N, 4, 2)` data. Axis-aligned boxes are built in clockwise top-left, top-right,- bottom-right, bottom-left order, but the vertices stay arbitrary: :meth:`transform_boxes` produces- rotated quadrilaterals. :meth:`compute_area` sorts vertices by angle about their arithmetic centroid- before applying the shoelace formula, so it assumes a convex quadrilateral and uses an exclusive area- convention that can disagree with :meth:`get_boxes_shape` and :meth:`to_mask`.- - The stored form is inclusive (``'vertices_plus'``): ``width = xmax - xmin + 1``. The exclusive- ``'xyxy'``, ``'xywh'``, and ``'vertices'`` modes convert to this form in :meth:`from_tensor` and back- in :meth:`to_tensor`. The constructor converts nothing and stores ``mode`` as a label. For exclusive- vertex data ``d``, ``Boxes(d, mode='vertices').to_tensor()`` applies export offsets to unconverted data,- while ``Boxes.from_tensor(d, mode='vertices')`` imports it before export; the round-trip conditions and- limitations are described next.- - An axis-aligned box in the documented vertex order whose extent is at least one unit per axis- round-trips exactly in its own mode when every intermediate conversion result is exactly representable- in the tensor dtype. A sub-unit extent does not: the inclusive ``- 1`` inverts the stored quadrilateral,- so normalized ``[0, 1]`` boxes with a sub-unit span on either axis are silently corrupted by the three- converting modes.- The ``'xyxy_plus'`` mode is unaffected because its ``+ 1`` cancels the ``- 1``;- ``'vertices_plus'`` applies no offset at all.- - :meth:`to_tensor` reduces the stored vertices with ``amin``/``amax``, so every export is an- axis-aligned bounding box. It is lossy for rotated boxes, and ``to_tensor('vertices_plus')`` is- therefore not the identity on :attr:`data`.- - :meth:`get_boxes_shape` returns ``(heights, widths)`` in that order, with exactly the values from- ``to_tensor('xywh', as_padded_sequence=True)``. For a list-backed object this includes its padding- entries, which report as 1-by-1 boxes under the inclusive ``+1`` convention even though an ordinary- :meth:`to_tensor` export trims them.- - :func:`~kornia.geometry.bbox.infer_bbox_shape`, :func:`~kornia.geometry.bbox.bbox_to_mask`,- :func:`~kornia.geometry.bbox.validate_bbox`, and :func:`~kornia.geometry.bbox.nms` have no mode argument,- but the module does not use one convention throughout. :func:`~kornia.geometry.bbox.infer_bbox_shape`- adds one per axis and- :func:`~kornia.geometry.bbox.bbox_to_mask` fills through the bottom-right vertex's row and column, so- both read their input as inclusive: pass them the ``'vertices_plus'`` export rather than- ``'vertices'``, which they read as one pixel larger per axis. Both consumers require unbatched- :math:`(N, 4, 2)` input and raise :class:`~kornia.core.exceptions.ShapeError` for a batched- :math:`(B, N, 4, 2)` export, so index or flatten it before passing it.- :func:`~kornia.geometry.bbox.validate_bbox` is invariant in exact arithmetic, because its ``+1``- terms cancel;- :func:`~kornia.geometry.bbox.nms` computes exclusive areas, and- :func:`~kornia.geometry.bbox.transform_bbox` converts ``'xywh'`` with the exclusive- ``xmax = xmin + width``.- - With ``validate_boxes=True``, a non-finite coordinate is rejected in every mode, and the ``'xy*'``- modes reject non-positive extents measured in that mode's- convention.- - The constructor rejects an integer tensor unless ``raise_if_not_floating_point=False``. A list input is- padded into a tensor of its *first* element's dtype before that check, so a mixed-dtype list is accepted- or rejected by its first box alone and the remaining boxes are cast to that dtype. For a single tensor,- :meth:`from_tensor` silently casts integer input to ``torch.get_default_dtype()``. For a list, it- converts each element independently and then pads into the first converted element's dtype,- recasting the remaining elements.- - :meth:`merge` concatenates boxes along the box axis and repacks list-backed batch rows so their padding- remains at the end, while :meth:`index_put` replaces selected coordinates. Both methods are non-mutating- by default.+ - A box is a quadrilateral of four floating-point ``(x, y)`` vertices, :math:`(N, 4, 2)` or+ :math:`(B, N, 4, 2)`, built in clockwise top-left, top-right, bottom-right, bottom-left order;+ :meth:`transform_boxes` can make it an arbitrary (rotated) quadrilateral.+ - The stored form is **inclusive** (``'vertices_plus'``): ``width = xmax - xmin + 1``. The exclusive+ ``'xyxy'``, ``'xywh'`` and ``'vertices'`` modes are converted by :meth:`from_tensor` and+ :meth:`to_tensor`; the constructor converts nothing and only records ``mode``.+ - :meth:`to_tensor` reduces the vertices with ``amin``/``amax``, so every export is an axis-aligned+ bounding box and ``to_tensor('vertices_plus')`` is not the identity for a rotated box.+ - :meth:`get_boxes_shape` returns ``(heights, widths)``; padding entries of a list-backed object report+ as 1-by-1 boxes (the inclusive ``+1``, `#3934 <https://github.com/kornia/kornia/issues/3934>`_).+ - :func:`~kornia.geometry.bbox.infer_bbox_shape` and :func:`~kornia.geometry.bbox.bbox_to_mask` read+ their input as inclusive: pass them the ``'vertices_plus'`` export, unbatched.+ :func:`~kornia.geometry.bbox.nms` takes exclusive ``xyxy``.+ - With ``validate_boxes=True``, the ``'xy*'`` modes reject a non-finite coordinate and non-positive+ extents.+ - The constructor rejects an integer tensor unless ``raise_if_not_floating_point=False`` (a list is+ checked by its first element's dtype); :meth:`from_tensor` casts integer input to the default dtype.+ - :meth:`merge` and :meth:`index_put` are non-mutating by default... warning::- The inclusive ``+1`` arithmetic differs from torchvision, COCO, and albumentations and is tracked as a- coordinated repair in `#3934 <https://github.com/kornia/kornia/issues/3934>`_. The sub-unit conversion- corruption is `#4061 <https://github.com/kornia/kornia/issues/4061>`_, the cross-module export trap is- `#4009 <https://github.com/kornia/kornia/issues/4009>`_, the exclusive :meth:`compute_area` convention is- `#4010 <https://github.com/kornia/kornia/issues/4010>`_, and the exclusive- :func:`~kornia.geometry.bbox.nms` convention is- `#4008 <https://github.com/kornia/kornia/issues/4008>`_. The differing ``width``/``height`` argument order- of :func:`~kornia.geometry.bbox.bbox_to_mask` and :meth:`to_mask` is tracked in- `#4014 <https://github.com/kornia/kornia/issues/4014>`_. The integer-input policy split between the- constructor and :meth:`from_tensor` is- `#4012 <https://github.com/kornia/kornia/issues/4012>`_. With ``validate_boxes=True``, vertex modes remain- unvalidated, and ``'vertices'`` also subtracts one from fixed vertex positions, potentially deforming the- input rather than rejecting it; this is tracked in `#4177 <https://github.com/kornia/kornia/issues/4177>`_.- The unimplemented ``trim``, ``translate(method='fast')``, and tuple-bound ``clamp`` paths are tracked in+ The inclusive ``+1`` differs from torchvision, COCO and albumentations:+ `#3934 <https://github.com/kornia/kornia/issues/3934>`_. A sub-unit extent (normalized ``[0, 1]`` boxes)+ is corrupted by the ``- 1`` of the converting modes: `#4061 <https://github.com/kornia/kornia/issues/4061>`_.+ Passing the ``'vertices'`` export to the bbox helpers reads one pixel larger:+ `#4009 <https://github.com/kornia/kornia/issues/4009>`_. :meth:`compute_area` is the shoelace area of the+ stored inclusive vertices, ``(width - 1) * (height - 1)``:+ `#4010 <https://github.com/kornia/kornia/issues/4010>`_. :func:`~kornia.geometry.bbox.nms` is exclusive:+ `#4008 <https://github.com/kornia/kornia/issues/4008>`_. :meth:`to_mask` and+ :func:`~kornia.geometry.bbox.bbox_to_mask` take opposite size orders:+ `#4014 <https://github.com/kornia/kornia/issues/4014>`_. The integer-input split is+ `#4012 <https://github.com/kornia/kornia/issues/4012>`_. Vertex modes are not validated and+ ``'vertices'`` can deform the input: `#4177 <https://github.com/kornia/kornia/issues/4177>`_. ``trim``,+ ``translate(method='fast')`` and tuple-bound ``clamp`` are unimplemented:`#4017 <https://github.com/kornia/kornia/issues/4017>`_."""@@ -527,18 +492,9 @@ class Boxes:See the Convention block on :class:`~kornia.geometry.boxes.Boxes`.Convention:- Bounds must be tensors with one ``(x, y)`` pair per batch element,- or a single row that broadcasts across the batch.- Every vertex is clamped independently, so a box wholly outside the- bounds collapses onto the nearest boundary instead of being removed.- Both the batched :math:`(B, N, 4, 2)` and the unbatched- :math:`(N, 4, 2)` container are supported; the unbatched form carries- a single image, so the bounds must have exactly one row.-- Coordinates below ``topleft`` are raised to the lower bound and- coordinates above ``botright`` are lowered to the upper bound. The- implementation accepts only tensor bounds with one ``(x, y)`` pair per- batch element, or a single row that broadcasts across the batch.+ Bounds are tensors with one ``(x, y)`` pair per batch element, or a single row that broadcasts (an+ unbatched container needs exactly one row). Every vertex is clamped independently, so a box wholly+ outside the bounds collapses onto the boundary instead of being removed.Args:topleft: Tensor of shape :math:`(B, 2)` containing the minimum@@ -649,15 +605,11 @@ class Boxes:See the Convention block on :class:`~kornia.geometry.boxes.Boxes`.Convention:- For axis-aligned boxes, the shoelace result over stored inclusive- vertices is ``(width - 1) * (height - 1)``, while the inclusive- terms from :meth:`get_boxes_shape` multiply to ``width * height``.- Rotated or otherwise non-axis-aligned quadrilaterals use their- polygon area instead.+ Vertices are sorted by angle about their centroid, so a convex quadrilateral is assumed... warning::- The differing area conventions are tracked in- `#4010 <https://github.com/kornia/kornia/issues/4010>`_.+ On the stored inclusive vertices an axis-aligned box gives ``(width - 1) * (height - 1)``, not the+ ``width * height`` of :meth:`get_boxes_shape`: `#4010 <https://github.com/kornia/kornia/issues/4010>`_.Returns:Area for each box, shaped :math:`(N,)` or :math:`(B, N)`.@@ -701,8 +653,8 @@ class Boxes:* 'vertices_plus': the inclusive stored vertex form. With shape :math:`(N, 4, 2)`,:math:`(B, N, 4, 2)`.- validate_boxes: Reject a non-finite coordinate, and check extents for the ``'xy*'`` modes in each- mode's convention. The extent half has no validation effect for vertex modes; see the warning on+ validate_boxes: For the ``'xy*'`` modes, reject a non-finite coordinate and non-positive extents in+ each mode's convention. The vertex modes are not validated; see the warning on:class:`~kornia.geometry.boxes.Boxes`.Returns:@@ -818,21 +770,16 @@ class Boxes:See the Convention block on :class:`~kornia.geometry.boxes.Boxes`.Convention:- The size is ``(height, width)`` and the mask is :math:`(N, height, width)` or- :math:`(B, N, height, width)` in the box dtype; :func:`~kornia.geometry.bbox.bbox_to_mask` takes- ``(width, height)`` for the same result. The boxes are exported as exclusive ``'xyxy'`` bounds (the- axis-aligned bounding box of a rotated quadrilateral), clamped to ``[0, width]`` and ``[0, height]``,- rounded to the nearest integer, and filled over the half-open ranges ``[xmin, xmax)`` and- ``[ymin, ymax)``, so a box entirely outside the image fills nothing and a fractional box can fill a- different area than :func:`~kornia.geometry.bbox.bbox_to_mask` gives for the same vertices. A- list-backed object keeps an empty mask channel for each padding entry. The loop taken on CPU and- MPS and the vectorized path taken on CUDA and under graph capture produce the same mask. A box tensor- that requires grad is rejected with ``RuntimeError``.+ The size is ``(height, width)`` and the mask :math:`(N, height, width)` or+ :math:`(B, N, height, width)` in the box dtype. The exclusive ``'xyxy'`` export is clamped to the+ image, rounded to the nearest integer and filled over ``[xmin, xmax)``, ``[ymin, ymax)``. Padding+ entries of a list-backed object give empty masks. A box tensor that requires grad raises+ ``RuntimeError``... warning::- The argument-order split with :func:`~kornia.geometry.bbox.bbox_to_mask` is tracked in- `#4014 <https://github.com/kornia/kornia/issues/4014>`_ and the rounding split in- `#4015 <https://github.com/kornia/kornia/issues/4015>`_.+ :func:`~kornia.geometry.bbox.bbox_to_mask` takes ``(width, height)``+ (`#4014 <https://github.com/kornia/kornia/issues/4014>`_) and does not round, so a fractional box can+ fill a different area (`#4015 <https://github.com/kornia/kornia/issues/4015>`_).Args:height: height of the masked image/images.@@ -957,11 +904,8 @@ class Boxes:See the Convention block on :class:`~kornia.geometry.boxes.Boxes`.Convention:- The in-place operation rebinds this object's internal tensor to a- transformed result for nonempty containers. A tensor reference- obtained from :attr:`data` before that call therefore remains- unchanged and no longer aliases the container's data. Empty- containers retain their original tensor reference.+ The internal tensor is rebound, not written: a tensor obtained from :attr:`data` before the call+ keeps the old coordinates (an empty container keeps its tensor).Returns:This :class:`Boxes` object after the transformation.@@ -1078,25 +1022,20 @@ class VideoBoxes(Boxes):See the Convention block on :class:`~kornia.geometry.boxes.Boxes`.Convention:- - :meth:`from_tensor` stores the :math:`(B, T, N, 4, 2)` input unchanged as batched- :math:`(B \cdot T, N, 4, 2)` ``'vertices_plus'`` data; there is no mode argument, no conversion and no- validation, and integer input is cast to ``torch.get_default_dtype()``.- Any other rank or last dimensions, and list input,- raise ``ValueError``.- - :meth:`to_tensor` accepts every :class:`Boxes` export mode and restores the temporal axis, so- ``to_tensor('xyxy')`` is :math:`(B, T, N, 4)`. Its default is the stored ``'vertices_plus'`` mode.- - A transformation matrix must carry one entry per flattened frame, :math:`(B \cdot T, 3, 3)`; a- :math:`(3, 3)` matrix raises ``ValueError``.- - Methods that copy through :meth:`clone`, among them :meth:`transform_boxes`, :meth:`translate`,- :meth:`clamp`, :meth:`filter_boxes_by_area` and :meth:`merge`, return a new :class:`VideoBoxes` with the- same :attr:`temporal_channel_size` and leave the source untouched. :meth:`pad`, :meth:`unpad`, :meth:`to`- and :meth:`type` update ``self`` in place and return it, so they keep the temporal size but change the- original coordinates or dtype.+ - :meth:`from_tensor` stores :math:`(B, T, N, 4, 2)` input unchanged as :math:`(B \cdot T, N, 4, 2)`+ ``'vertices_plus'`` data, with no mode, conversion or validation; integer input is cast to the default+ dtype, and another shape or a list raises ``ValueError``.+ - :meth:`to_tensor` accepts every :class:`Boxes` mode and restores the temporal axis+ (``to_tensor('xyxy')`` is :math:`(B, T, N, 4)`).+ - A transformation matrix is :math:`(B \cdot T, 3, 3)`; a :math:`(3, 3)` matrix raises ``ValueError``+ unless :math:`B \cdot T = 1`.+ - :meth:`transform_boxes`, :meth:`translate`, :meth:`clamp`, :meth:`filter_boxes_by_area` and+ :meth:`merge` return a new :class:`VideoBoxes`; :meth:`pad`, :meth:`unpad`, :meth:`to` and+ :meth:`type` update ``self`` in place... warning::Indexing returns a wrapper without :attr:`temporal_channel_size`, so its :meth:`to_tensor` raises- ``AttributeError``; this is the remaining half of- `#4249 <https://github.com/kornia/kornia/issues/4249>`_. The inert ``validate_boxes`` flag is part of+ ``AttributeError``: `#4249 <https://github.com/kornia/kornia/issues/4249>`_. ``validate_boxes`` is inert:`#4177 <https://github.com/kornia/kornia/issues/4177>`_.Attributes:@@ -1195,47 +1134,32 @@ class Boxes3D:Convention:- A box is a `hexahedron <https://en.wikipedia.org/wiki/Hexahedron>`_ of eight floating-point- ``(x, y, z)`` vertices, stored as :math:`(N, 8, 3)` or :math:`(B, N, 8, 3)` data, in the order- front-top-left, front-top-right, front-bottom-right, front-bottom-left, then the same four back- vertices. The vertices stay arbitrary after :meth:`transform_boxes`.- - The stored form is inclusive: ``width = xmax - xmin + 1``, ``height = ymax - ymin + 1`` and- ``depth = zmax - zmin + 1``. The exclusive ``'xyzxyz'`` and ``'xyzwhd'`` modes subtract one from the- max corner in :meth:`from_tensor` and add it back in :meth:`to_tensor`; ``'xyzxyz_plus'`` is stored as- given. :meth:`from_tensor` accepts only :math:`(N, 6)` or :math:`(B, N, 6)` input in those three modes;- the vertex modes ``'vertices'`` (exclusive) and ``'vertices_plus'`` (the stored form) exist for- :meth:`to_tensor` only. Mode strings are lowercased before use.- - :meth:`to_tensor` reduces the stored vertices with ``amin``/``amax``, so every export is an axis-aligned- bounding box and ``to_tensor('vertices_plus')`` is not the identity on :attr:`data` for a rotated box.- Its default mode is ``'xyzxyz'`` whatever the stored label, unlike :meth:`Boxes.to_tensor`, which- defaults to the stored mode.- - :meth:`get_boxes_shape` returns ``(depths, heights, widths)`` in that order, in the inclusive terms.- - :func:`~kornia.geometry.bbox.validate_bbox3d`, :func:`~kornia.geometry.bbox.infer_bbox_shape3d` and- :func:`~kornia.geometry.bbox.bbox_to_mask3d` have no mode argument and read their input as inclusive:- pass them the ``'vertices_plus'`` export, never ``'vertices'``, which they read as one larger per axis.- The validator also accepts batched :math:`(B, N, 8, 3)` input, but the shape and mask helpers require- unbatched :math:`(N, 8, 3)` input; see their warnings.- - With ``validate_boxes=True``, :meth:`from_tensor` rejects a non-finite coordinate, and extents that- are not positive in the given mode's convention, so ``xmax == xmin`` is rejected in ``'xyzxyz'`` and- accepted in ``'xyzxyz_plus'``.+ ``(x, y, z)`` vertices, :math:`(N, 8, 3)` or :math:`(B, N, 8, 3)`: front-top-left, front-top-right,+ front-bottom-right, front-bottom-left, then the same four back vertices.+ - The stored form is **inclusive** (``depth = zmax - zmin + 1``), as for :class:`Boxes`. :meth:`from_tensor`+ takes :math:`(N, 6)` or :math:`(B, N, 6)` in ``'xyzxyz'``, ``'xyzwhd'`` (exclusive) or+ ``'xyzxyz_plus'``; the vertex modes exist for :meth:`to_tensor` only. Modes are case-insensitive.+ - :meth:`to_tensor` exports the ``amin``/``amax`` axis-aligned bounding box and defaults to ``'xyzxyz'``+ whatever the stored label.+ - :meth:`get_boxes_shape` returns ``(depths, heights, widths)``, inclusive.+ - :func:`~kornia.geometry.bbox.infer_bbox_shape3d` and :func:`~kornia.geometry.bbox.bbox_to_mask3d` read+ their input as inclusive: pass them the ``'vertices_plus'`` export, unbatched.+ - With ``validate_boxes=True``, :meth:`from_tensor` rejects a non-finite coordinate and extents that are+ not positive in the given mode (``xmax == xmin`` fails in ``'xyzxyz'``, passes in ``'xyzxyz_plus'``).- The constructor rejects an integer tensor unless ``raise_if_not_floating_point=False``;- :meth:`from_tensor` silently casts integer input to ``torch.get_default_dtype()``.- - :meth:`transform_boxes` leaves the source unchanged and returns a new object labelled- ``'xyzxyz_plus'``; :meth:`transform_boxes_` rebinds the internal tensor of ``self`` and keeps the label.+ :meth:`from_tensor` casts integer input to the default dtype.+ - :meth:`transform_boxes` returns a new object labelled ``'xyzxyz_plus'``; :meth:`transform_boxes_`+ rebinds the internal tensor of ``self`` and keeps the label... warning::- The inclusive ``+1`` arithmetic differs from torchvision, COCO, and albumentations and is tracked as a- coordinated repair in `#3934 <https://github.com/kornia/kornia/issues/3934>`_. The exclusive-export trap is- `#4009 <https://github.com/kornia/kornia/issues/4009>`_, the integer-input policy split is- `#4012 <https://github.com/kornia/kornia/issues/4012>`_, the validator contract split with- :func:`~kornia.geometry.bbox.validate_bbox` is `#4013 <https://github.com/kornia/kornia/issues/4013>`_, and- boxes built by :func:`~kornia.geometry.bbox.bbox_generator3d` measure one larger than requested,- `#4018 <https://github.com/kornia/kornia/issues/4018>`_. The :meth:`to_tensor` default-mode split with- :class:`Boxes` is tracked in `#4251 <https://github.com/kornia/kornia/issues/4251>`_. The free functions- reject rank-4 input rather than misreading it, so flatten to :math:`(B \cdot N, 8, 3)` before calling- :func:`~kornia.geometry.bbox.infer_bbox_shape3d` or :func:`~kornia.geometry.bbox.bbox_to_mask3d`.- :meth:`to_mask` rejects- boxes that require grad even though :meth:`to_tensor` is differentiable; see the note on- :meth:`to_tensor`.+ The inclusive ``+1`` is `#3934 <https://github.com/kornia/kornia/issues/3934>`_ and the ``'vertices'``+ export trap `#4009 <https://github.com/kornia/kornia/issues/4009>`_. The integer-input split is+ `#4012 <https://github.com/kornia/kornia/issues/4012>`_ and the validator split with+ :func:`~kornia.geometry.bbox.validate_bbox` is `#4013 <https://github.com/kornia/kornia/issues/4013>`_.+ Boxes from :func:`~kornia.geometry.bbox.bbox_generator3d` measure one larger than requested:+ `#4018 <https://github.com/kornia/kornia/issues/4018>`_. The :meth:`to_tensor` default differs from+ :meth:`Boxes.to_tensor`, which defaults to the stored mode:+ `#4251 <https://github.com/kornia/kornia/issues/4251>`_."""@@ -1395,11 +1319,9 @@ class Boxes3D:See the Convention block on :class:`~kornia.geometry.boxes.Boxes3D`.Convention:- ``mode`` selects the export format and defaults to ``'xyzxyz'`` regardless of the label stored by- :meth:`from_tensor` or the constructor; :meth:`Boxes.to_tensor` defaults to its stored mode instead- (`#4251 <https://github.com/kornia/kornia/issues/4251>`_).- Every export starts from the ``amin``/``amax`` bounds of the stored vertices, so it is the- axis-aligned bounding box of a rotated hexahedron.+ ``mode`` defaults to ``'xyzxyz'`` regardless of the stored label+ (`#4251 <https://github.com/kornia/kornia/issues/4251>`_). Every export is the ``amin``/``amax``+ axis-aligned bounding box of the stored vertices.Args:mode: The format in which the boxes are provided, matched case-insensitively.@@ -1426,20 +1348,9 @@ class Boxes3D:* Any other value: :math:`(N, 6)` or :math:`(B, N, 6)`.Note:- The vertex-to-corner reduction below is ``amin``/``amax`` over the 8 vertices, which is- differentiable everywhere except where multiple vertices exactly tie for an axis extremum --- e.g. every face of an axis-aligned box, where 4 vertices share each min/max coordinate. At an- exact tie PyTorch's ``amin``/``amax`` backward splits the gradient evenly among the tied- vertices (``1/k`` for ``k`` ties), a valid subgradient usable for optimization, but one that- :func:`torch.autograd.gradcheck`'s central-difference estimate will not exactly match at that- point -- the same non-uniqueness any reduction has at a kink (compare ``torch.max`` or- :class:`~torch.nn.ReLU` at their own kinks). This was previously (see `#1396- <https://github.com/kornia/kornia/issues/1396>`_) mistaken for an actual gradient bug and- gated behind a ``RuntimeError``; :class:`Boxes` (2D) uses the same reduction and was never- gated, because an axis-aligned rectangle always ties 2-way per extremum, where the ``1/2``- split happens to coincide with the central-difference estimate -- gradcheck cannot see the- same kink there. A degenerate 2D box -- zero extent on an axis, so four vertices tie -- reaches- the same 4-way split and is not guaranteed that coincidence.+ The ``amin``/``amax`` reduction ties on every face of an axis-aligned box (4 vertices share each+ extremum), so the gradient there is a subgradient shared among the tied vertices; it sums to one+ over them but need not match a finite-difference estimate such as :func:`torch.autograd.gradcheck`.Examples:>>> boxes_xyzxyz = torch.as_tensor([[0, 3, 6, 1, 4, 8], [5, 1, 3, 8, 4, 9]])@@ -1485,18 +1396,14 @@ class Boxes3D:See the Convention block on :class:`~kornia.geometry.boxes.Boxes3D`.Convention:- The size is ``(depth, height, width)`` and the mask is :math:`(N, depth, height, width)` or- :math:`(B, N, depth, height, width)` in the box dtype, where :func:`~kornia.geometry.bbox.bbox_to_mask3d`- returns ``float32`` with an extra channel axis. The boxes are exported as exclusive ``'xyzxyz'``- bounds, clamped to the volume, rounded to the nearest integer, and filled over half-open ranges, so a- box entirely outside the volume fills nothing and a fractional box can fill a different volume than- :func:`~kornia.geometry.bbox.bbox_to_mask3d`, which truncates. The loop and the grid comparison taken- under graph capture produce the same mask. A box tensor that requires grad is rejected with- ``RuntimeError``.+ The size is ``(depth, height, width)`` and the mask :math:`(N, depth, height, width)` or+ :math:`(B, N, depth, height, width)` in the box dtype, with no channel axis. The exclusive+ ``'xyzxyz'`` export is clamped to the volume, rounded to the nearest integer and filled over+ half-open ranges. A box tensor that requires grad raises ``RuntimeError``... warning::- The rounding split with :func:`~kornia.geometry.bbox.bbox_to_mask3d` is tracked in- `#4015 <https://github.com/kornia/kornia/issues/4015>`_.+ :func:`~kornia.geometry.bbox.bbox_to_mask3d` truncates instead of rounding, so a fractional box can+ fill a different volume: `#4015 <https://github.com/kornia/kornia/issues/4015>`_.Args:depth: depth of the masked image/images.@@ -1625,9 +1532,8 @@ class Boxes3D:See the Convention block on :class:`~kornia.geometry.boxes.Boxes3D`.Convention:- The in-place operation rebinds this object's internal tensor to the transformed result. A tensor- reference obtained from :attr:`data` before that call therefore remains unchanged and no longer- aliases the container's data. The stored mode label is kept.+ The internal tensor is rebound, not written: a tensor obtained from :attr:`data` before the call+ keeps the old coordinates. The stored mode label is kept.Returns:This :class:`Boxes3D` object after the transformation.diff --git a/kornia/geometry/calibration/distort.py b/kornia/geometry/calibration/distort.pyindex 694ba9304..40e6101ec 100644--- a/kornia/geometry/calibration/distort.py+++ b/kornia/geometry/calibration/distort.py@@ -28,16 +28,12 @@ def tilt_projection(taux: torch.Tensor, tauy: torch.Tensor, return_inverse: boolr"""Estimate the tilt projection matrix or the inverse tilt projection matrix.Convention:- - the rotation is ``R = Ry(tauy) @ Rx(taux)`` and ``Pz`` is built from the third column of ``R``. Both- branches return exactly ``eye(3)`` when ``taux`` and ``tauy`` are zero, which is the case for a- ``dist`` vector whose 13th and 14th entries are zero.- - ``return_inverse=True`` returns the inverse of ``Pz @ R``. That is the branch- :func:`~kornia.geometry.calibration.undistort_points` applies, and it is what reproduces OpenCV's- ``undistortPoints`` on this repository's own reference values.- - ``return_inverse=False`` returns ``Pz @ R``, matching OpenCV's tilt projection.- - Scalar angles return :math:`(3, 3)`. For non-scalar angles, a trailing singleton angle-component- axis is consumed and every leading batch dimension is preserved; without that trailing singleton,- the full input shape is treated as the batch shape.+ - the rotation is ``R = Ry(tauy) @ Rx(taux)`` and ``Pz`` is built from the third column of ``R``;+ ``return_inverse=False`` returns ``Pz @ R`` (OpenCV's tilt projection) and ``return_inverse=True`` its+ inverse, the branch :func:`~kornia.geometry.calibration.undistort_points` applies. Zero angles give+ ``eye(3)``.+ - scalar angles return :math:`(3, 3)`; otherwise a trailing singleton angle axis, if present, is+ consumed and the remaining dimensions are the batch shape.Args:taux: Rotation angle in radians around the :math:`x`-axis with any shape, matching the other angle.@@ -117,24 +113,17 @@ def distort_points(distortion models are considered in this function.Convention:- See :doc:`camera and world conventions </get-started/camera-conventions>` for the camera-intrinsics and- integer pixel-centre conventions used here.-- - ``points`` are **pixel** coordinates in ``(u, v)`` order and so is the result. Pixel centres lie at- integer coordinates: the top-left centre is ``(0, 0)``.+ - ``points`` are **pixel** coordinates in ``(u, v)`` order and so is the result (integer pixel centres;+ see :class:`~kornia.geometry.camera.pinhole.PinholeCamera`).:func:`~kornia.geometry.camera.distort_points_affine` and- :func:`~kornia.geometry.camera.distort_points_kannala_brandt` are the counterparts that take a point- on the normalized :math:`z = 1` plane and a flat parameter vector instead of ``K`` and ``dist``.+ :func:`~kornia.geometry.camera.distort_points_kannala_brandt` take a point on the normalized+ :math:`z = 1` plane and a flat parameter vector instead.- ``dist`` is OpenCV's coefficient vector in the order listed under ``Args``. The lengths 4, 5, 8, 12- and 14 are accepted and every other length raises :class:`ValueError`; an accepted shorter vector is- zero-padded to 14 internally, so a 4-element vector and its 14-element zero padding give the same- answer.- - ``new_K`` and ``K`` play opposite roles: ``new_K`` maps the incoming pixel onto the normalized- plane and ``K`` maps the distorted normalized point back to pixels. ``new_K`` defaults to ``K``.- - :func:`~kornia.geometry.calibration.undistort_points` is the inverse map and takes the same- coefficient layout, with the two intrinsics in the mirrored roles.- - Matching leading dimensions are preserved with or without tilt. Compilation and ONNX export always apply- the tilt branch, including for zero tilt, where the resulting projection is the identity.+ and 14 are accepted, zero-padded to 14 internally; any other length raises :class:`ValueError`.+ - ``new_K`` maps the incoming pixel onto the normalized plane and ``K`` maps the distorted point back+ to pixels; ``new_K`` defaults to ``K``. :func:`~kornia.geometry.calibration.undistort_points` is the+ inverse map, with the two intrinsics in the mirrored roles.+ - matching leading dimensions of ``points``, ``K`` and ``dist`` are preserved.Args:points: Input image points with shape :math:`(*, N, 2)`.diff --git a/kornia/geometry/calibration/pnp.py b/kornia/geometry/calibration/pnp.pyindex 8197e3e22..b05a935c5 100644--- a/kornia/geometry/calibration/pnp.py+++ b/kornia/geometry/calibration/pnp.py@@ -65,8 +65,8 @@ def solve_pnp_dlt() -> torch.Tensor:r"""Attempt to solve the Perspective-n-Point (PnP) problem using Direct Linear Transform (DLT).- Given a batch (torch.where batch size is :math:`B`) of :math:`N` 3D points- (torch.where :math:`N \geq 6`) in the world space, a batch of :math:`N`+ Given a batch (where batch size is :math:`B`) of :math:`N` 3D points+ (where :math:`N \geq 6`) in the world space, a batch of :math:`N`corresponding 2D points in the image space and a batch ofintrinsic matrices, this function tries to estimate a batch ofworld to camera transformation matrices.@@ -85,16 +85,20 @@ def solve_pnp_dlt(Convention:- the returned :math:`(B, 3, 4)` matrix is the **world-to-camera** ``[R | t]``: it maps a world point- into the camera frame, rather than storing a camera-to-world pose. If the camera frame is the world- frame shifted so that ``X_cam = X_world + (1, 0, 0)``, the recovered ``t`` is ``(+1, 0, 0)`` and not- ``(-1, 0, 0)``.+ into the camera frame (``X_cam = X_world + (1, 0, 0)`` gives ``t = (+1, 0, 0)``), not a+ camera-to-world pose.- ``intrinsics`` is the :math:`(B, 3, 3)` ``K``; the :math:`(B, 4, 4)` matrix that a- ``PinholeCamera`` stores is rejected by the shape check.- - ``weights`` scales the two rows each point contributes to the linear system. That system is- homogeneous, so a uniform ``weights`` leaves the answer unchanged up to rounding, and a zero weight- drops that point from the fit.- - too few points raise a ``BaseError`` whose message names no argument, while a degenerate- ``world_points`` raises :class:`AssertionError` from the singular-value check described above.+ ``PinholeCamera`` stores is rejected.+ - ``weights`` scales the two rows each point contributes to the homogeneous linear system, so a uniform+ ``weights`` leaves the answer unchanged up to rounding.+ - fewer than 6 points, or a ``world_points``, ``img_points`` or ``intrinsics`` in a dtype other than+ float32/float64, raise :class:`~kornia.core.exceptions.BaseError` naming the argument; a degenerate+ ``world_points`` raises :class:`AssertionError` from the check above.++ .. warning::+ A zero weight removes a point's rows but not the point: it still enters the normalization and the+ degeneracy check, so coplanar points plus zero-weight points off the plane pass the check and return a+ wrong pose: `#4799 <https://github.com/kornia/kornia/issues/4799>`_.Args:world_points : A torch.Tensor with shape :math:`(B, N, 3)` representing@@ -157,15 +161,20 @@ def solve_pnp_dlt(KORNIA_CHECK_IS_TENSOR(world_points)KORNIA_CHECK_IS_TENSOR(img_points)KORNIA_CHECK_IS_TENSOR(intrinsics)- KORNIA_CHECK(isinstance(svd_eps, float))- KORNIA_CHECK(world_points.dtype in accepted_dtypes)- KORNIA_CHECK(img_points.dtype in accepted_dtypes)- KORNIA_CHECK(intrinsics.dtype in accepted_dtypes)+ KORNIA_CHECK(isinstance(svd_eps, float), f"svd_eps must be a float, got {type(svd_eps).__name__}.")+ KORNIA_CHECK(+ world_points.dtype in accepted_dtypes, f"world_points must be float32 or float64, got {world_points.dtype}."+ )+ KORNIA_CHECK(img_points.dtype in accepted_dtypes, f"img_points must be float32 or float64, got {img_points.dtype}.")+ KORNIA_CHECK(intrinsics.dtype in accepted_dtypes, f"intrinsics must be float32 or float64, got {intrinsics.dtype}.")KORNIA_CHECK_SHAPE(world_points, ["B", "N", "3"])KORNIA_CHECK_SHAPE(img_points, ["B", "N", "2"])KORNIA_CHECK_SHAPE(intrinsics, ["B", "3", "3"])KORNIA_CHECK_SAME_SHAPE(world_points[:, :, 0], img_points[:, :, 0])- KORNIA_CHECK(world_points.shape[1] >= 6)+ KORNIA_CHECK(+ world_points.shape[1] >= 6,+ f"world_points must hold at least 6 points (N >= 6), got N = {world_points.shape[1]}.",+ )if weights is not None:KORNIA_CHECK_IS_TENSOR(weights)diff --git a/kornia/geometry/calibration/undistort.py b/kornia/geometry/calibration/undistort.pyindex 9033ac397..4f76b2390 100644--- a/kornia/geometry/calibration/undistort.py+++ b/kornia/geometry/calibration/undistort.py@@ -42,28 +42,20 @@ def undistort_points(distortion models are considered in this function.Convention:- See :doc:`camera and world conventions </get-started/camera-conventions>` for the camera-intrinsics and- integer pixel-centre conventions used here.-- - ``points`` are **pixel** coordinates in ``(u, v)`` order and so is the result. Pixel centres lie at- integer coordinates: the top-left centre is ``(0, 0)``.- - ``dist`` follows the coefficient layout documented on- :func:`~kornia.geometry.calibration.distort_points`, which is the forward map this function inverts;- the accepted lengths and the internal zero-padding are the same.- - ``K`` and ``new_K`` play the mirror image of their roles in the forward map: ``K`` maps the incoming- pixel onto the normalized plane and ``new_K`` maps the undistorted normalized point back to pixels.- - the inverse is a fixed-point iteration of ``num_iters`` steps, not a closed form, so the round trip- through :func:`~kornia.geometry.calibration.distort_points` closes only to the accuracy that- iteration has reached. Within its convergence region, increasing ``num_iters`` can improve the- result until it reaches the working dtype's rounding floor; ``float16`` can reach that floor at the- default count, while ``float32`` and ``float64`` can continue to improve.- - Matching leading dimensions are preserved with or without tilt. Compilation and ONNX export always apply- the tilt branch, including for zero tilt, and the legacy unbatched form remains supported there as well.+ - ``points`` are **pixel** coordinates in ``(u, v)`` order and so is the result (integer pixel centres;+ see :class:`~kornia.geometry.camera.pinhole.PinholeCamera`).+ - ``dist`` follows the layout of :func:`~kornia.geometry.calibration.distort_points`, the forward map+ this function inverts; ``K`` maps the incoming pixel onto the normalized plane and ``new_K`` maps the+ undistorted point back to pixels.+ - the inverse is a fixed-point iteration of ``num_iters`` steps, so the round trip through+ :func:`~kornia.geometry.calibration.distort_points` closes only to the accuracy the iteration reaches;+ within its convergence region more steps improve it down to the dtype's rounding.+ - matching leading dimensions of ``points``, ``K`` and ``dist`` are preserved... warning::- The iteration has no convergence test and no valid-radius guard. Outside the iteration- convergence region it can enter a two-point cycle, so the answer depends on whether ``num_iters``- is odd or even and no count converges. Tracked as `#4285 <https://github.com/kornia/kornia/issues/4285>`_.+ The iteration has no convergence test and no valid-radius guard: outside the convergence region it can+ enter a two-point cycle, so the answer depends on the parity of ``num_iters``.+ `#4285 <https://github.com/kornia/kornia/issues/4285>`_.Args:points: Input image points with shape :math:`(*, N, 2)`.@@ -178,23 +170,13 @@ def undistort_image(image: torch.Tensor, K: torch.Tensor, dist: torch.Tensor) ->distortion models are considered in this function.Convention:- See :doc:`camera and world conventions </get-started/camera-conventions>` for pixel centres and camera- intrinsics, and :doc:`Conventions & Pitfalls </get-started/conventions>` for sampling and- ``align_corners`` guidance.-- - The leading dimensions of ``image`` (everything in front of ``C, H, W``), of ``K`` (in front of its- :math:`3 \times 3` block) and of ``dist`` (in front of its ``n`` coefficients) must match exactly.- They may be empty, a single batch axis, or several axes deep, including with non-zero tilt and under- compilation or ONNX export. The one exception is the legacy unbatched call -- a :math:`(1, C, H, W)`- image with a :math:`(3, 3)` ``K`` and an :math:`(n,)` ``dist``.- - the sampling map is built by applying :func:`~kornia.geometry.calibration.distort_points` to the- grid of integer pixel centres that :func:`~kornia.geometry.grid.create_meshgrid` enumerates: the- top-left centre is ``(0, 0)``.- - the map is resampled with ``align_corners=True``; the flag is baked in and the function exposes no- way to change it.- - with every coefficient zero the map is the pixel grid up to floating-point rounding, but the image- still goes through the bilinear sampler, so the output is equal to the input at the working dtype's- tolerance and is not bit-identical to it.+ - the leading dimensions of ``image`` (in front of ``C, H, W``), ``K`` (in front of :math:`3 \times 3`)+ and ``dist`` (in front of its ``n`` coefficients) must match exactly; the one exception is the+ legacy unbatched call, a :math:`(1, C, H, W)` image with a :math:`(3, 3)` ``K`` and an :math:`(n,)`+ ``dist``.+ - the sampling map applies :func:`~kornia.geometry.calibration.distort_points` to the integer pixel+ centres (see :class:`~kornia.geometry.camera.pinhole.PinholeCamera`) and is resampled bilinearly with+ a fixed ``align_corners=True``, so all-zero coefficients return the input only to rounding.Args:image: Input image with shape :math:`(*, C, H, W)`.diff --git a/kornia/geometry/camera/distortion_affine.py b/kornia/geometry/camera/distortion_affine.pyindex 978d12c82..1fb23c9ad 100644--- a/kornia/geometry/camera/distortion_affine.py+++ b/kornia/geometry/camera/distortion_affine.py@@ -34,12 +34,11 @@ def distort_points_affine(projected_points_in_camera_z1_plane: torch.Tensor, parConvention:- ``projected_points_in_camera_z1_plane`` is a point on the **normalized** :math:`z = 1` plane, not a- pixel, and ``params`` is the flat vector ``[fx, fy, cx, cy]``; the result is in pixels.- Pixel centres lie at integer coordinates: the top-left centre is ``(0, 0)``.+ pixel, and ``params`` is the flat vector ``[fx, fy, cx, cy]``; the result is in pixels (integer pixel+ centres; see :class:`~kornia.geometry.camera.pinhole.PinholeCamera`).- :func:`~kornia.geometry.calibration.distort_points` is the same camera parametrized by a:math:`(*, 3, 3)` ``K`` and an OpenCV coefficient vector; it takes a **pixel** input instead.- - :func:`undistort_points_affine` inverts this map in closed form -- one subtraction and one division- per axis, with no iteration; the Kannala-Brandt pair needs a Gauss-Newton solve for the same step.+ - :func:`undistort_points_affine` is the closed-form inverse.Args:projected_points_in_camera_z1_plane: torch.Tensor representing the points to distort with shape (..., 2).@@ -83,9 +82,8 @@ def undistort_points_affine(distorted_points_in_camera: torch.Tensor, params: to- ``distorted_points_in_camera`` is a **pixel** coordinate and the result is a point on the normalized:math:`z = 1` plane; ``params`` is the same ``[fx, fy, cx, cy]`` vector that:func:`distort_points_affine` takes, and this function is its closed-form inverse.- - a zero ``fx`` or ``fy`` is not rejected: that axis divides by zero and comes back as an infinity- carrying the numerator's sign, or as ``nan`` for a point that sits exactly on the corresponding- principal-point coordinate.+ - ``params`` values are not validated (a design choice shared with the other intrinsics consumers): a+ zero ``fx`` or ``fy`` gives ``inf`` or ``nan`` on that axis.Args:distorted_points_in_camera: torch.Tensor representing the points to undistort with shape (..., 2).@@ -125,8 +123,7 @@ def dx_distort_points_affine(projected_points_in_camera_z1_plane: torch.Tensor,Convention:- the result is the :math:`(..., 2, 2)` Jacobian of :func:`distort_points_affine` with respect to the- **point**: rows are the output components ``(u, v)``, columns the input components ``(x, y)``. It- agrees with :func:`torch.autograd.functional.jacobian` of the same function.+ **point**: rows are the output components ``(u, v)``, columns the input components ``(x, y)``.- the map is affine, so that Jacobian is ``diag(fx, fy)`` and does not depend on the point.Args:diff --git a/kornia/geometry/camera/distortion_kannala_brandt.py b/kornia/geometry/camera/distortion_kannala_brandt.pyindex 459837fe7..7958e1f81 100644--- a/kornia/geometry/camera/distortion_kannala_brandt.py+++ b/kornia/geometry/camera/distortion_kannala_brandt.py@@ -66,8 +66,8 @@ def distort_points_kannala_brandt(Convention:- ``projected_points_in_camera_z1_plane`` is a point on the **normalized** :math:`z = 1` plane, not a- pixel, and the result is in pixels.- Pixel centres lie at integer coordinates: the top-left centre is ``(0, 0)``.+ pixel, and the result is in pixels (integer pixel centres; see+ :class:`~kornia.geometry.camera.pinhole.PinholeCamera`).- ``params`` is the flat vector ``[fx, fy, cx, cy, k0, k1, k2, k3]``: the first four are the affinepart that :func:`~kornia.geometry.camera.distort_points_affine` takes on its own, and ``k0`` to``k3`` multiply :math:`\theta^2`, :math:`\theta^4`, :math:`\theta^6` and :math:`\theta^8` in the@@ -114,13 +114,10 @@ def undistort_points_kannala_brandt(distorted_points_in_camera: torch.Tensor, pa- ``distorted_points_in_camera`` is a **pixel** coordinate and the result is a point on the normalized:math:`z = 1` plane; ``params`` is the same 8-element vector documented on:func:`distort_points_kannala_brandt`.- - the inverse is a fixed number of Gauss-Newton steps rather than a closed form: the step count is not- a parameter and there is no convergence test, so the round trip through- :func:`distort_points_kannala_brandt` closes only to the accuracy that iteration has reached. The- step count cannot be raised by a caller. :func:`~kornia.geometry.camera.undistort_points_affine` is the- closed-form contrast.- - an exact zero distorted radius is handled structurally and maps to the origin. Nonzero radii use the- radius itself for the final radial rescale, without an additive epsilon.+ - the inverse is a fixed number of Gauss-Newton steps with no convergence test and no caller-visible+ step count, so the round trip through :func:`distort_points_kannala_brandt` closes only to the+ accuracy that iteration reaches.+ - a zero distorted radius maps to the origin.Args:distorted_points_in_camera: torch.Tensor representing the points to undistort with shape (..., 2).@@ -202,9 +199,8 @@ def dx_distort_points_kannala_brandt(- the result has shape :math:`(..., 2, 2)` and is laid out like the Jacobian that:func:`~kornia.geometry.camera.dx_distort_points_affine` returns: rows are the output components``(u, v)``, columns the input components ``(x, y)``.- - the Jacobian matches :func:`distort_points_kannala_brandt` with respect to the input point.- For squared radii less than or equal to ``1e-8``, the forward function uses its affine branch,- so the Jacobian is ``diag(fx, fy)``.+ - for squared radii ``<= 1e-8`` the forward function uses its affine branch, so the Jacobian there is+ ``diag(fx, fy)``.Args:projected_points_in_camera_z1_plane: torch.Tensor representing the points to distort with shape (..., 2).diff --git a/kornia/geometry/camera/perspective.py b/kornia/geometry/camera/perspective.pyindex 98536efd7..17a1b90cc 100644--- a/kornia/geometry/camera/perspective.py+++ b/kornia/geometry/camera/perspective.py@@ -34,16 +34,13 @@ def project_points(point_3d: torch.Tensor, camera_matrix: torch.Tensor) -> torchConvention:- ``point_3d`` is a **camera-frame** point and ``camera_matrix`` the :math:`(*, 3, 3)` ``K``; thefunction 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.-- See :doc:`camera and world conventions </get-started/camera-conventions>` for camera-frame coordinates,- intrinsics and the pixel-centre convention.+ - the input must be at least rank 2: an unbatched :math:`(3,)` point raises :class:`ValueError`... warning::- The ``z = 0`` answer is tracked in `#4267 <https://github.com/kornia/kornia/issues/4267>`_.+ At ``abs(z) <= 1e-8`` the divide is skipped and ``K`` is applied to the undivided point, giving the+ finite placeholder ``fx x + cx``; the other projection entry points do not follow this rule yet:+ `#4267 <https://github.com/kornia/kornia/issues/4267>`_. Neither that placeholder nor a point behind the+ camera is flagged as invalid: `#4555 <https://github.com/kornia/kornia/issues/4555>`_.Args:point_3d: tensor containing the 3d points to be projected@@ -86,9 +83,6 @@ def unproject_points(- ``depth`` is the camera-frame ``z`` of the result. With ``normalize=True`` it is read as theEuclidean ray length instead, so the result has that norm and a smaller ``z``.- See :doc:`camera and world conventions </get-started/camera-conventions>` for camera-frame depth,- intrinsics and the pixel-centre convention.-Args:point_2d: tensor containing the 2d points to be projected tothe camera frame. The shape of the tensor can be :math:`(*, 2)`.diff --git a/kornia/geometry/camera/pinhole.py b/kornia/geometry/camera/pinhole.pyindex 79742776b..6609ed276 100644--- a/kornia/geometry/camera/pinhole.py+++ b/kornia/geometry/camera/pinhole.py@@ -32,33 +32,27 @@ class PinholeCamera:- ``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/camera-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 owns copies of the ``intrinsics``, ``extrinsics``, ``height`` and ``width`` tensors it is- constructed from. :meth:`scale_` and the ``tx`` / ``ty`` / ``tz`` setters therefore update only the- camera's storage, while :meth:`scale` and :meth:`clone` return independently owned cameras.+ ``K (R X + t)`` and returns pixels, while :meth:`unproject` takes pixels and a camera-frame depth and+ returns **world** points. The functional API takes a ``3x3`` ``K`` and no extrinsics, so it works in+ the **camera** frame.+ - pixel coordinates are ``(u, v)`` = (column, row) with **integer pixel centres**: pixel ``(0, 0)`` is+ centred at ``(0, 0)``, as :func:`~kornia.geometry.grid.create_meshgrid` enumerates, so a centred image+ has ``cx = (W - 1) / 2``, ``cy = (H - 1) / 2``. COLMAP's half-pixel convention reports the same+ principal point half a pixel larger. ``kornia.geometry.camera``, ``kornia.geometry.depth`` and+ ``kornia.geometry.calibration`` all use this convention; see :doc:`/get-started/camera-conventions`.+ - ``depth`` is the camera-frame ``z``, except where a ``normalize`` / ``normalize_points`` flag reads it+ as the Euclidean ray length.+ - the class owns copies of the tensors it is constructed from: :meth:`scale_` and the ``tx`` / ``ty`` /+ ``tz`` setters update only the camera, and :meth:`scale` and :meth:`clone` return independent cameras... 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 direct projection limitation for- :math:`(B, N, 4, 4)` camera storage is `#4266 <https://github.com/kornia/kornia/issues/4266>`_. The- behaviour described here is documented as it is; the issues above track the repairs.+ :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:+ `#4263 <https://github.com/kornia/kornia/issues/4263>`_. With the :math:`(B, N, 4, 4)` storage the+ validator admits, :meth:`project` raises on :math:`(B, N, 3)` points:+ `#4266 <https://github.com/kornia/kornia/issues/4266>`_. The ``intrinsics`` form is not validated: a+ zero-padded ``K`` with ``intrinsics[3, 3] = 0`` projects but :meth:`unproject` raises on the singular+ matrix: `#4771 <https://github.com/kornia/kornia/issues/4771>`_.Args:intrinsics: torch.Tensor with shape :math:`(B, 4, 4)`@@ -310,18 +304,11 @@ class PinholeCamera: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 owns its parameter storage, so writing ``tx`` / ``ty`` / ``tz`` on the returned- camera leaves the source where it was.- - with a floating-point ``scale_factor``, an integer ``height`` / ``width`` is promoted to floating- point, as :meth:`scale_` does. An integer factor preserves the integer image-size dtype.-- See :doc:`camera and world conventions </get-started/camera-conventions>` for image resizing and- the matching intrinsics scaling convention.+ ``scale_factor``: ``fx' = s * fx`` and ``cx' = s * cx``.+ - ``height`` / ``width`` take the promoted dtype of ``scale_factor * height``... 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+ The ``cx' = s * cx`` rule disagrees with kornia's integer pixel centres:`#4263 <https://github.com/kornia/kornia/issues/4263>`_.Args:@@ -348,16 +335,11 @@ class PinholeCamera:r"""Scale the pinhole model in-place.Convention:- - applies the same rescaling as :meth:`scale` in place and returns ``self``. The camera owns its- parameter storage, so the tensors passed to the constructor are not modified.- - with a floating-point ``scale_factor``, an integer ``height`` / ``width`` is promoted to floating- point, just as :meth:`scale` does. An integer factor preserves the integer image-size dtype.-- See :doc:`camera and world conventions </get-started/camera-conventions>` for image resizing and- the matching intrinsics scaling convention.+ - applies the rescaling of :meth:`scale` in place and returns ``self``; the tensors passed to the+ constructor are not modified... warning::- The principal-point rule shared with :meth:`scale` is tracked in+ The principal-point rule shared with :meth:`scale` is`#4263 <https://github.com/kornia/kornia/issues/4263>`_.Args:@@ -391,7 +373,8 @@ class PinholeCamera:perspective divide is then skipped, so the result is the undivided ``K (R X + t)``... warning::- The ``z = 0`` answer is tracked in `#4267 <https://github.com/kornia/kornia/issues/4267>`_.+ This ``z = 0`` answer differs from :func:`~kornia.geometry.camera.perspective.project_points`, which+ applies ``K`` after the skipped divide: `#4267 <https://github.com/kornia/kornia/issues/4267>`_.Args:point_3d: torch.Tensor containing the 3d points to be projected@@ -592,10 +575,8 @@ def pinhole_matrix(pinholes: torch.Tensor, eps: float = 1e-6) -> torch.Tensor: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+ The output is built as ``eye(4) + eps`` before the parameters are written, so every structural zero+ carries ``eps``; ``eps=0.0`` returns the exact matrix.`#4268 <https://github.com/kornia/kornia/issues/4268>`_.Args:@@ -651,10 +632,8 @@ def inverse_pinhole_matrix(pinhole: torch.Tensor, eps: float = 1e-6) -> torch.Te.. 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>`_.+ one ``pinhole_matrix`` returns, and a zero focal length gives a large value instead of raising.+ `#4268 <https://github.com/kornia/kornia/issues/4268>`_.Args:pinhole: torch.Tensor with pinhole models.@@ -765,7 +744,7 @@ def homography_i_H_ref(pinhole_i: torch.Tensor, pinhole_ref: torch.Tensor) -> topinhole = (f_x, f_y, c_x, c_y, height, width,r_x, r_y, r_z, t_x, t_y, t_z)- torch.where:+ where::math:`(r_x, r_y, r_z)` is the rotation vector in angle-axisconvention.@@ -818,13 +797,12 @@ def pixel2cam(depth: torch.Tensor, intrinsics_inv: torch.Tensor, pixel_coords: tSee 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`` must have shape :math:`(B, 4, 4)`; other ranks or matrix sizes raise- :class:`ValueError` before transforming the pixel coordinates.- - ``depth`` must have shape ``Bx1xHxW``; multi-channel depth raises :class:`ValueError`.- ``pixel_coords`` must have shape ``BxHxWx3``.+ - ``intrinsics_inv`` is a :math:`(B, 4, 4)` inverse calibration matrix (the+ :class:`~kornia.geometry.camera.pinhole.PinholeCamera` layout, not a ``3x3`` ``K``), and ``depth`` is+ the camera-frame ``z`` at each pixel of the ``(u, v, 1)`` grid.+ - a ``depth`` that is not ``Bx1xHxW``, an ``intrinsics_inv`` that is not :math:`(B, 4, 4)` or a+ ``pixel_coords`` that is not ``BxHxWx3`` raises :class:`ValueError`; that ``pixel_coords`` matches+ the ``H`` and ``W`` of ``depth`` is not checked.Args:depth: the source depth maps. Shape must be Bx1xHxW.@@ -855,16 +833,15 @@ def cam2pixel(cam_coords_src: torch.Tensor, dst_proj_src: torch.Tensor, eps: floSee 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 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.+ - ``dst_proj_src`` is a :math:`(B, 4, 4)` projection matrix (the+ :class:`~kornia.geometry.camera.pinhole.PinholeCamera` layout, not a ``3x3`` ``K``), and the result is+ ``(u, v)`` pixel coordinates in the destination frame... warning::- The ``z = 0`` answer is tracked in `#4267 <https://github.com/kornia/kornia/issues/4267>`_.+ The perspective division is ``x / (z + eps)`` rather than a guarded divide, so ``z = 0`` gives+ ``x / eps``, huge for a nonzero ``x`` (``inf`` where ``eps`` underflows), and ``eps`` biases every small+ depth:+ `#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.diff --git a/kornia/geometry/camera/projection_orthographic.py b/kornia/geometry/camera/projection_orthographic.pyindex 829c0190e..e1f22019f 100644--- a/kornia/geometry/camera/projection_orthographic.py+++ b/kornia/geometry/camera/projection_orthographic.py@@ -55,8 +55,8 @@ def unproject_points_orthographic(points_in_camera: torch.Tensor, extension: tor\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.+ - ``extension`` becomes the ``z`` component of the result; both a ``(N,)`` and a ``(N, 1)`` extension+ are accepted.Args:points_in_camera: torch.Tensor representing the points to unproject with shape (..., 2).diff --git a/kornia/geometry/camera/projection_z1.py b/kornia/geometry/camera/projection_z1.pyindex b3f7d41ec..7e22ca977 100644--- a/kornia/geometry/camera/projection_z1.py+++ b/kornia/geometry/camera/projection_z1.py@@ -43,17 +43,14 @@ def project_points_z1(points_in_camera: torch.Tensor) -> torch.Tensor: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``.+ a normalized coordinate rather than a pixel; applying ``K`` with+ :func:`~kornia.geometry.conversions.denormalize_points_with_intrinsics` gives the pixel.+ - the ``z > 0`` precondition above is not validated... warning::- Returning component-dependent infinities or ``nan`` is one of several answers this namespace gives at- ``z = 0``. Tracked in+ The divide is plain at every ``z``: at ``z = 0`` a component is infinite, or ``nan`` for a zero+ numerator. :func:`~kornia.geometry.camera.perspective.project_points` instead skips its divide at+ ``abs(z) <= 1e-8`` and returns finite pixels there, so the two disagree below that threshold:`#4267 <https://github.com/kornia/kornia/issues/4267>`_.Args:@@ -85,9 +82,7 @@ def unproject_points_z1(- ``extension`` is the camera-frame ``z`` of the unprojected point: the canonical point is multipliedby 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.+ ``depth``. Both ``(...,)`` and ``(..., 1)`` extensions are accepted.Args:points_in_cam_canonical: torch.Tensor representing the points to unproject with shape (..., 2).@@ -138,8 +133,7 @@ def dx_project_points_z1(points_in_camera: torch.Tensor) -> torch.Tensor: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`.+ holding the derivatives with respect to ``x``, ``y`` and ``z``.- the same ``z > 0`` precondition applies, and it is not validated either.Args:diff --git a/kornia/geometry/camera/stereo.py b/kornia/geometry/camera/stereo.pyindex d240537aa..0ea68afe3 100644--- a/kornia/geometry/camera/stereo.py+++ b/kornia/geometry/camera/stereo.py@@ -56,42 +56,26 @@ class StereoCamera:shape :math:`(B, 3, 4)`: ``[[fx, 0, cx, 0], [0, fy, cy, 0], [0, 0, 1, 0]]`` for the left camera, andthe same matrix with ``-tx * fx`` in the last column for the right one. The constructor requires thetwo to be equal outside that last column.- - the baseline is read back from that column as ``tx = -P_right[0, 3] / fx``, and :attr:`Q` is built- from ``fx``, ``fy``, ``cx_left``, ``cy`` and that ``tx``. Note which focal length sits in which row:- ``Q[0, 0]`` carries ``fy`` and ``Q[1, 1]`` carries ``fx``, while the homogeneous divide is by- ``-fy * disparity``, so the two cancel and the first output coordinate ends up scaled by ``1 / fx``- and the second by ``1 / fy``.- - a point cloud is a homogeneous transform by :attr:`Q` followed by the divide by ``W``. When- ``abs(W) > 1e-8``, an overall sign on :attr:`Q` cancels, so :attr:`Q` and its negation return the- same points. For ``abs(W) <= 1e-8``, the homogeneous conversion returns the numerator unchanged,- and the two matrices return opposing values. :attr:`Q` is exactly the matrix written out on the- :doc:`/geometry.camera.stereo` page, above this docstring, evaluated at the page's own ``tx``: the- page's :math:`P_1` carries ``fx * tx`` in its last column, so that ``tx`` is ``P_right[0, 3] / fx``,- which the constructor requires to be strictly **negative** for every rig in the batch; a zero product- (a degenerate baseline) and a positive one (the cameras swapped) both raise. The :attr:`tx` attribute- exposes the negation of that symbol, ``-P_right[0, 3] / fx``; substituting the attribute's value for- the page's ``tx`` gives neither :attr:`Q` nor its negation, because the page's last row carries no- ``tx`` and does not flip.- - a disparity map is channels-**last**, :math:`(B, H, W, 1)`, for- :meth:`~kornia.geometry.camera.stereo.StereoCamera.reproject_disparity_to_3D` and for the module-level- :func:`~kornia.geometry.camera.stereo.reproject_disparity_to_3D` alike -- the :math:`(B, 1, H, W)`- layout the rest of kornia uses for images is rejected -- and the returned point cloud is- :math:`(B, H, W, 3)`.- - the pixels are the integer pixel centres that :func:`~kornia.geometry.grid.create_meshgrid`- enumerates, described in the Convention block on+ - the baseline is read back as the attribute :attr:`tx` ``= -P_right[0, 3] / fx``, which must be+ strictly **positive** for every rig in the batch: a zero baseline and swapped cameras both raise. A+ non-finite ``P_right[0, 3]`` is not screened, and these checks and the equal-intrinsics check are+ skipped under ``torch.export``.+ The :doc:`/geometry.camera.stereo` page's symbol ``tx`` is the negation of this attribute; :attr:`Q`+ is the page's matrix evaluated at the page's ``tx``.+ - ``Q[0, 0]`` carries ``fy`` and ``Q[1, 1]`` carries ``fx``; with the divide by ``W = -fy * disparity``+ the result is ``X = (u - cx) Z / fx``, ``Y = (v - cy) Z / fy``, ``Z = fx * tx / disparity``.+ - ``u`` is the **column** index and ``v`` the **row** index, as in ``cv2.reprojectImageTo3D``.+ - a disparity map is channels-**last**, :math:`(B, H, W, 1)` (a :math:`(B, 1, H, W)` map is rejected),+ and the point cloud is :math:`(B, H, W, 3)`.+ - pixel centres are integers; see the Convention block on:class:`~kornia.geometry.camera.pinhole.PinholeCamera`.- - ``u`` is the **column** index and ``v`` the **row** index, as in ``cv2.reprojectImageTo3D``:- :math:`X = (u - c_x) Z / f_x` and :math:`Y = (v - c_y) Z / f_y`.-- See :doc:`camera and world conventions </get-started/camera-conventions>` for the shared intrinsics,- depth and integer pixel-centre conventions... warning::- A differing ``cx`` is **rejected**, even though :attr:`cx_left` and :attr:`cx_right` are exposed- separately and ``Q[3, 3]`` carries ``fy * (cx_left - cx_right)`` for exactly that case, so that factor- is zero on any rig the constructor accepts. Whether to admit a differing ``cx`` or to drop that claim is- tracked as `#4270 <https://github.com/kornia/kornia/issues/4270>`_ and pinned by- ``test_wart_stereo_rejects_differing_principal_points_4270`` in ``tests/geometry/camera/test_stereo.py``.+ A differing ``cx`` is **rejected**, although ``Q[3, 3] = fy * (cx_left - cx_right)`` exists for that+ case, so it is zero on every rig the constructor accepts outside ``torch.export``:+ `#4270 <https://github.com/kornia/kornia/issues/4270>`_. A zero disparity (a point at infinity) makes+ ``W = 0``; the divide is then skipped and a finite placeholder, behind the camera on a real rig, is+ returned and not flagged as invalid: `#4555 <https://github.com/kornia/kornia/issues/4555>`_... warning::The module-level :func:`~kornia.geometry.camera.stereo.reproject_disparity_to_3D` is rendered ondiff --git a/kornia/geometry/depth.py b/kornia/geometry/depth.pyindex d77f15083..2c22e303d 100644--- a/kornia/geometry/depth.py+++ b/kornia/geometry/depth.py@@ -65,24 +65,13 @@ def unproject_meshgrid(the meshgrid computation when warping multiple frames with the same camera intrinsics.Convention:- - the result is the ray through each pixel at depth 1, in the :math:`(B, H, W, 3)` layout, so- multiplying it by a :math:`(B, H, W)` depth map reproduces- :func:`~kornia.geometry.depth.depth_to_3d_v2` exactly -- which is what makes it usable as that- function's ``xyz_grid`` cache.- - the pixels are the integer pixel centres that :func:`~kornia.geometry.grid.create_meshgrid`- enumerates, described in the Convention block on- :class:`~kornia.geometry.camera.pinhole.PinholeCamera`: pixel ``(0, 0)`` is centred at ``(0, 0)``.- ``camera_matrix`` is the :math:`(3, 3)` ``[[fx, 0, cx], [0, fy, cy], [0, 0, 1]]`` of that grid and- there are no extrinsics, so the rays are in the **camera** frame.- - ``camera_matrix`` must have shape :math:`(B, 3, 3)`, which returns- :math:`(B, H, W, 3)`. Unbatched matrices and extra leading dimensions raise ``ShapeError``- at the input guard, with a message naming the caller's shape.- - ``normalize_points=True`` returns the unit ray instead of the ray whose ``z`` is 1, which is the form- :func:`~kornia.geometry.depth.depth_to_3d_v2` needs when its depth is a Euclidean ray length rather- than a camera-frame ``z``.-- See :doc:`camera and world conventions </get-started/camera-conventions>` for pixel centres,- camera-frame depth and the intrinsics convention used by these rays.+ - the result is the **camera-frame** ray through each pixel at depth 1, :math:`(B, H, W, 3)`, so+ multiplying it by a :math:`(B, H, W)` depth map reproduces :func:`~kornia.geometry.depth.depth_to_3d_v2`+ (its ``xyz_grid`` cache). Pixel centres are integers; see+ :class:`~kornia.geometry.camera.pinhole.PinholeCamera`.+ - ``camera_matrix`` must be :math:`(B, 3, 3)`; an unbatched matrix or extra leading dimensions raise+ ``ShapeError``.+ - ``normalize_points=True`` returns the unit ray instead of the ray whose ``z`` is 1.Args:height: height of image.@@ -136,40 +125,30 @@ def depth_to_3d_v2(that does not require the creation of a meshgrid.Convention:- - ``depth`` is the camera-frame ``z`` of each pixel and the result is the camera-frame point- ``((u - cx) z / fx, (v - cy) z / fy, z)``, laid out channels-**last** as :math:`(*, H, W, 3)`.- :func:`~kornia.geometry.depth.depth_to_3d` computes the same points in the :math:`(B, 3, H, W)`- layout, and the two are equal after ``permute(0, 2, 3, 1)``.- - ``u`` and ``v`` are the column and the row of the integer-centre pixel grid that- :func:`~kornia.geometry.depth.unproject_meshgrid` builds, described in the Convention block on- :class:`~kornia.geometry.camera.pinhole.PinholeCamera`. There are no extrinsics, so the points are in- the **camera** frame.- - ``camera_matrix`` needs a leading batch dimension: a bare :math:`(3, 3)` passes this function's own- guard and, when ``xyz_grid`` is not given, is then rejected inside- :func:`~kornia.geometry.depth.unproject_meshgrid`. When ``xyz_grid`` is given,- ``camera_matrix`` is never read, so any matrix that passes the ``(*, 3, 3)`` guard -- a bare- :math:`(3, 3)` included -- is silently accepted.- - ``normalize_points=True`` reads ``depth`` as the Euclidean ray length from the camera centre instead- of as ``z``, so the returned point has that norm rather than that ``z``.- - passing ``xyz_grid`` skips the grid construction and uses the given rays instead; the two forms give- the same result when ``xyz_grid`` is what- :func:`~kornia.geometry.depth.unproject_meshgrid` returns for the same camera.-- See :doc:`camera and world conventions </get-started/camera-conventions>` for the pixel-centre,- camera-frame depth and intrinsics conventions used here.+ - ``depth`` is the camera-frame ``z`` of each pixel and the result the camera-frame point+ ``((u - cx) z / fx, (v - cy) z / fy, z)``, channels-**last** :math:`(*, H, W, 3)`, with ``u`` the+ column and ``v`` the row (integer pixel centres; see+ :class:`~kornia.geometry.camera.pinhole.PinholeCamera`). It equals+ :func:`~kornia.geometry.depth.depth_to_3d` after ``permute(0, 2, 3, 1)``.+ - without ``xyz_grid``, ``camera_matrix`` must be exactly :math:`(B, 3, 3)` (another shape raises+ ``ShapeError``); with ``xyz_grid`` it is never read.+ - ``normalize_points=True`` reads ``depth`` as the Euclidean ray length instead of ``z``.+ - ``xyz_grid`` replaces the grid construction; pass what :func:`~kornia.geometry.depth.unproject_meshgrid`+ returns for the same camera.Args:depth: image tensor containing a depth value per pixel with shape :math:`(*, H, W)`.- camera_matrix: tensor containing the camera intrinsics with shape :math:`(*, 3, 3)`.+ camera_matrix: tensor containing the camera intrinsics with shape :math:`(B, 3, 3)`.normalize_points: whether to normalise the pointcloud. This must be set to `True` when the depth isrepresented as the Euclidean ray length from the camera position.xyz_grid: explicit xyz point values.Return:tensor with a 3d point per pixel of the same resolution as the input, :math:`(*, H, W, 3)`, whose- leading dimensions are the broadcast of ``depth``'s and ``camera_matrix``'s: the Example broadcasts a+ leading dimensions are the broadcast of ``depth``'s and the grid's: the Example broadcasts a:math:`(4, 4)` depth against a :math:`(2, 3, 3)` camera to :math:`(2, 4, 4, 3)`, and a- :math:`(B, T, H, W)` depth with a :math:`(B, 1, 3, 3)` camera returns :math:`(B, T, H, W, 3)`.+ :math:`(B, T, H, W)` depth with an ``xyz_grid`` of shape :math:`(B, 1, H, W, 3)` returns+ :math:`(B, T, H, W, 3)`.Example:>>> depth = torch.rand(4, 4)@@ -200,27 +179,16 @@ def depth_to_3d(depth: torch.Tensor, camera_matrix: torch.Tensor, normalize_poin.. note:::py:func:`kornia.geometry.depth.depth_to_3d_v2` computes the same points without building a meshgrid,- in the :math:`(B, H, W, 3)` layout, and is the newer of the two. Which of them survives,- and on what deprecation path, is a coordinated decision that has not been taken: the two are kept side- by side as they are and this function emits no ``DeprecationWarning``.+ in the :math:`(B, H, W, 3)` layout.Convention:- - ``depth`` is the camera-frame ``z`` of each pixel and the result is the camera-frame point- ``((u - cx) z / fx, (v - cy) z / fy, z)``, laid out channels-**first** as :math:`(B, 3, H, W)`.- :func:`~kornia.geometry.depth.depth_to_3d_v2` computes the same points in the :math:`(B, H, W, 3)`- layout, and the two are equal after ``permute(0, 2, 3, 1)``.- - ``u`` and ``v`` are the column and the row of the integer pixel centres that- :func:`~kornia.geometry.grid.create_meshgrid` enumerates, described in the Convention block on- :class:`~kornia.geometry.camera.pinhole.PinholeCamera`: pixel ``(0, 0)`` is centred at ``(0, 0)``.- ``camera_matrix`` is the :math:`(3, 3)` ``[[fx, 0, cx], [0, fy, cy], [0, 0, 1]]`` of that grid and- there are no extrinsics, so the points are in the **camera** frame.- - ``normalize_points=True`` reads ``depth`` as the Euclidean ray length from the camera centre instead- of as ``z``, so the returned point has that norm rather than that ``z``.- - an integer ``depth`` map is promoted through arithmetic with ``camera_matrix``: with floating-point- intrinsics the point cloud follows their dtype (for example, ``float32`` or ``float64``).-- See :doc:`camera and world conventions </get-started/camera-conventions>` for the pixel-centre,- camera-frame depth and intrinsics conventions used here.+ - ``depth`` is the camera-frame ``z`` of each pixel and the result the camera-frame point+ ``((u - cx) z / fx, (v - cy) z / fy, z)``, channels-**first** :math:`(B, 3, H, W)`, with ``u`` the+ column and ``v`` the row (integer pixel centres; see+ :class:`~kornia.geometry.camera.pinhole.PinholeCamera`). It equals+ :func:`~kornia.geometry.depth.depth_to_3d_v2` after ``permute(0, 2, 3, 1)``.+ - ``normalize_points=True`` reads ``depth`` as the Euclidean ray length instead of ``z``.+ - an integer ``depth`` is not rejected; the result takes the floating dtype of ``camera_matrix``.Args:depth: image tensor containing a depth value per pixel with shape :math:`(B, 1, H, W)`.@@ -266,16 +234,11 @@ def depth_to_normals(depth: torch.Tensor, camera_matrix: torch.Tensor, normalizeConvention:- both spatial dimensions must be at least 2: a surface normal requires two tangent directions.- - the normal is the cross product of the two spatial gradients of the unprojected point cloud, taken in- the order ``d/dx`` cross ``d/dy`` and then normalized to unit length, so a fronto-parallel plane gets- the normal ``(0, 0, 1)``: ``+z`` points **away** from the camera, along the viewing direction, and- not back towards it.- - the same order fixes the two in-plane signs: a depth that grows along the column axis tilts the- normal towards ``-x``, and a depth that grows along the row axis tilts it towards ``-y``.- - ``depth``, ``camera_matrix`` and ``normalize_points`` mean here what they mean for- :func:`~kornia.geometry.depth.depth_to_3d`, whose Convention block states the pixel grid, the camera- frame and the two readings of ``depth``; the result carries that function's :math:`(B, 3, H, W)`- layout, with the three normal components on the channel axis.+ - the normal is the unit cross product ``d/dx`` x ``d/dy`` of the unprojected point cloud, so a+ fronto-parallel plane gets ``(0, 0, 1)``, pointing **away** from the camera; a depth growing along+ the columns tilts it towards ``-x``, one growing along the rows towards ``-y``.+ - the arguments mean what they mean for :func:`~kornia.geometry.depth.depth_to_3d`, and the result+ has its :math:`(B, 3, H, W)` layout.Args:depth: image tensor containing a depth value per pixel with shape :math:`(B, 1, H, W)`, with@@ -339,16 +302,15 @@ def depth_from_plane_equation(- the plane is given in Hessian form :math:`n \cdot X = d`, with the normal ``plane_normals`` and theoffset ``plane_offsets`` in the **camera** frame: ``n = (0, 0, 1)`` with ``d = 2`` is the plane``z = 2``, and every pixel on it has depth 2.- - ``points_uv`` are pixel coordinates on the integer-centre grid described in the Convention block on- :class:`~kornia.geometry.camera.pinhole.PinholeCamera`; this function normalizes them with- ``camera_matrix`` itself, so they are pixels and not normalized coordinates.- - the result is the camera-frame ``z`` of each of those pixels, one value per pixel, in the- :math:`(B, N)` layout of ``points_uv`` -- a list of depths rather than a depth map.- - the ray-plane dot product is clamped, in a masked branch, to :math:`\pm` ``eps`` when it falls- strictly inside :math:`(-eps, eps)`, keeping the sign of the denominator, so a nearly-grazing ray- returns a large signed depth. An exactly zero denominator is replaced by positive ``eps``.- The result is finite when representable in the input dtype; small ``eps`` can still underflow- or produce overflow in ``float16``. Nothing outside the mask is touched.+ - ``points_uv`` are **pixels** (integer centres; see+ :class:`~kornia.geometry.camera.pinhole.PinholeCamera`), normalized here with ``camera_matrix``.+ - the result is the camera-frame ``z`` of each pixel, :math:`(B, N)`: a list of depths, not a map.+ - a ray-plane dot product inside :math:`(-eps, eps)` is replaced by :math:`\pm` ``eps`` with its sign+ (``+eps`` for an exact zero), so a grazing ray returns a large signed depth rather than ``inf``.++ .. warning::+ The default ``eps = 1e-8`` rounds to zero in float16, where a grazing ray therefore returns ``inf``:+ `#4803 <https://github.com/kornia/kornia/issues/4803>`_.Args:plane_normals (torch.Tensor): Plane normal vectors of shape (B, 3).@@ -409,26 +371,16 @@ def warp_frame_depth(Convention:- the depth belongs to the **destination** frame (``depth_dst``) and the image to the **source** frame(``image_src``), and ``src_trans_dst`` maps destination-frame points into the source frame. With- ``fx = fy = 1`` and a unit depth, a :math:`+1` translation in ``x`` therefore samples ``image_src``- one pixel to the right of each destination pixel.+ ``fx = fy = 1`` and a unit depth, a :math:`+1` translation in ``x`` samples ``image_src`` one pixel to+ the right of each destination pixel.- the unprojection is :func:`~kornia.geometry.depth.depth_to_3d_v2` and the reprojection- :func:`~kornia.geometry.camera.perspective.project_points`, so the pixel grid, the camera frame and- the two readings of ``depth`` selected by ``normalize_points`` are the ones stated in that function's- Convention block.- - the sampling is ``grid_sample`` with ``align_corners=True`` and the default- ``padding_mode="zeros"``, both baked in: the function exposes neither. Bilinear interpolation blends in-bounds- neighbors with the zero extension outside the image, so subpixel samples just beyond the border- can be nonzero; samples whose entire interpolation footprint is outside return 0.- - the result carries ``image_src``'s channel count, whatever it is: the output is :math:`(B, D, H, W)`.-- See :doc:`camera and world conventions </get-started/camera-conventions>` for the camera-frame,- depth and intrinsics conventions composed by this warp.+ :func:`~kornia.geometry.camera.perspective.project_points`, whose conventions apply.+ - the sampling is bilinear ``grid_sample`` with a fixed ``align_corners=True`` and+ ``padding_mode="zeros"``; the output is :math:`(B, D, H, W)` with ``image_src``'s channels... warning::- :class:`~kornia.geometry.depth.DepthWarper` performs the same warp under the **opposite** naming: the- frame this function calls ``dst`` (the one holding the depth) is that class's ``src``, and the image it- calls ``image_src`` is that class's ``patch_dst``. The Convention block on- :class:`~kornia.geometry.depth.DepthWarper` states the mapping in full. Tracked as+ :class:`~kornia.geometry.depth.DepthWarper` performs the same warp under the **opposite** naming: this+ function's ``dst`` (holding the depth) is that class's ``src``, and ``image_src`` is its ``patch_dst``:`#4273 <https://github.com/kornia/kornia/issues/4273>`_.Args:@@ -491,51 +443,23 @@ class DepthWarper(nn.Module):- this is a two-step API: :meth:`compute_projection_matrix` has to be called first. Until it hasbeen, :meth:`warp_grid` and :meth:`forward` raise ``ValueError`` and :meth:`compute_subpixel_step`raises ``RuntimeError``.- - :meth:`compute_projection_matrix` stores exactly the matrix of the equation above,- ``K_dst @ (E_dst @ inverse(E_src))``, with ``K_dst`` and ``E_dst`` the ``intrinsics`` and- ``extrinsics`` of the ``pinhole_dst`` given to the constructor and ``E_src`` the ``extrinsics`` of- the ``pinhole_src`` given to that method. The source extrinsics are inverted, not transposed, so the- translation is carried through.- - both cameras are :class:`~kornia.geometry.camera.pinhole.PinholeCamera` objects, so their- ``intrinsics`` are the :math:`(B, 4, 4)` matrix and their ``extrinsics`` the world-to-camera- transform that class's Convention block describes.- - the ``grid`` attribute is this instance's own grid of integer pixel centres -- the grid- :func:`~kornia.geometry.grid.create_meshgrid` enumerates and the Convention block on- :class:`~kornia.geometry.camera.pinhole.PinholeCamera` describes -- in homogeneous form: pixel- ``(0, 0)`` is ``(0, 0, 1)``. :meth:`warp_grid` returns something else: the sampling positions in- ``grid_sample``'s ``align_corners=True`` normalized coordinates, in which the **destination**- image's integer-centre pixel ``(0, 0)`` is ``(-1, -1)`` and its pixel ``(H - 1, W - 1)`` is- ``(1, 1)``. Where each destination pixel actually lands is wherever the reprojection sends it: an- identity camera pair leaves pixel ``(0, 0)`` at ``(-1, -1)``, a rotated and translated one sends- it elsewhere.- - ``align_corners`` defaults to ``True``; it is handed to ``grid_sample`` unchanged, together with- ``mode`` and ``padding_mode``.- - :func:`~kornia.geometry.depth.depth_warp` is the functional form of this class -- it builds one,- calls :meth:`compute_projection_matrix` and forwards -- and returns a result equal to it bit for bit.- It exposes ``align_corners`` only; ``mode`` and ``padding_mode`` keep their defaults there.-- See :doc:`camera and world conventions </get-started/camera-conventions>` for the camera/world-frame,- intrinsics and pixel-centre conventions used by this class.+ - :meth:`compute_projection_matrix` stores ``K_dst @ (E_dst @ inverse(E_src))``, the matrix above, from+ the constructor's ``pinhole_dst`` and that method's ``pinhole_src`` (both+ :class:`~kornia.geometry.camera.pinhole.PinholeCamera`, world-to-camera extrinsics).+ - the ``grid`` attribute is the homogeneous integer-centre pixel grid (pixel ``(0, 0)`` is+ ``(0, 0, 1)``); :meth:`warp_grid` returns sampling positions in ``grid_sample``'s+ ``align_corners=True`` normalized coordinates of the **destination** image.+ - ``align_corners`` (default ``True``), ``mode`` and ``padding_mode`` are forwarded to ``grid_sample``.+ :func:`~kornia.geometry.depth.depth_warp` is the functional form and exposes ``align_corners`` only... warning::- :func:`~kornia.geometry.depth.warp_frame_depth` performs the same warp under the **opposite** naming.- The frame this class calls ``src``, the one holding the depth, is that function's ``dst``- (``depth_dst``), and the image this class takes as ``patch_dst`` is that function's ``image_src``;- reading "dst" as "dst" across the two APIs gives the inverse warp. The two also differ arithmetically:- they build the sampling grid by different routes -- :func:`~kornia.geometry.depth.depth_to_3d_v2` and- :func:`~kornia.geometry.camera.perspective.project_points` here, ``pixel2cam`` and ``cam2pixel`` there- -- so the grid, and with it the resampled image, can differ in the last bits. Where the two grids come- out bit-identical, so do the images. Wherever the transformed points keep a camera-frame ``z`` away- from zero, the two agree at the working dtype's tolerance in float32 and float64; in float16 and- bfloat16 the gap is wider than that tolerance, which is why the agreement is claimed for the two- single- and double-precision dtypes only. At ``z = 0`` the two split outright, because their two- projection routes guard the singularity differently:- :func:`~kornia.geometry.camera.perspective.project_points` skips the homogeneous divide when- ``abs(z) <= 1e-8``, so :func:`~kornia.geometry.depth.warp_frame_depth` samples ``image_src`` at the- undivided ``(x, y)`` and returns image content, while ``cam2pixel`` divides by ``z + 1e-12`` and sends- the same pixel to a coordinate of order ``1e12``, far outside the image. That split is one instance of- `#4267 <https://github.com/kornia/kornia/issues/4267>`_, the namespace-wide ``z = 0`` conflict. The- naming conflict is tracked as `#4273 <https://github.com/kornia/kornia/issues/4273>`_.+ :func:`~kornia.geometry.depth.warp_frame_depth` performs the same warp under the **opposite** naming:+ this class's ``src`` (holding the depth) is that function's ``dst``, and ``patch_dst`` is its+ ``image_src``; reading "dst" as "dst" across the two gives the inverse warp:+ `#4273 <https://github.com/kornia/kornia/issues/4273>`_. The two agree to rounding for float32/float64+ away from ``z = 0``, and split at ``z = 0``, where ``cam2pixel`` sends every pixel with a nonzero+ projected numerator far outside the image:+ `#4267 <https://github.com/kornia/kornia/issues/4267>`_.Args:pinhole_dst: the pinhole model for the destination frame.@@ -824,23 +748,15 @@ def depth_from_disparity(- the depth is ``baseline * focal / disparity``, elementwise: ``baseline`` is the distance between thetwo camera centres and ``focal`` the focal length in pixels, so a disparity of 2 with a baseline of0.5 and a focal length of 100 gives a depth of 25.- - ``baseline`` and ``focal`` are each a Python ``int`` or ``float``, a scalar tensor, or a tensor of- shape :math:`(1,)`, all of which share one value across the whole disparity; or a per-batch-element- tensor of shape :math:`(B,)`, which pairs element ``b`` with ``disparity[b]``. A :math:`(B,)` tensor- needs a batch axis, so ``disparity`` must be at least :math:`(B, H, W)` with a leading size of ``B``;- any other size raises ``ShapeError``. The two may mix, for example a per-sample ``baseline`` with- one shared ``focal``.- - ``disparity`` is :math:`(*, H, W)` and the result has its shape. Its sign is not checked, so a- negative disparity gives a negative depth.+ - ``baseline`` and ``focal`` are each a scalar (Python number, 0-d or :math:`(1,)` tensor) shared by the+ whole disparity, or a :math:`(B,)` tensor paired with ``disparity[b]``, which then needs a leading+ batch axis of size ``B`` (otherwise ``ShapeError``). The two may mix.+ - ``disparity`` is :math:`(*, H, W)` and the result has its shape. Its sign is not checked... warning::- The epsilon is inside the arithmetic -- the divisor is ``disparity + 1e-8`` -- instead of selecting a- branch, so a zero disparity, which is what a stereo matcher writes where it found no match, returns a- large finite depth rather than ``inf`` in float32, float64 and bfloat16: ``baseline * focal / 1e-8``,- ``5e9`` for a baseline of ``0.5`` and a focal length of ``100``, a value set by the epsilon as much as- by the camera and one no caller can threshold against. In float16 the ``1e-8`` itself rounds to zero,- so the same call divides by zero and returns ``inf`` after all. Tracked as- `#4272 <https://github.com/kornia/kornia/issues/4272>`_.+ The divisor is ``disparity + 1e-8``, so a zero disparity (no stereo match) returns a large finite depth+ set by the epsilon (``5e9`` for baseline ``0.5``, focal ``100``) rather than ``inf``, except where the+ epsilon underflows: `#4272 <https://github.com/kornia/kornia/issues/4272>`_.Args:disparity: Disparity tensor of shape :math:`(*, H, W)`.diff --git a/kornia/losses/focal.py b/kornia/losses/focal.pyindex 7302046c2..d4e0a422f 100644--- a/kornia/losses/focal.py+++ b/kornia/losses/focal.py@@ -331,7 +331,7 @@ class BinaryFocalLossWithLogits(nn.Module):\text{FL}(p_t) = -\alpha_t (1 - p_t)^{\gamma} \, \text{log}(p_t)- torch.where:+ where:- :math:`p_t` is the model's estimated probability for each class.Args:diff --git a/kornia/metrics/ssim3d.py b/kornia/metrics/ssim3d.pyindex 6f8a4cd2a..c757a5de8 100644--- a/kornia/metrics/ssim3d.py+++ b/kornia/metrics/ssim3d.py@@ -60,7 +60,7 @@ def ssim3d(\text{SSIM}(x, y) = \frac{(2\mu_x\mu_y+c_1)(2\sigma_{xy}+c_2)}{(\mu_x^2+\mu_y^2+c_1)(\sigma_x^2+\sigma_y^2+c_2)}- torch.where:+ where:- :math:`c_1=(k_1 L)^2` and :math:`c_2=(k_2 L)^2` are two variables tostabilize the division with weak denominator.- :math:`L` is the dynamic range of the pixel-values (typically this is@@ -152,7 +152,7 @@ class SSIM3D(nn.Module):\text{SSIM}(x, y) = \frac{(2\mu_x\mu_y+c_1)(2\sigma_{xy}+c_2)}{(\mu_x^2+\mu_y^2+c_1)(\sigma_x^2+\sigma_y^2+c_2)}- torch.where:+ where:- :math:`c_1=(k_1 L)^2` and :math:`c_2=(k_2 L)^2` are two variables tostabilize the division with weak denominator.- :math:`L` is the dynamic range of the pixel-values (typically this isdiff --git a/kornia/sensors/camera/camera_model.py b/kornia/sensors/camera/camera_model.pyindex 8f1490b35..def16af91 100644--- a/kornia/sensors/camera/camera_model.py+++ b/kornia/sensors/camera/camera_model.py@@ -112,54 +112,27 @@ class CameraModelBase: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. ``CameraModelBase.matrix`` implements it for all supported camera models.- - :meth:`project` is ``self.distortion.distort(self.params, self.projection.project(points))`` and- :meth:`unproject` the reverse,- ``self.projection.unproject(self.distortion.undistort(self.params, points), depth)``. ``depth`` is- 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>`_.-- See :doc:`camera and world conventions </get-started/camera-conventions>` for the shared pixel-centre,- depth and intrinsics conventions across the camera APIs.+ :meth:`unproject` the reverse; a raw :class:`torch.Tensor` is not accepted. This type system is kept+ separate from :doc:`kornia.geometry.camera </geometry.camera>` by design+ (`#4274 <https://github.com/kornia/kornia/issues/4274>`_).+ - ``params`` is a flat ``(N,)`` or batched :math:`(B, N)` vector whose length is fixed by the model:+ ``[fx, fy, cx, cy]`` for ``PINHOLE`` and ``ORTHOGRAPHIC``, 12 for ``BROWN_CONRADY`` and 8 for+ ``KANNALA_BRANDT_K3``; another length or a rank above 2 raises ``ValueError``.+ - :meth:`matrix` and its alias :meth:`K` return the :math:`(*, 3, 3)` ``K``, not the :math:`(B, 4, 4)`+ ``intrinsics`` that :class:`~kornia.geometry.camera.pinhole.PinholeCamera` stores.+ - :meth:`project` is ``distortion.distort(params, projection.project(points))`` and :meth:`unproject`+ the reverse; ``depth`` is the camera-frame ``z``, shaped ``(*,)`` where+ :func:`~kornia.geometry.camera.perspective.unproject_points` takes ``(*, 1)``. Pixel centres are+ integers (see :class:`~kornia.geometry.camera.pinhole.PinholeCamera`).++ .. warning::+ Batched ``(B, 4)`` intrinsics apply along the **last point axis**, not the camera axis: with+ ``(B, N, 3)`` points and ``B > 1`` they silently pair with the wrong points when ``B == N``,+ :meth:`project` broadcasts to a ``(B, B, 2)`` result when ``N == 1``, and other ``N`` raise, whereas the+ geometry functions apply them per camera:+ `#4274 <https://github.com/kornia/kornia/issues/4274>`_. :meth:`project` divides by ``z`` with no guard,+ so ``z = 0`` gives infinities where :func:`~kornia.geometry.camera.perspective.project_points` returns+ finite pixels: `#4267 <https://github.com/kornia/kornia/issues/4267>`_.Example:>>> params = torch.Tensor([328., 328., 320., 240.])@@ -370,19 +343,13 @@ class PinholeModel(CameraModelBase):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.-- See :doc:`camera and world conventions </get-started/camera-conventions>` for image resizing and- the matching intrinsics scaling convention.+ ``scale_factor``: ``fx' = s * fx`` and ``cx' = s * cx``, as+ :meth:`~kornia.geometry.camera.pinhole.PinholeCamera.scale` does... 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.+ ``cx' = s * cx`` disagrees with kornia's integer pixel centres, and a tensor ``scale_factor``+ rebuilds ``image_size`` with 0-dim tensors where the constructor took python integers:+ `#4263 <https://github.com/kornia/kornia/issues/4263>`_.Args:scale_factor: Scale factor to scale the camera model.diff --git a/kornia/sensors/camera/distortion_model.py b/kornia/sensors/camera/distortion_model.pyindex 799abeb1d..204efaa1a 100644--- a/kornia/sensors/camera/distortion_model.py+++ b/kornia/sensors/camera/distortion_model.py@@ -38,15 +38,9 @@ class AffineTransform: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.+ ``u = fx * x + cx`` and ``v = fy * y + cy``, with ``params`` laid out as ``[fx, fy, cx, cy]``;+ the ``Vector2`` counterpart of :func:`~kornia.geometry.camera.distort_points_affine`.+ - :meth:`undistort` is the closed-form inverse.Args:params: torch.Tensor representing the affine transform parameters.diff --git a/kornia/sensors/camera/projection_model.py b/kornia/sensors/camera/projection_model.pyindex 92436ec94..3980f1a09 100644--- a/kornia/sensors/camera/projection_model.py+++ b/kornia/sensors/camera/projection_model.py@@ -38,14 +38,12 @@ class Z1Projection: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.+ not in pixels: the map is ``xy / z``, with no epsilon and no validation... 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.+ A point with :math:`z = 0` projects to an infinity (``nan`` for a zero numerator) instead of raising:+ `#4267 <https://github.com/kornia/kornia/issues/4267>`_. A point behind the camera projects to a+ finite coordinate and is not flagged: `#4555 <https://github.com/kornia/kornia/issues/4555>`_.Args:points: Vector3 representing the points to project.@@ -75,8 +73,7 @@ class Z1Projection:Convention:- ``depth`` is the camera-frame ``z``: the :math:`z = 1` point is multiplied by it, so the thirdcoordinate 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.+ - a python ``float`` or ``int`` ``depth`` is converted to the device and dtype of ``points``.Args:points: Vector2 representing the points to unproject.diff --git a/tests/geometry/calibration/test_distort.py b/tests/geometry/calibration/test_distort.pyindex c38f54cbf..5471bf7e0 100644--- a/tests/geometry/calibration/test_distort.py+++ b/tests/geometry/calibration/test_distort.py@@ -184,15 +184,8 @@ class TestDistortPoints(BaseTester):assert self.gradcheck(distort_points, (points, K, distCoeff, new_K), raise_exception=True, fast_mode=True)def test_convention_accepts_4_5_8_12_14_coefficients_and_rejects_6(self, device, dtype):- # Convention pin: the distortion vector is OpenCV's- # (k1, k2, p1, p2[, k3[, k4, k5, k6[, s1, s2, s3, s4[, taux, tauy]]]]), so only the five prefix lengths- # 4, 5, 8, 12 and 14 are meaningful; anything else -- 6 and 3 below -- is a ValueError, not a silent- # zero-pad. Shorter accepted vectors ARE zero-padded to 14 internally, which is why 4 and 14 zeros give- # the same answer. undistort_points enforces the identical rule.- # Snippet used to generate expected: distort_points(pts, K, zeros(1, n)) for n in (3, 4, 5, 6, 8, 12, 14)- # executed 2026-09-06 on commit c0b50ad7 (torch 2.14.0, cpu and mps, every dtype) -> shape (1, 2, 2)- # for the five accepted lengths, ValueError("Invalid number of distortion coefficients. Got 6") for 6;- # torch.equal between the 4-coefficient answer and its 14-coefficient zero-padding -> True on every cell.+ # OpenCV's (k1, k2, p1, p2[, k3[, k4, k5, k6[, s1, s2, s3, s4[, taux, tauy]]]]): only the prefix lengths+ # 4, 5, 8, 12 and 14 are accepted, and a shorter vector is zero-padded to 14 internally.points = torch.tensor([[[54.0, 53.0], [-16.0, 23.0]]], device=device, dtype=dtype)K = _k_asymmetric(device, dtype)for n in (4, 5, 8, 12, 14):@@ -206,46 +199,16 @@ class TestDistortPoints(BaseTester):assert torch.equal(distort_points(points, K, short), distort_points(points, K, padded))def test_convention_zero_coefficients_are_a_no_op_at_dtype_tolerance(self, device, dtype):- # Convention pin: with every coefficient zero, distort_points normalizes- # with new_K (= K here) and denormalizes with K, so it is a no-op -- but only up to the dtype tolerance,- # because ``(u - cx) / fx`` followed by ``fx * x + cx`` is not an exact round trip for a general pixel.- # This is the GENERAL statement; the bit-for-bit case is scoped in the sibling pin below.- # The points sit half a focal length off the principal point on both sides of it, so the round trip is- # exercised at a radius where a non-zero coefficient would move them by 2.775 px, and the fractional- # offsets keep ``(u - cx) / fx`` off the exactly-representable grid.- # Snippet used to generate expected: (distort_points(pts, K, zeros(1, 4)) - pts).abs().max() on- # [[54.3, 53.7], [-16.1, 23.9]] executed 2026-09-06 on commit c0b50ad7 (torch 2.14.0), differenced- # in the working dtype -> cpu float32 3.81e-06 (torch.equal False), float64 0.0, float16 3.13e-02,- # bfloat16 2.50e-01; mps float32 3.81e-06, float16 3.13e-02.+ # With every coefficient zero, distort_points normalizes with new_K (= K here) and denormalizes with K,+ # so it is a no-op to roundoff. The points sit half a focal length off the principal point.points = torch.tensor([[[54.3, 53.7], [-16.1, 23.9]]], device=device, dtype=dtype)K = _k_asymmetric(device, dtype)self.assert_close(distort_points(points, K, torch.zeros(1, 4, device=device, dtype=dtype)), points)- def test_convention_zero_coefficients_are_bit_exact_on_these_points(self, device, dtype):- # On these four coordinates the normalize/denormalize arithmetic rounds back to the input- # bit for bit in the tested dtypes, even though +/-0.2 are not exactly representable in binary.- # This is NOT a general bit-for-bit no-op. Executed counterexample on the same K, 2026-09-06 on the- # commit c0b50ad7 (torch 2.14.0): the perturbed points [[54.3, 53.7], [-16.1, 23.9]] give torch.equal- # False with a residual of 3.81e-06 in cpu float32 (3.13e-02 in float16, 2.50e-01 in bfloat16); only the- # float64 cell is still exact there.- # Snippet used to generate expected: torch.equal(distort_points(pts, K, zeros(1, 4)), pts) on- # [[54.0, 53.0], [-16.0, 23.0]] executed 2026-09-06 -> True on cpu for float32/float64/float16/bfloat16- # and on mps for float32/float16.- points = torch.tensor([[[54.0, 53.0], [-16.0, 23.0]]], device=device, dtype=dtype)- K = _k_asymmetric(device, dtype)- assert torch.equal(distort_points(points, K, torch.zeros(1, 4, device=device, dtype=dtype)), points)-def test_convention_new_K_normalizes_and_K_denormalizes(self, device, dtype):- # Convention pin: the two intrinsics play OPPOSITE roles -- new_K maps- # the incoming pixel to the normalized z = 1 plane, K maps the distorted normalized point back to pixels.- # Every intrinsic is distinct here (new_K: fx 5, fy 7, cx 2, cy 4; K: fx 2, fy 3, cx 1, cy 1), so- # swapping the two arguments, or fx with fy, changes both literals: (10, 10) normalizes to- # ((10-2)/5, (10-4)/7) = (1.6, 6/7) and denormalizes to (2*1.6+1, 3*6/7+1) = (4.2, 3.571428...).- # The diag(2, 2, 1) probe is the same claim with the roles reversed: a (1, 2) pixel- # under new_K = diag(2, 2, 1) and K = eye(3) comes back as (0.5, 1.0).- # Snippet used to generate expected: distort_points([[[10., 10.]]], K, zeros(1, 4), new_K) executed- # 2026-09-06 on commit c0b50ad7 (torch 2.14.0, cpu float32) -> [[[4.199999809265137,- # 3.5714285373687744]]]; the same call on mps float32 gives the same value.+ # new_K maps the incoming pixel to the normalized z = 1 plane and K maps it back to pixels. Every+ # intrinsic is distinct, so swapping the arguments or fx with fy changes the literal: (10, 10) normalizes+ # to ((10-2)/5, (10-4)/7) = (1.6, 6/7) and denormalizes to (2*1.6+1, 3*6/7+1) = (4.2, 3.571428...).K = torch.tensor([[[2.0, 0.0, 1.0], [0.0, 3.0, 1.0], [0.0, 0.0, 1.0]]], device=device, dtype=dtype)new_K = torch.tensor([[[5.0, 0.0, 2.0], [0.0, 7.0, 4.0], [0.0, 0.0, 1.0]]], device=device, dtype=dtype)zero_dist = torch.zeros(1, 4, device=device, dtype=dtype)@@ -265,16 +228,9 @@ class TestDistortPoints(BaseTester):)def test_convention_agrees_with_distort_points_affine_on_the_same_camera(self, device, dtype):- # Convention pin: the two paths encode the same- # pinhole camera through different INPUT DOMAINS and parametrizations. distort_points_affine takes a- # normalized z = 1 point and a flat [fx, fy, cx, cy]; calibration.distort_points takes a pixel point, a- # (3, 3) K and a coefficient vector. Feeding the normalized point through distort_points with- # new_K = eye(3) (so the normalization step is the identity) and K = the same camera reproduces the- # affine answer bit for bit, and the already-pixel point with zero coefficients- # gives the same [54, 28].- # Snippet used to generate expected: torch.equal(distort_points([[[0.5, 0.25]]], K, zeros(1, 4), eye(3)[None])- # .reshape(2), distort_points_affine([0.5, 0.25], [100., 100., 4., 3.])) executed 2026-09-06 on the- # commit c0b50ad7 (torch 2.14.0, cpu float32) -> True, value [54., 28.].+ # Same camera, different input domains: distort_points_affine takes a normalized z = 1 point and a flat+ # [fx, fy, cx, cy]; distort_points takes a pixel, a (3, 3) K and a coefficient vector, so with+ # new_K = eye(3) it maps the normalized point to the same pixel.K = _k_asymmetric(device, dtype)zero_dist = torch.zeros(1, 4, device=device, dtype=dtype)expected = torch.tensor([[[54.0, 28.0]]], device=device, dtype=dtype)@@ -282,7 +238,7 @@ class TestDistortPoints(BaseTester):torch.tensor([0.5, 0.25], device=device, dtype=dtype),torch.tensor([100.0, 100.0, 4.0, 3.0], device=device, dtype=dtype),)- self.assert_close(affine.reshape(1, 1, 2), expected, atol=0.0, rtol=0.0)+ self.assert_close(affine.reshape(1, 1, 2), expected)self.assert_close(distort_points(torch.tensor([[[0.5, 0.25]]], device=device, dtype=dtype),@@ -291,41 +247,32 @@ class TestDistortPoints(BaseTester):torch.eye(3, device=device, dtype=dtype)[None],),expected,- atol=0.0,- rtol=0.0,- )- self.assert_close(distort_points(expected, K, zero_dist), expected, atol=0.0, rtol=0.0)-- def test_convention_tilt_projection_zero_angles_are_the_identity(self, device, dtype):- # Both branches reduce to the identity when tilt is disabled.- zero = torch.zeros(1, 1, device=device, dtype=dtype)- identity = torch.eye(3, device=device, dtype=dtype)[None]- assert torch.equal(tilt_projection(zero, zero), identity)- self.assert_close(tilt_projection(zero, zero, True), identity, atol=0.0, rtol=0.0)-- def test_convention_tilt_projection_inverse_branch_inverts_pz_times_r(self, device, dtype):- # Preserve OpenCV's inverse independently of the forward/inverse round trip (#4276).- # A simultaneous change to both branches must not hide a convention error.- r, p_z = _pz_r(0.1, 0.2, device, dtype)- inverse = tilt_projection(- torch.tensor([[0.1]], device=device, dtype=dtype), torch.tensor([[0.2]], device=device, dtype=dtype), True)- identity = torch.eye(3, device=device, dtype=dtype)[None]- self.assert_close((p_z @ r) @ inverse, identity)- wrong = (p_z @ r.transpose(-1, -2)) @ inverse- assert (wrong - identity).abs().max().item() > 0.1+ self.assert_close(distort_points(expected, K, zero_dist), expected)def test_convention_tilt_projection_forward_is_pz_times_r_4276(self, device, dtype):+ # OpenCV's tilt projection is Pz @ R (distortion_model.hpp); zero angles give the identity.+ zero = torch.zeros(1, 1, device=device, dtype=dtype)+ self.assert_close(tilt_projection(zero, zero), torch.eye(3, device=device, dtype=dtype)[None])r, p_z = _pz_r(0.1, 0.2, device, dtype)taux = torch.tensor([[0.1]], device=device, dtype=dtype)tauy = torch.tensor([[0.2]], device=device, dtype=dtype)self.assert_close(tilt_projection(taux, tauy), p_z @ r)- def test_convention_tilt_projection_branches_are_inverses_4276(self, device, dtype):+ def test_convention_tilt_projection_inverse_branch_inverts_pz_times_r_4276(self, device, dtype):+ # Checked against the independent Pz @ R, not only against the forward branch, so a simultaneous+ # change to both branches cannot hide a convention error.+ zero = torch.zeros(1, 1, device=device, dtype=dtype)+ identity = torch.eye(3, device=device, dtype=dtype)[None]+ self.assert_close(tilt_projection(zero, zero, True), identity)+ r, p_z = _pz_r(0.1, 0.2, device, dtype)taux = torch.tensor([[0.1]], device=device, dtype=dtype)tauy = torch.tensor([[0.2]], device=device, dtype=dtype)- product = tilt_projection(taux, tauy) @ tilt_projection(taux, tauy, True)- self.assert_close(product, torch.eye(3, device=device, dtype=dtype)[None])+ inverse = tilt_projection(taux, tauy, True)+ self.assert_close((p_z @ r) @ inverse, identity)+ self.assert_close(tilt_projection(taux, tauy) @ inverse, identity)+ wrong = (p_z @ r.transpose(-1, -2)) @ inverse+ assert (wrong - identity).abs().max().item() > 0.1def test_jit(self, device, dtype):# A random K has fx, fy < 1, and with random coefficients the distortion polynomialdiff --git a/tests/geometry/calibration/test_pnp.py b/tests/geometry/calibration/test_pnp.pyindex 6e166943b..3cb835caf 100644--- a/tests/geometry/calibration/test_pnp.py+++ b/tests/geometry/calibration/test_pnp.py@@ -19,7 +19,7 @@ import pytestimport torchimport kornia-from kornia.core.exceptions import ShapeError+from kornia.core.exceptions import BaseError, ShapeErrorfrom kornia.geometry.calibration.pnp import _mean_isotropic_scale_normalizefrom testing.base import BaseTester@@ -184,18 +184,11 @@ class TestSolvePnpDlt(BaseTester):)def test_convention_returns_the_world_to_camera_extrinsics(self, device, dtype):- # Convention pin: solve_pnp_dlt returns a (B, 3, 4)- # [R | t] that maps WORLD points INTO the camera frame -- the same direction as PinholeCamera.extrinsics- # and OpenCV's solvePnP rvec/tvec, not the camera pose in the world. Two cases: world points that are- # already camera-frame points recover [I | 0], and a camera translated so that cam = world + (1, 0, 0)- # recovers t = (+1, 0, 0). A cam-to-world reading would give t = (-1, 0, 0) on the second case, which is- # why the identity case alone is not enough.- # Snippet used to generate expected: solve_pnp_dlt(W, project_points(W + [1., 0., 0.], K), K) executed- # 2026-09-06 at c0b50ad7 (torch 2.14.0, cpu float64) -> [[[1., -0., -0., 1.], [0., 1., -0.,- # 0.], [0., 0., 1., 0.]]], max abs error vs [I | (1, 0, 0)] 6.14e-15; the identity case gives [I | 0] to- # 8.01e-14.- if dtype != torch.float64:- pytest.skip("float64-only pin: float32 recovers [R|t] to 1.06e-05 on mps, outside the float32 atol")+ # The (B, 3, 4) [R | t] maps world points into the camera frame (PinholeCamera.extrinsics, OpenCV+ # solvePnP). Camera-frame world points recover [I | 0]; a camera with cam = world + (1, 0, 0) recovers+ # t = (+1, 0, 0), where a camera-to-world reading would give (-1, 0, 0).+ if dtype not in (torch.float32, torch.float64):+ pytest.skip("solve_pnp_dlt accepts float32 and float64 only (pinned below)")world_points = self._convention_world_points(device, dtype)K = torch.tensor([[[100.0, 0.0, 4.0], [0.0, 100.0, 3.0], [0.0, 0.0, 1.0]]], device=device, dtype=dtype)identity = torch.tensor(@@ -203,7 +196,7 @@ class TestSolvePnpDlt(BaseTester):)recovered = kornia.geometry.solve_pnp_dlt(world_points, kornia.geometry.project_points(world_points, K), K)assert recovered.shape == (1, 3, 4)- self.assert_close(recovered, identity)+ self.assert_close(recovered, identity, atol=1e-4, rtol=1e-4)shift = torch.tensor([1.0, 0.0, 0.0], device=device, dtype=dtype)shifted = kornia.geometry.solve_pnp_dlt(world_points, kornia.geometry.project_points(world_points + shift, K), K@@ -211,42 +204,28 @@ class TestSolvePnpDlt(BaseTester):expected = torch.tensor([[[1.0, 0.0, 0.0, 1.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0]]], device=device, dtype=dtype)- self.assert_close(shifted, expected)-- def test_convention_world_to_camera_translation_sign(self, device, dtype):- # Convention pin: the tolerance-free half of the pin above covers the- # frame-direction claim is covered on every device and not only where float64 exists (mps has none).- # A camera translated so that cam = world + (1, 0, 0) gives a world-to-camera [R | t] with t = (+1, 0, 0);- # the cam-to-world reading is t = (-1, 0, 0). The assertion is a sign test, not a value test, so it needs- # no tolerance and survives the float32 solve on mps, which recovers t only to about 1e-05.- # Snippet used to generate expected: solve_pnp_dlt(W, project_points(W + [1., 0., 0.], K), K)[0, :, 3]- # executed 2026-09-06 at c0b50ad7 (torch 2.14.0) -> cpu float32- # [1.0000005960464478, 3.45e-06, 5.88e-06]; mps float32 [1.0000009536743164, -2.21e-06, -1.06e-05].- if dtype not in (torch.float32, torch.float64):- pytest.skip("solve_pnp_dlt's shape/dtype validation rejects float16 and bfloat16 (BaseError)")+ self.assert_close(shifted, expected, atol=1e-4, rtol=1e-4)++ def test_convention_validation_errors_name_the_argument(self, device, dtype):+ # solve_pnp_dlt accepts float32 and float64 only, needs N >= 6 points and a float svd_eps; each check+ # raises a kornia BaseError that names its argument.world_points = self._convention_world_points(device, dtype)K = torch.tensor([[[100.0, 0.0, 4.0], [0.0, 100.0, 3.0], [0.0, 0.0, 1.0]]], device=device, dtype=dtype)- shift = torch.tensor([1.0, 0.0, 0.0], device=device, dtype=dtype)- translation = kornia.geometry.solve_pnp_dlt(- world_points, kornia.geometry.project_points(world_points + shift, K), K- )[0, :, 3]- assert translation[0] > 0.5- assert abs(translation[1]) < 0.5- assert abs(translation[2]) < 0.5+ img_points = world_points[..., :2] / world_points[..., 2:]+ if dtype not in (torch.float32, torch.float64):+ with pytest.raises(BaseError, match="world_points must be float32 or float64"):+ kornia.geometry.solve_pnp_dlt(world_points, img_points, K)+ return+ with pytest.raises(BaseError, match="world_points must hold at least 6 points"):+ kornia.geometry.solve_pnp_dlt(world_points[:, :5], img_points[:, :5], K)+ with pytest.raises(BaseError, match="svd_eps must be a float, got int"):+ kornia.geometry.solve_pnp_dlt(world_points, img_points, K, svd_eps=1)def test_convention_rejects_4x4_intrinsics(self, device, dtype):- # Convention pin: ``intrinsics`` is the (B, 3, 3)- # K, and the (B, 4, 4) intrinsics matrix that a PinholeCamera stores is rejected by the shape check- # rather than silently truncated to its upper-left block. The positive control is the same call with- # that upper-left block passed on its own, which solves: so the rejection is about the shape and not- # about the camera.- # Snippet used to generate expected: solve_pnp_dlt(W, project_points(W, K), eye(4)[None] with K in the- # upper-left 3x3) executed 2026-09-06 at c0b50ad7 (torch 2.14.0) -> ShapeError("Shape- # mismatch at dimension 1: expected 3, got 4. | Expected shape: ['B', '3', '3'] | Actual shape:- # [1, 4, 4]") on cpu float32 and float64. In float16 and bfloat16 the earlier dtype validation fires- # first with a bare BaseError("Validation condition failed"), so those cells are skipped.+ # intrinsics is the (B, 3, 3) K: the (B, 4, 4) matrix a PinholeCamera stores is rejected rather than+ # truncated, while its upper-left block solves.if dtype not in (torch.float32, torch.float64):- pytest.skip("solve_pnp_dlt's dtype validation rejects float16 and bfloat16 before the 4x4 shape check")+ pytest.skip("solve_pnp_dlt accepts float32 and float64 only")world_points = self._convention_world_points(device, dtype)K = torch.tensor([[[100.0, 0.0, 4.0], [0.0, 100.0, 3.0], [0.0, 0.0, 1.0]]], device=device, dtype=dtype)img_points = kornia.geometry.project_points(world_points, K)@@ -257,16 +236,10 @@ class TestSolvePnpDlt(BaseTester):assert kornia.geometry.solve_pnp_dlt(world_points, img_points, K_4x4[:, :3, :3]).shape == (1, 3, 4)def test_convention_planar_world_points_raise(self, device, dtype):- # Convention pin: the DLT needs a non-degenerate configuration, and- # the function enforces it -- a coplanar point set (the same six points flattened onto z = 5) raises- # AssertionError naming the last singular value, rather than returning a silently wrong pose. This is a- # documented, validated contract, so it is a convention and not a wart.- # Snippet used to generate expected: solve_pnp_dlt(planar, project_points(planar, K), K) executed- # 2026-09-06 at c0b50ad7 (torch 2.14.0, cpu float32 and float64) -> AssertionError("The last- # singular value of one/more of the elements of the batch is smaller than 0.0001. ..."). In float16 and- # bfloat16 the earlier dtype validation fires first, so those cells are skipped.+ # A coplanar point set (the six points flattened onto z = 5) raises kornia's singular-value+ # AssertionError instead of returning a wrong pose.if dtype not in (torch.float32, torch.float64):- pytest.skip("solve_pnp_dlt's dtype validation rejects float16 and bfloat16 before the degeneracy check")+ pytest.skip("solve_pnp_dlt accepts float32 and float64 only")world_points = self._convention_world_points(device, dtype)K = torch.tensor([[[100.0, 0.0, 4.0], [0.0, 100.0, 3.0], [0.0, 0.0, 1.0]]], device=device, dtype=dtype)planar = torch.stack(@@ -275,6 +248,27 @@ class TestSolvePnpDlt(BaseTester):with pytest.raises(AssertionError, match="last singular value"):kornia.geometry.solve_pnp_dlt(planar, kornia.geometry.project_points(planar, K), K)+ def test_wart_zero_weight_point_still_enters_the_degeneracy_check_4799(self, device, dtype):+ # kornia#4799: the same coplanar set plus two off-plane points recovers [I | 0]; with those two points at+ # weight 0 it still passes the degeneracy check, which ignores the weights, and the rank-deficient system+ # returns a wrong pose. A fix that checks the weighted points raises here instead.+ if dtype not in (torch.float32, torch.float64):+ pytest.skip("solve_pnp_dlt accepts float32 and float64 only")+ world_points = self._convention_world_points(device, dtype)+ K = torch.tensor([[[100.0, 0.0, 4.0], [0.0, 100.0, 3.0], [0.0, 0.0, 1.0]]], device=device, dtype=dtype)+ planar = torch.stack(+ [world_points[0, :, 0], world_points[0, :, 1], torch.full_like(world_points[0, :, 0], 5.0)], -1+ )[None]+ off_plane = torch.tensor([[[0.0, 0.0, 8.0], [1.0, -1.0, 11.0]]], device=device, dtype=dtype)+ points = torch.cat([planar, off_plane], 1)+ img_points = kornia.geometry.project_points(points, K)+ weights = torch.ones(1, points.shape[1], device=device, dtype=dtype)+ pose = kornia.geometry.solve_pnp_dlt(points, img_points, K, weights=weights)+ assert pose[0, :, 3].abs().max() < 1e-2+ weights[0, -2:] = 0.0+ pose = kornia.geometry.solve_pnp_dlt(points, img_points, K, weights=weights)+ assert pose[0, :, 3].abs().max() > 1.0+class TestNormalization(BaseTester):@pytest.mark.parametrize("dimension", (2, 3, 5))diff --git a/tests/geometry/calibration/test_undistort.py b/tests/geometry/calibration/test_undistort.pyindex 7bd948ad7..e62b5fe85 100644--- a/tests/geometry/calibration/test_undistort.py+++ b/tests/geometry/calibration/test_undistort.py@@ -133,23 +133,6 @@ class TestUndistortPoints(BaseTester):pointsu = undistort_points(points, K, distCoeff, new_K)assert pointsu.shape == (B, N, 2)- @pytest.mark.device_agnostic- def test_convention_out_of_radius_fixed_point_is_a_two_cycle_4285(self):- dtype = torch.float64- K = torch.tensor([[[100.0, 0.0, 4.0], [0.0, 100.0, 3.0], [0.0, 0.0, 1.0]]], dtype=dtype)- dist = torch.tensor([[0.5, 0.0, 0.0, 0.0]], dtype=dtype)- points = torch.tensor([[[304.0, 3.0]]], dtype=dtype)- distorted = distort_points(points, K, dist)-- residuals = {}- for num_iters in (5, 6, 7, 8):- recovered = undistort_points(distorted, K, dist, num_iters=num_iters)- residuals[num_iters] = (recovered - points).abs().max()-- self.assert_close(residuals[5], residuals[7])- self.assert_close(residuals[6], residuals[8])- assert residuals[6] > residuals[5] > 1-def test_opencv_five_coeff(self, device, dtype):# Test using 5 distortion coefficientspts = torch.tensor(@@ -334,22 +317,10 @@ class TestUndistortPoints(BaseTester):self.assert_close(ptsu[1], ptsu_expected2, rtol=1e-4, atol=1e-4)def test_convention_undistort_points_inverts_distort_points(self, device, dtype):- # Convention pin: undistort_points is the- # ITERATIVE inverse of distort_points (a 5-step fixed point by default), so the round trip closes to the- # dtype tolerance on these points with moderate coefficients. Both- # functions take PIXEL points and a (3, 3) K -- contrast the affine and Kannala-Brandt pairs in- # tests/geometry/camera/test_distortion.py, which take normalized z = 1 points and a flat parameter- # vector. The pin asserts closure at assert_close's dtype tolerance and states no error bound; the- # five-step float64 residual (4.62e-05) passes because atol plus rtol * abs(points) allows it.- # Raising the count to 50 improves float32/float64 accuracy; float16 stays at its rounding floor.- # Outside the valid radius the iteration can cycle (#4285), pinned separately below.- # The two pixels sit half a focal length off the principal point in both directions and on both sides of- # it, so the forward map actually moves them by 2.775 px -- a round trip pin on near-axis points would- # pass with undistort_points replaced by the identity.- # Snippet used to generate expected: (undistort_points(distort_points(pts, K, d), K, d) - pts).abs().max()- # executed 2026-09-06 on commit c0b50ad7 (torch 2.14.0), differenced in the working dtype -> cpu- # float32 3.81e-05, float64 4.62e-05, float16 1.56e-02, bfloat16 0.0; mps float32 3.81e-05,- # float16 1.56e-02. The forward displacement (distorted - points).abs().max() is 2.775 px on cpu float32.+ # undistort_points is the iterative (5-step fixed point by default) inverse of distort_points on pixel+ # points and a (3, 3) K; the round trip closes to the dtype tolerance with moderate coefficients. The+ # points sit half a focal length off the principal point, so the forward map moves them (2.775 px) and an+ # identity undistort_points would fail. Outside the valid radius the iteration cycles (#4285, below).points = torch.tensor([[[54.0, 53.0], [-16.0, 23.0]]], device=device, dtype=dtype)K = _k_asymmetric(device, dtype)dist = torch.tensor([[0.1, 0.01, 0.001, 0.001]], device=device, dtype=dtype)@@ -373,18 +344,9 @@ class TestUndistortPoints(BaseTester):self.assert_close(undistort_points(distort_points(points, K, zero_tilt), K, zero_tilt), points)def test_convention_new_K_denormalizes_and_K_normalizes(self, device, dtype):- # The two intrinsics play the mirror image of their- # roles in distort_points -- here K maps the incoming distorted pixel onto the normalized z = 1 plane and- # new_K maps the undistorted normalized point back to pixels, which is why the same new_K that shrinks- # the forward answer enlarges this one. Every intrinsic is distinct (K: fx 2, fy 3, cx 1, cy 1; new_K:- # fx 5, fy 7, cx 2, cy 4), so swapping the two arguments, or fx with fy, changes both literals:- # (10, 10) normalizes under K to ((10-1)/2, (10-1)/3) = (4.5, 3.0) and denormalizes under new_K to- # (5*4.5+2, 7*3+4) = (24.5, 25.0). The sibling pin in test_distort.py fixes the forward direction.- # Snippet used to generate expected: undistort_points([[[10., 10.]]], K, zeros(1, 4), new_K) executed- # 2026-09-06 on commit c0b50ad7 (torch 2.14.0, cpu float32 and float64) -> [[[24.5, 25.0]]]; the- # same call on mps float32 gives the same value. The second case, the mirror of test_distort.py's- # diag(2, 2, 1) probe, doubles instead of halving: (1, 2) under K = eye(3) and new_K = diag(2, 2, 1)- # comes back as (2.0, 4.0).+ # The mirror image of distort_points: K maps the incoming pixel onto the normalized z = 1 plane and new_K+ # maps it back to pixels. Every intrinsic is distinct, so a swap changes the literal: (10, 10) normalizes+ # under K to ((10-1)/2, (10-1)/3) = (4.5, 3.0) and denormalizes under new_K to (5*4.5+2, 7*3+4).K = torch.tensor([[[2.0, 0.0, 1.0], [0.0, 3.0, 1.0], [0.0, 0.0, 1.0]]], device=device, dtype=dtype)new_K = torch.tensor([[[5.0, 0.0, 2.0], [0.0, 7.0, 4.0], [0.0, 0.0, 1.0]]], device=device, dtype=dtype)zero_dist = torch.zeros(1, 4, device=device, dtype=dtype)@@ -404,21 +366,8 @@ class TestUndistortPoints(BaseTester):)def test_convention_more_iterations_shrink_the_round_trip_residual(self, device, dtype):- # Inside the convergence region, more iterations reduce the residual down to the rounding floor.- # The fx = fy = 100 camera above already passes assert_close after five steps, although 50 steps- # improve its float32/float64 residual. Halving fy here makes the five-step error exceed that tolerance.- # The first assertion is the non-triviality guard: the five-step answer is OUTSIDE the tolerance that- # assert_close would use on these points, so the strict decrease below is not a decrease between three- # already-converged answers.- # Snippet used to generate expected: (undistort_points(distort_points(pts, K, d), K, d, num_iters=n)- # - pts).abs().max() for n in (5, 10, 50), executed 2026-09-06 on commit c0b50ad7 (torch 2.14.0),- # differenced in the working dtype -> cpu float64 1.355131e-02, 2.410766e-05, 1.421085e-14; cpu float32- # 1.355362e-02, 3.051758e-05, 1.907349e-06; mps float32 the same three float32 values. float32 has- # reached its own rounding floor by 50 steps while float64 is still closing, which is the scoping the- # Convention block states. The forward map displaces these points by 7.306 px, so an identity- # undistort_points would not pass. In float16 and bfloat16 the residual is pinned at the dtype's own- # quantum from the first step (1.5625e-02 and 0.5), so the three counts are indistinguishable there and- # those cells are skipped.+ # Inside the convergence region, more iterations shrink the residual. Halving fy puts the five-step+ # answer outside assert_close's tolerance, so the decrease is not between already-converged answers.if dtype not in (torch.float32, torch.float64):pytest.skip("half precision quantizes the residual, so the three step counts are indistinguishable")points = torch.tensor([[[54.0, 53.0], [-16.0, 23.0]]], device=device, dtype=dtype)@@ -433,8 +382,9 @@ class TestUndistortPoints(BaseTester):self.assert_close(undistort_points(distorted, K, dist, num_iters=50), points)def test_wart_fixed_point_cycles_outside_valid_radius_4285(self, device, dtype):- # The iteration alternates between two inaccurate values; a larger even count is worse- # than an odd count, rather than the residual increasing monotonically. Delete after #4285.+ # Wart pin for #4285: outside the valid radius the fixed-point iteration silently alternates between two+ # inaccurate values (odd and even counts agree, even is worse) instead of converging or reporting it.+ # Delete when #4285 is repaired.if dtype not in (torch.float32, torch.float64):pytest.skip("probe requires float32/float64 to avoid half-precision overflow")points = torch.tensor([[[304.0, 3.0]]], device=device, dtype=dtype)@@ -572,37 +522,20 @@ class TestUndistortImage(BaseTester):imu = undistort_image(im / 255.0, K, dist)self.assert_close(imu, imu_expected / 255.0, rtol=1e-2, atol=1e-2)- def test_convention_zero_coefficients_are_close_but_not_byte_identical(self, device, dtype):- # Convention pin: with every coefficient zero the- # DISTORTION MAP is exact -- distort_points reproduces the pixel grid bit for bit (Y3-03: 0.0) -- but- # undistort_image still routes the image through remap's bilinear sampler, so the returned image is NOT- # byte-identical to the input; it is only equal within the dtype tolerance. This refutes the plausible- # "zero coefficients give back the same image" reading, and it is why the pin uses assert_close where the- # point-level pin in test_distort.py uses torch.equal. No residual bound is asserted.- # Snippet used to generate expected: (torch.equal(undistort_image(img, K, zeros(1, 4)), img),- # (undistort_image(...) - img).abs().max()) executed 2026-09-06 on commit c0b50ad7 (torch 2.14.0)- # -> cpu float32 (False, 1.19e-07), float64 (False, 2.09e-16), float16 (False, 9.19e-04), bfloat16- # (False, 7.81e-03); mps float32 (False, 1.19e-07), float16 (False, 1.84e-03). Only the mps float16 cell- # exceeds its atol, so the skip is conditioned on the device and the cpu float16 leg still runs.+ def test_convention_zero_coefficients_are_a_no_op_to_tolerance(self, device, dtype):+ # With every coefficient zero the image still goes through remap's bilinear sampler, so it comes back+ # equal to the input within the dtype tolerance.if dtype == torch.float16 and device.type == "mps":- pytest.skip("mps float16 only: the remap round trip leaves a 1.84e-03 residual, outside the atol")+ pytest.skip("mps float16: the remap round trip residual exceeds the float16 atol")image = _ramp_image(1, 3, 5, 7, device, dtype)K = _k_short_focal(device, dtype)out = undistort_image(image, K, torch.zeros(1, 4, device=device, dtype=dtype))- assert not torch.equal(out, image)self.assert_close(out, image)def test_convention_accepts_both_batch_conventions(self, device, dtype):- # Convention pin: undistort_image accepts the batched form- # (B, C, H, W) + (B, 3, 3) + (B, n) AND the legacy unbatched form (1, C, H, W) + (3, 3) + (n,), which the- # source keeps "to avoid a breaking change". The legacy relaxation is special-cased to B = 1 only: the- # same unbatched K and dist with a B = 2 image raise ValueError rather than broadcasting. The batch is- # built from the SAME image repeated twice with different intrinsics (fx 3/5, fy 2/4, cx 3/2, cy 2/1) and- # different coefficients, so the two output rows can only differ if each element used its own K and dist.- # Snippet used to generate expected: shapes from undistort_image on each form, plus- # (out[0] - out[1]).abs().max(), executed 2026-09-06 on commit c0b50ad7 (torch 2.14.0) ->- # (2, 3, 5, 7), (1, 3, 5, 7), ValueError("Input shape is invalid. Input batch dimensions should match."),- # and a row-to-row difference of 0.284 (cpu float32) / 0.283 (mps float32) on an image in [0, 1).+ # Batched (B, C, H, W) + (B, 3, 3) + (B, n) and the legacy unbatched (1, C, H, W) + (3, 3) + (n,) are both+ # accepted; the legacy form is B = 1 only (a B = 2 image with an unbatched K raises, no broadcasting).+ # The same image with two different K and dist must give two different rows.dist = torch.tensor([[0.1, 0.01, 0.001, 0.001]], device=device, dtype=dtype)K = _k_short_focal(device, dtype)K_batch = torch.cat([K, _k_short_focal(device, dtype, fx=5.0, fy=4.0, cx=2.0, cy=1.0)])@@ -617,18 +550,9 @@ class TestUndistortImage(BaseTester):undistort_image(torch.cat([image, image]), K[0], dist[0])def test_convention_resamples_with_align_corners_true(self, device, dtype):- # Convention pin: undistort_image is exactly- # ``remap(image, mapx, mapy, align_corners=True)`` over the map that distort_points produces on the- # create_meshgrid pixel grid -- the align_corners choice is BAKED IN and the function exposes no way to- # change it (a documented window item; the same baked flag appears in warp_frame_depth and DepthWarper).- # The align_corners=False arm is asserted to DIFFER on the same map, so the pin discriminates rather than- # passing for both settings; the coefficients are non-trivial for the same reason.- # Snippet used to generate expected: torch.equal(undistort_image(img, K, dist), remap(img, mapx, mapy,- # align_corners=True)) executed 2026-09-06 on commit c0b50ad7 (torch 2.14.0) -> True on cpu for- # float32/float64/float16/bfloat16 and on mps for float32/float16; the align_corners=False output is- # visibly different on every one of those cells, which the pin asserts without a bound. On this- # short-focal camera the map deviates from the pixel grid by 0.738 px and the undistorted image differs- # from the input by 0.652 (cpu float32), so the pin is not comparing two copies of an unresampled image.+ # undistort_image is remap(image, mapx, mapy, align_corners=True) over the map distort_points produces+ # on the create_meshgrid pixel grid; align_corners is fixed and not exposed. The align_corners=False arm+ # must differ, so the pin discriminates between the two settings.image = _ramp_image(1, 3, 5, 7, device, dtype)K = _k_short_focal(device, dtype)dist = torch.tensor([[0.1, 0.01, 0.001, 0.001]], device=device, dtype=dtype)diff --git a/tests/geometry/camera/test_distortion.py b/tests/geometry/camera/test_distortion.pyindex 1be97b978..97a6c7e82 100644--- a/tests/geometry/camera/test_distortion.py+++ b/tests/geometry/camera/test_distortion.py@@ -135,14 +135,8 @@ class TestDistortionAffine(BaseTester):self._test_jit_undistort(device, dtype)def test_convention_distort_points_affine_takes_normalized_z1_points(self, device, dtype):- # Convention pin: distort_points_affine consumes points on the z = 1- # NORMALIZED plane and a flat ``[fx, fy, cx, cy]`` parameter vector -- it is the pinhole projection, not a- # pixel-to-pixel map. (0.5, 0.25) with fx = fy = 100, cx = 4, cy = 3 therefore lands on- # u = 100 * 0.5 + 4 = 54, v = 100 * 0.25 + 3 = 28. cx != cy and x != y, so a transposed reading of either- # the point or the parameter vector changes both literals; the batched row uses a second, differently- # scaled camera (fx = 200, fy = 50, cx = 6, cy = 2) so a broadcast of element 0 fails too.- # Snippet used to generate expected: distort_points_affine(tensor([0.5, 0.25]), tensor([100., 100., 4., 3.]))- # executed 2026-09-06 at c0b50ad7 (torch 2.14.0, cpu and mps, every dtype) -> [54., 28.].+ # Input is a normalized z = 1 point and a flat [fx, fy, cx, cy]: (0.5, 0.25) -> (100*0.5 + 4, 100*0.25 + 3)+ # = (54, 28). The second batch row uses a different camera so a broadcast of element 0 fails.points = torch.tensor([0.5, 0.25], device=device, dtype=dtype)params = torch.tensor([100.0, 100.0, 4.0, 3.0], device=device, dtype=dtype)self.assert_close(distort_points_affine(points, params), torch.tensor([54.0, 28.0], device=device, dtype=dtype))@@ -153,30 +147,17 @@ class TestDistortionAffine(BaseTester):torch.tensor([[54.0, 28.0], [206.0, 52.0]], device=device, dtype=dtype),)- def test_convention_undistort_points_affine_is_the_exact_inverse(self, device, dtype):- # Convention pin: undistort_points_affine((u, v), params) is the exact inverse of- # distort_points_affine -- pixel in, normalized z = 1 point out -- and the round trip recovers the input- # bit for bit on this asymmetric camera (atol = rtol = 0). The pair is a genuine forward/inverse duo; the- # Kannala-Brandt twin below is iterative and closes only to a tolerance.- # Snippet used to generate expected: torch.equal(undistort_points_affine(distort_points_affine(p, par), par), p)- # executed 2026-09-06 at c0b50ad7 (torch 2.14.0) -> True on cpu for float32/float64/float16/- # bfloat16 and on mps for float32/float16; recovered value [0.5, 0.25].+ def test_convention_undistort_points_affine_is_the_closed_form_inverse(self, device, dtype):+ # undistort_points_affine (pixel in, normalized z = 1 point out) inverts distort_points_affine in closed+ # form, with no iteration; the Kannala-Brandt pair below is iterative.points = torch.tensor([0.5, 0.25], device=device, dtype=dtype)params = torch.tensor([100.0, 100.0, 4.0, 3.0], device=device, dtype=dtype)distorted = distort_points_affine(points, params)- self.assert_close(undistort_points_affine(distorted, params), points, atol=0.0, rtol=0.0)+ self.assert_close(undistort_points_affine(distorted, params), points)def test_convention_dx_distort_points_affine_matches_autograd(self, device, dtype):- # Convention pin: dx_distort_points_affine returns the (2, 2)- # Jacobian of distort_points_affine with respect to the POINT (rows = output components, columns = input- # components), byte-identical to torch.autograd.functional.jacobian, and constant in the point because the- # map is affine -- diag(fx, fy) = diag(100, 100). This is the control probe for the Kannala-Brandt- # Jacobian pinned in TestDistortionKannalaBrandt below, which now also matches the Jacobian of- # distort_points_kannala_brandt (kornia#4277, kornia#4368).- # Snippet used to generate expected: torch.equal(dx_distort_points_affine(p, par),- # torch.autograd.functional.jacobian(lambda q: distort_points_affine(q, par), p)) executed 2026-09-06 on- # c0b50ad7 (torch 2.14.0) -> True on cpu (float32/float64/float16/bfloat16) and on mps- # (float32/float16); value [[100., 0.], [0., 100.]].+ # The (2, 2) Jacobian with respect to the point (rows = outputs, columns = inputs) is diag(fx, fy) and+ # matches autograd.points = torch.tensor([0.5, 0.25], device=device, dtype=dtype)params = torch.tensor([100.0, 100.0, 4.0, 3.0], device=device, dtype=dtype)analytic = dx_distort_points_affine(points, params)@@ -308,46 +289,24 @@ class TestDistortionKannalaBrandt(BaseTester):self._test_jit_distort(device, dtype)self._test_jit_undistort(device, dtype)- def test_convention_undistort_points_kannala_brandt_round_trip_closes(self, device, dtype):- # Convention pin: unlike the affine pair in- # TestDistortionAffine, undistort_points_kannala_brandt is an ITERATIVE inverse (10 Gauss-Newton steps),- # so the round trip closes to the dtype tolerance rather than bit for bit. The pin asserts closure at- # assert_close's dtype tolerance and deliberately states no error bound; the executed residuals are- # recorded, not enforced. The far-off-axis case is the sibling pin below.- # Snippet used to generate expected: (undistort_points_kannala_brandt(distort_points_kannala_brandt(p, par),- # par) - p).abs().max(), differenced in the working dtype. Removing the additive radial-rescale epsilon- # makes the float64 residual reach the Gauss-Newton rounding floor instead of stopping around 1e-8.+ def test_convention_undistort_points_kannala_brandt_round_trip_closes_4308(self, device, dtype):+ # undistort_points_kannala_brandt is an iterative (Gauss-Newton) inverse, so the round trip closes to the+ # dtype tolerance, including at a normalized radius of 3 where the polynomial is far from linear (the+ # fixed-point undistort_points does not, #4285). In float64 nonzero radii are rescaled by r itself, so the+ # residual reaches the rounding floor rather than an additive-epsilon bias of ~1e-8 (#4308).params = torch.tensor([100.0, 100.0, 4.0, 3.0, 0.1, 0.01, 0.001, 0.0001], device=device, dtype=dtype)- points = torch.tensor([0.5, 0.25], device=device, dtype=dtype)- self.assert_close(- undistort_points_kannala_brandt(distort_points_kannala_brandt(points, params), params), points- )-- def test_convention_undistort_points_kannala_brandt_closes_far_off_axis(self, device, dtype):- # Convention pin: the Gauss-Newton inverse still closes at a normalized radius of- # 3 focal lengths, where the fish-eye polynomial is far from linear -- the fixed-point iteration in- # kornia.geometry.calibration.undistort_points does NOT (kornia#4285). Closure is asserted at- # assert_close's dtype tolerance, with no error bound.- # Snippet used to generate expected: (undistort_points_kannala_brandt(distort_points_kannala_brandt(- # tensor([3., 0.]), par), par) - tensor([3., 0.])).abs().max(), differenced in the working dtype. The- # float64 result now reaches the rounding floor because the final rescale divides by r rather than r + 1e-8.+ points = torch.tensor([[0.5, 0.25], [3.0, 0.0], [0.01, 0.0]], device=device, dtype=dtype)if dtype == torch.bfloat16:- pytest.skip("bfloat16: the far-off-axis round trip closes only to 6.25e-02, outside the bfloat16 atol")- params = torch.tensor([100.0, 100.0, 4.0, 3.0, 0.1, 0.01, 0.001, 0.0001], device=device, dtype=dtype)- far = torch.tensor([3.0, 0.0], device=device, dtype=dtype)- self.assert_close(undistort_points_kannala_brandt(distort_points_kannala_brandt(far, params), params), far)+ points = points[[0, 2]] # the far-off-axis point closes only to about 6e-02 in bfloat16+ recovered = undistort_points_kannala_brandt(distort_points_kannala_brandt(points, params), params)+ self.assert_close(recovered, points)+ if dtype == torch.float64:+ assert (recovered - points).abs().max().item() < 1e-12def test_convention_principal_point_undistorts_to_the_origin(self, device, dtype):- # Convention pin: an exact zero distorted radius is handled structurally, so the principal point (cx, cy)- # undistorts to the EXACT origin without relying on a dtype-dependent epsilon. The assertion is torch.equal,- # not assert_close, because the masked zero-radius path is exact rather than approximate.- # cx != cy in these params, so the principal point is off the diagonal and a cx/cy swap would move it.- # The second, off-centre point is what keeps the pin from being frame-invariant: (54, 28) normalizes to- # (0.5, 0.25) and undistorts to a value that changes under either swap -- the same params with cx and cy- # exchanged give [0.5507686734199524, 0.2591852843761444] and with fy halved to 50 they give- # [0.5658687353134155, 0.5658687353134155].- # The body computes in params.dtype and casts back to the points dtype, including the mixed float16-points /- # float32-params case pinned below.+ # A zero distorted radius is masked, so the principal point undistorts to the exact origin, also with+ # float16 points and float32 params (the result keeps the points dtype). The off-centre point changes+ # under a cx/cy or fx/fy swap, so the pin is not frame-invariant.params = torch.tensor([100.0, 100.0, 4.0, 3.0, 0.1, 0.01, 0.001, 0.0001], device=device, dtype=dtype)principal_point = torch.tensor([4.0, 3.0], device=device, dtype=dtype)undistorted = undistort_points_kannala_brandt(principal_point, params)@@ -391,17 +350,6 @@ class TestDistortionKannalaBrandt(BaseTester):self.assert_close(point_jacobian, expected_point_jacobian)self.assert_close(params_jacobian, expected_params_jacobian)- def test_convention_float64_round_trip_precision_4308(self, device, dtype):- # Regression for kornia#4308: nonzero radii must be rescaled by r itself. An additive 1e-8 denominator- # guard biases these representative float64 round trips by about 1e-8, well above the dtype's rounding floor.- if dtype != torch.float64:- pytest.skip("float64-only precision regression")- params = torch.tensor([100.0, 100.0, 4.0, 3.0, 0.1, 0.01, 0.001, 0.0001], device=device, dtype=dtype)- points = torch.tensor([[0.5, 0.25], [3.0, 0.0], [0.01, 0.0]], device=device, dtype=dtype)- distorted = distort_points_kannala_brandt(points, params)- residual = (undistort_points_kannala_brandt(distorted, params) - points).abs().max().item()- assert residual < 1e-12-def test_dx_distort_points_kannala_brandt_affine_branch(self, device, dtype) -> None:# The forward distortion switches to the affine model when radius_sq <= 1e-8.# Its Jacobian must therefore be diag(fx, fy), including exactly at the origin.diff --git a/tests/geometry/camera/test_perspective.py b/tests/geometry/camera/test_perspective.pyindex efe47606e..64b7d2ec2 100644--- a/tests/geometry/camera/test_perspective.py+++ b/tests/geometry/camera/test_perspective.py@@ -67,14 +67,9 @@ class TestProjectPoints(BaseTester):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.+ # Wart pin for #4267: the masked |z| <= 1e-8 divide skips the divide and K is applied after it, so a point+ # on the camera plane projects to (fx*x + cx, fy*y + cy) = (104, 203); a point behind the camera projects+ # silently too. 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)@@ -87,18 +82,10 @@ class TestProjectPoints(BaseTester):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.+ # Integer pixel centres: create_meshgrid enumerates (0, 0) .. (W - 1, H - 1), so a centred image has+ # cx = (W - 1) / 2, cy = (H - 1) / 2 (not the half-pixel W / 2, H / 2). H = 2 != W = 3; under cx = 1,+ # cy = 0.5 the first and last pixels unproject to negatives of each other and the optical axis lands on+ # the principal point. Every literal is dyadic, 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)@@ -189,12 +176,8 @@ class TestUnprojectPoints(BaseTester):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]].+ # depth is the camera-frame z by default ((29, 53) at depth 2 -> (0.5, 1, 2)); with normalize=True it is+ # the ray length, so the result has norm 2 and z < 2. The pixel is off the principal point on purpose.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)diff --git a/tests/geometry/camera/test_pinhole.py b/tests/geometry/camera/test_pinhole.pyindex af013e4e8..96dddef49 100644--- a/tests/geometry/camera/test_pinhole.py+++ b/tests/geometry/camera/test_pinhole.py@@ -166,13 +166,8 @@ 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.+ # Wart pin for #4267: cam2pixel divides by z + 1e-12, so (1, 2, 0) gives a finite 1e14-scale pixel (inf in+ # float16) and the epsilon biases every result below z ~ 1e-10. 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:@@ -682,12 +677,9 @@ class TestPinholeCamera(BaseTester):assert pinhole.device() == intrinsics.devicedef 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.]].+ # project() computes K (R X + t): the extrinsics map world points into the camera frame (OpenCV / COLMAP).+ # With R = I, t = (1, 0, 0), the world point (1, 2, 4) is (2, 2, 4) in the camera and projects to+ # (100*2/4 + 4, 100*2/4 + 3) = (54, 53); a camera-to-world reading gives (4, 53).cam = kornia.geometry.camera.PinholeCamera(_k44(device, dtype),_e44(device, dtype, tx=1.0),@@ -698,12 +690,8 @@ class TestPinholeCamera(BaseTester):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.+ # unproject(uv, depth) returns the world point (inverse of K @ E), with depth the camera-frame z. With the+ # tx = 1 extrinsics above, a camera-frame result (2, 2, 4) fails.cam = kornia.geometry.camera.PinholeCamera(_k44(device, dtype),_e44(device, dtype, tx=1.0),@@ -715,10 +703,7 @@ class TestPinholeCamera(BaseTester):self.assert_close(back, X)def test_convention_clone_is_a_deep_copy(self, device, dtype):- # Convention pin: clone() returns a new object with independent parameter storage, and mutating the clone- # leaves the source untouched. Constructor inputs and scale() results are independently owned as well.- # 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].+ # clone() returns a camera with independent storage; mutating the clone leaves the source untouched.cam = kornia.geometry.camera.PinholeCamera(_k44(device, dtype),_e44(device, dtype, tx=2.0),@@ -735,15 +720,9 @@ class TestPinholeCamera(BaseTester):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)")+ def test_convention_intrinsics_inverse_inverts_intrinsics(self, device, dtype):+ # intrinsics_inverse() is the inverse of the full 4x4 intrinsics (the pair DepthWarper feeds pixel2cam),+ # checked on an asymmetric fx = 100, fy = 50, cx = 4, cy = 3.cam = kornia.geometry.camera.PinholeCamera(_k44(device, dtype, fy=50.0),_e44(device, dtype, tx=1.0),@@ -751,15 +730,11 @@ class TestPinholeCamera(BaseTester):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)+ self.assert_close(product, torch.eye(4, device=device, dtype=dtype)[None])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.+ # Wart pin for #4263: scale(s) gives cx' = s * cx (2.0 for cx = 4, s = 0.5), the half-pixel rule, while+ # kornia's integer pixel centres give cx' = s * cx + (s - 1) / 2 = 1.75. Delete when #4263 is repaired.cam = kornia.geometry.camera.PinholeCamera(_k44(device, dtype),_e44(device, dtype, tx=1.0),@@ -941,13 +916,9 @@ class TestPinholeCamera(BaseTester):)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.+ # Wart pin for #4267: PinholeCamera.project and project_points agree away from z = 0 but apply K on+ # opposite sides of the masked |z| <= 1e-8 divide, so at z = 0 they return [100, 200] and [104, 203].+ # The divergence is the defect, not either value. Delete when #4267 is repaired.cam = kornia.geometry.camera.PinholeCamera(_k44(device, dtype),_e44(device, dtype),@@ -968,6 +939,28 @@ class TestPinholeCamera(BaseTester):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_wart_unproject_fails_on_zero_padded_intrinsics_4771(self, device, dtype):+ # Wart pin for #4771: a 3x3 K zero-padded to 4x4 ([3, 3] = 0) constructs and projects correctly, but+ # unproject inverts the singular intrinsics @ extrinsics and raises. Delete or invert when #4771 is+ # repaired (constructor validation or a 3x3-block unproject both fail this pin). The control sets+ # [3, 3] = 1 and changes nothing else, so the raise is attributable to the zero pad.+ height, width = torch.tensor([6], device=device), torch.tensor([8], device=device)+ point = torch.tensor([[1.0, 2.0, 4.0]], device=device, dtype=dtype)+ depth = torch.tensor([[4.0]], device=device, dtype=dtype)+ K = torch.zeros(1, 4, 4, device=device, dtype=dtype)+ K[:, :3, :3] = _k44(device, dtype)[:, :3, :3]+ cam = kornia.geometry.camera.PinholeCamera(K, _e44(device, dtype), height, width)+ uv = cam.project(point)+ self.assert_close(uv, torch.tensor([[29.0, 53.0]], device=device, dtype=dtype))+ control = K.clone()+ control[:, 3, 3] = 1.0+ self.assert_close(+ kornia.geometry.camera.PinholeCamera(control, _e44(device, dtype), height, width).unproject(uv, depth),+ point,+ )+ with pytest.raises(RuntimeError):+ cam.unproject(uv, depth)+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)@@ -1010,21 +1003,14 @@ class TestPinholeMatrix(BaseTester):)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.+ # Wart pin for #4268: pinhole_matrix adds its default eps = 1e-06 to the whole identity, so every entry is+ # perturbed ([0, 0, 1] = 1e-06, [0, 3, 3] = 1.000001); eps=0.0 gives the exact matrix. The legacy pair is+ # therefore never an exact inverse, and a (1, 4, 4) input raises a bare AssertionError, not a ShapeError.+ # 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)")+ pytest.skip("half precision cannot hold 1 + 1e-06")vec = self._vec12(device, dtype)matrix = pinhole_matrix(vec)- assert matrix[0, 0, 1].item() != 0.0- assert matrix[0, 3, 3].item() != 1.0self.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)@@ -1032,17 +1018,12 @@ class TestPinholeMatrix(BaseTester):assert exact[0, 3, 3].item() == 1.0residual = (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\]\)"):+ with pytest.raises(AssertionError):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.+ # Wart pin for #4283: get_optical_pose_base and homography_i_H_ref are documented but always raise+ # NotImplementedError. Delete when #4283 is repaired.vec = self._vec12(device, dtype)with pytest.raises(NotImplementedError):get_optical_pose_base(vec)diff --git a/tests/geometry/camera/test_projections.py b/tests/geometry/camera/test_projections.pyindex 75c494e6b..21eadebe3 100644--- a/tests/geometry/camera/test_projections.py+++ b/tests/geometry/camera/test_projections.py@@ -173,26 +173,19 @@ 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]].+ def test_wart_project_points_z1_zero_depth_is_not_finite_4267(self, device, dtype):+ # Wart pin for #4267: project_points_z1 divides by z with no guard, so z = 0 gives inf or nan in every+ # component, where project_points masks the divide. Delete when #4267 is repaired.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.+ assert not bool(torch.isfinite(project_points_z1(points)).any())++ def test_wart_project_points_z1_differs_below_perspective_epsilon_4267(self, device, dtype):+ # kornia#4267: project_points_z1 divides plainly ([[1e9, 2e9]]) while project_points skips the divide when+ # abs(z) <= 1e-8 ([[1., 2.]]); the decided rule makes both skip it.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)@@ -203,13 +196,8 @@ class TestProjectionZ1(BaseTester):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.+ # The (..., 2, 3) Jacobian d(u, v) / d(x, y, z), rows indexed by the output; checked against autograd at+ # an off-axis point where all six entries differ.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)@@ -279,17 +267,8 @@ class TestProjectionOrthographic(BaseTester):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.+ # dx_project_points_orthographic returns the scalar du/dx = 1 with shape (..., 1), not the (2, 3)+ # Jacobian that its z1 sibling dx_project_points_z1 returns. Every literal is dyadic, so exact.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,)@@ -346,12 +325,7 @@ class TestProjectionOrthographic(BaseTester):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.+ # Projection drops z and keeps (x, y) in order; unprojection appends the extension as z.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)@@ -359,12 +333,7 @@ class TestProjectionOrthographic(BaseTester):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.+ # A (N,) and a (N, 1) extension are both accepted for N > 1 and give the same answer.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))diff --git a/tests/geometry/camera/test_stereo.py b/tests/geometry/camera/test_stereo.pyindex b5ca6e91e..14ede7483 100644--- a/tests/geometry/camera/test_stereo.py+++ b/tests/geometry/camera/test_stereo.py@@ -375,19 +375,9 @@ class TestStereoCamera(BaseTester):return StereoCamera(left, right)def test_convention_reproject_disparity_takes_bhw1(self, device, dtype):- # Convention pin: the disparity map is- # channels-LAST, (B, H, W, 1), for both the method and the module-level function, and the returned point- # cloud is (B, H, W, 3). The channels-FIRST (B, 1, H, W) layout that the rest of kornia uses for images- # is rejected, and so is an unbatched (B, H, W). The method's docstring used to say (B, 1, H, W) -- the- # layout the shared guard rejects -- and now says (B, H, W, 1), matching the module-level function and- # the private guard's own docstring. The message names the required layout and the last-dimension- # channel check (regression for kornia#4374).- # The shape claim carries a value so it cannot pass on a dummy: with fx = 100 and tx = 0.5, a disparity- # of 10 puts every point at Z = fx * tx / d = 5.- # Snippet used to generate expected: cam.reproject_disparity_to_3D(full((1, 3, 5, 1), 10.0)) executed- # recorded in original commit 1a96bfd1 (torch 2.14.0) -> shape (1, 3, 5, 3) with Z = 5.0,- # and StereoException for the (1, 1, 3, 5) and (1, 3, 5) layouts, on cpu for float32, float64,- # float16 and bfloat16 and on mps for float32 and float16.+ # The disparity map is channels-last (B, H, W, 1) for the method and the module-level function, and the+ # cloud is (B, H, W, 3); (B, 1, H, W) and (B, H, W) are rejected with a message naming the layout+ # (#4374). With fx = 100 and tx = 0.5, a disparity of 10 puts every point at Z = fx * tx / d = 5.cam = self._asymmetric_stereo(device, dtype)disparity = torch.full((1, 3, 5, 1), 10.0, device=device, dtype=dtype)points = cam.reproject_disparity_to_3D(disparity)@@ -399,14 +389,8 @@ class TestStereoCamera(BaseTester):cam.reproject_disparity_to_3D(torch.full((1, 3, 5), 10.0, device=device, dtype=dtype))def test_convention_reproject_method_and_free_function_are_byte_identical(self, device, dtype):- # Convention pin: the method is- # a thin forwarder -- it passes ``self.Q`` to the module-level function and returns its result bit for- # bit. ``Q`` is the cached tensor, not a fresh one, so the two calls see the same matrix. The result is- # not a degenerate all-zero cloud (it reaches 5.0), so the equality is not the trivial one.- # Snippet used to generate expected: torch.equal(cam.reproject_disparity_to_3D(d),- # reproject_disparity_to_3D(d, cam.Q)) and cam.Q is cam._Q_matrix recorded in original commit 1a96bfd1- # (torch 2.14.0) -> True and True on cpu for float32, float64, float16 and bfloat16 and on mps for- # float32 and float16.+ # The method forwards the cached self.Q to the module-level function. The cloud is not all zero, so the+ # equality is not the trivial one.cam = self._asymmetric_stereo(device, dtype)disparity = torch.full((1, 3, 5, 1), 10.0, device=device, dtype=dtype)assert torch.equal(cam.reproject_disparity_to_3D(disparity), reproject_disparity_to_3D(disparity, cam.Q))@@ -414,18 +398,9 @@ class TestStereoCamera(BaseTester):assert cam.reproject_disparity_to_3D(disparity).abs().max().item() > 0.1def test_convention_tx_is_the_right_translation_over_fx_and_fixes_q(self, device, dtype):- # Convention pin: the baseline is read off the- # right camera's last column, tx = -P_right[0, 3] / fx, and Q is built from it. Note which focal length- # sits in which row: Q[0, 0] = fy * (-tx) and Q[1, 1] = fx * (-tx), i.e. the row that scales the FIRST- # output coordinate carries fy. The fy = 50 arm varies exactly that one intrinsic and moves Q by 2500,- # so a reading in which Q[0, 0] carried fx would fail here while passing on the fx = fy camera.- # Q[3, 3] = fy * (cx_left - cx_right) is always 0, because the constructor rejects differing principal- # points outright (pinned as a wart below).- # Snippet used to generate expected, recorded in original commit 1a96bfd1 (torch 2.14.0) ->- # [[[-50, 0, 0, 200], [0, -50, 0, 150], [0, 0, 0, -5000], [0, 0, -100, 0]]] for fy = 100 and- # [[[-25, 0, 0, 100], [0, -50, 0, 150], [0, 0, 0, -2500], [0, 0, -50, 0]]] for fy = 50, on cpu for- # float32, float64, float16 and bfloat16 and on mps for float32 and float16 (bfloat16 rounds the -5000- # and -2500 entries to -4992 and -2496, hence the dtype tolerance rather than an exact comparison).+ # tx = -P_right[0, 3] / fx, and Q is built from it with Q[0, 0] = fy * (-tx), Q[1, 1] = fx * (-tx): the+ # row that scales the first output coordinate carries fy, so the fy = 50 arm fails a reading with fx+ # there. Q[3, 3] = fy * (cx_left - cx_right) is always 0 (#4270, below).cam = self._asymmetric_stereo(device, dtype)self.assert_close(cam.tx, torch.tensor([0.5], device=device, dtype=dtype))self.assert_close(cam.tx, -cam.rectified_right_camera[..., 0, 3] / cam.fx)@@ -444,40 +419,28 @@ class TestStereoCamera(BaseTester):self.assert_close(self._asymmetric_stereo(device, dtype, fy=50.0).Q, asymmetric_q)assert (symmetric_q - asymmetric_q).abs().max().item() > 1.0- def test_convention_q_signs_only_cancel_away_from_a_zero_homogeneous_coordinate(self, device, dtype):- # The homogeneous conversion divides by W only when abs(W) > 1e-8. With zero disparity, this Q gives- # W = 0, so the conversion returns the homogeneous numerator. Negating Q therefore negates the result- # instead of cancelling as it does for ordinary Euclidean points.- # The map is a single pixel (u = v = 0) on purpose: the claim is about W = 0, and a 1 x 1 map reads the- # same whichever index feeds which coordinate, so this pin survives the #4269 repair unchanged.- # Snippet used to generate expected: reproject_disparity_to_3D(zeros(1, 1, 1, 1), q) and the same call- # with -q, executed 2026-09-08 at commit 089daad9 (torch 2.14.0) -> [1, 2, 3] and its negation on cpu- # for float32, float64, float16 and bfloat16 and on mps for float32 and float16.+ def test_wart_reproject_disparity_zero_disparity_returns_the_numerator_4555(self, device, dtype):+ # kornia#4555: zero disparity (a point at infinity) gives W = 0, and the masked homogeneous divide (the+ # #4267 rule) returns the numerator as a finite placeholder -- behind the camera on a real rig, and Q and+ # -Q disagree there -- with nothing flagging it invalid. Update when #4555 adds a validity signal.+ disparity = torch.zeros(1, 1, 1, 1, device=device, dtype=dtype)+ self.assert_close(+ self._asymmetric_stereo(device, dtype).reproject_disparity_to_3D(disparity),+ torch.tensor([[[[200.0, 150.0, -5000.0]]]], device=device, dtype=dtype),+ )q = torch.tensor([[[1.0, 0.0, 0.0, 1.0], [0.0, 1.0, 0.0, 2.0], [0.0, 0.0, 0.0, 3.0], [0.0, 0.0, 1.0, 0.0]]],device=device,dtype=dtype,)- disparity = torch.zeros(1, 1, 1, 1, device=device, dtype=dtype)- points = reproject_disparity_to_3D(disparity, q)expected = torch.tensor([[[[1.0, 2.0, 3.0]]]], device=device, dtype=dtype)- self.assert_close(points, expected)+ self.assert_close(reproject_disparity_to_3D(disparity, q), expected)self.assert_close(reproject_disparity_to_3D(disparity, -q), -expected)def test_convention_reproject_disparity_uses_the_column_as_u_4269(self, device, dtype):- # The contract, repaired by #4269 and an ordinary passing regression since: u is the COLUMN index and- # v the ROW index, as in cv2.reprojectImageTo3D -- X = (u - cx) Z / fx, Y = (v - cy) Z / fy, with- # Z = fx * tx / d. On this fixture (fx = fy = 100, cx = 4, cy = 3, tx = 0.5, d = 10, so Z = 5) that is- # [-0.1, -0.15, 5] at (row 0, col 2), [-0.2, -0.1, 5] at (row 1, col 0) and [0.0, -0.05, 5] at- # (row 2, col 4). It was a strict xfail while the two indices were transposed.- cam = self._asymmetric_stereo(device, dtype)- points = cam.reproject_disparity_to_3D(torch.full((1, 3, 5, 1), 10.0, device=device, dtype=dtype))- self.assert_close(points[0, 0, 2], torch.tensor([-0.1, -0.15, 5.0], device=device, dtype=dtype))- self.assert_close(points[0, 1, 0], torch.tensor([-0.2, -0.1, 5.0], device=device, dtype=dtype))- self.assert_close(points[0, 2, 4], torch.tensor([0.0, -0.05, 5.0], device=device, dtype=dtype))- # The whole map on a camera with fx = 100 != fy = 50, so a reading that swapped the focal lengths as- # well as the indices could not reproduce it. This arm is what the deleted wart pin asserted- # transposed.+ # u is the column index and v the row index, as in cv2.reprojectImageTo3D: X = (u - cx) Z / fx,+ # Y = (v - cy) Z / fy, Z = fx * tx / d (repaired in #4269). fx = 100 != fy = 50 and H != W, so a reading+ # that swapped the indices or the focal lengths cannot reproduce the map.points = self._asymmetric_stereo(device, dtype, fy=50.0).reproject_disparity_to_3D(torch.full((1, 3, 5, 1), 10.0, device=device, dtype=dtype))@@ -486,34 +449,13 @@ class TestStereoCamera(BaseTester):depth = torch.full((3, 5), 5.0, device=device, dtype=dtype)opencv = torch.stack([(columns - 4.0) * 0.05, (rows - 3.0) * 0.1, depth], dim=-1)[None]self.assert_close(points, opencv)-- def test_convention_reproject_disparity_x_varies_with_the_column_4269(self, device, dtype):- # The axis-dependence form of the contract, and the one statement that survives any change of fixture- # because it asserts which INDEX each output coordinate depends on rather than a literal. On a constant- # disparity map X is a function of the column, so it varies along a row and is constant down a column;- # Y is the mirror image. This was a wart pin asserting the reverse while the indices were transposed.- cam = self._asymmetric_stereo(device, dtype)- points = cam.reproject_disparity_to_3D(torch.full((1, 3, 5, 1), 10.0, device=device, dtype=dtype))- # X: steps by 0.05 along a row, constant down a column.- self.assert_close(points[0, 0, :, 0], torch.tensor([-0.2, -0.15, -0.1, -0.05, 0.0], device=device, dtype=dtype))- x_down_column = points[0, :, 0, 0]- assert bool((x_down_column == x_down_column[0]).all())- # Y: constant along a row, steps by 0.05 down a column.- y_along_row = points[0, 0, :, 1]- assert bool((y_along_row == y_along_row[0]).all())- self.assert_close(points[0, :, 0, 1], torch.tensor([-0.15, -0.1, -0.05], device=device, dtype=dtype))+ # X depends only on the column and Y only on the row.+ assert bool((points[0, :, :, 0] == points[0, :1, :, 0]).all())+ assert bool((points[0, :, :, 1] == points[0, :, :1, 1]).all())def test_wart_stereo_rejects_differing_principal_points_4270(self, device, dtype):- # Wart pin for kornia#4270: the docs page says "cx may differ between- # the left and right cameras, which is taken into account here", and Q[3, 3] = fy * (cx_left -- # cx_right) exists for exactly that case -- but the constructor requires the two camera matrices to be- # equal outside the last column, so cx_left and cx_right can never differ and Q[3, 3] is always 0.- # Snippet used to generate expected: StereoCamera(left, right) with the right camera's cx set to 5.0- # recorded in original commit 1a96bfd1 (torch 2.14.0) -> StereoException("Expected- # 'left_rectified_camera' and 'rectified_right_camera' to havesame parameters except for the last- # column.") on cpu for float32, float64, float16 and bfloat16 and on mps for float32 and float16; on the- # accepted camera, cx_left == cx_right (torch.equal True) and Q[3, 3] == 0.0.- # Pins the CURRENT behavior; NOT a contract; delete when #4270 is repaired.+ # Wart pin for #4270: Q[3, 3] = fy * (cx_left - cx_right) exists for a differing cx, but the constructor+ # rejects one, so Q[3, 3] is always 0. Delete when #4270 is repaired.with pytest.raises(StereoException, match="same parameters except for the last column"):self._asymmetric_stereo(device, dtype, cx_right=5.0)cam = self._asymmetric_stereo(device, dtype)@@ -522,11 +464,8 @@ class TestStereoCamera(BaseTester):@pytest.mark.parametrize("bad_index", [0, 1])def test_convention_stereo_rejects_a_batch_with_one_positive_tx_fx_4270(self, bad_index, device, dtype):- # Convention pin for kornia#4270: the right camera's last column is -tx * fx, and the sign guard rejects a- # batch in which ANY rig has it positive, i.e. its two cameras swapped. Until the fix the guard was- # ``torch.all(torch.gt(tx * fx, 0))``, which fired only when EVERY element was positive, so a batch with one- # swapped rig was accepted and silently reprojected that rig behind the camera (its tx was -0.5). Both- # positions of the bad rig are covered, and the all-positive batch that was already rejected still is.+ # The right camera's last column is -tx * fx; a batch in which any rig has it positive (cameras swapped)+ # is rejected (#4270), whichever position the bad rig holds.left = torch.tensor([[[100.0, 0.0, 4.0, 0.0], [0.0, 100.0, 3.0, 0.0], [0.0, 0.0, 1.0, 0.0]]] * 2, device=device, dtype=dtype)@@ -545,11 +484,7 @@ class TestStereoCamera(BaseTester):@pytest.mark.parametrize("zero", [0.0, -0.0])def test_convention_stereo_rejects_a_zero_baseline_4270(self, zero, device, dtype):- # Convention pin for kornia#4270: tx * fx == 0 means coincident cameras, a rig with no baseline. It is not- # "greater than zero", so until the fix it passed the sign guard: Q collapsed to zeros except- # Q[3, 2] = -fy, and every disparity, including a large valid one, reprojected to exactly the origin with- # no warning and no inf to notice. It is now rejected with a message naming tx, both for a single rig and- # when one rig of a batch is degenerate. -0.0 is covered because it compares equal to 0.+ # tx * fx == 0 (no baseline) is rejected (#4270) for a single rig and for one rig of a batch; -0.0 too.with pytest.raises(StereoException, match="non-zero stereo baseline"):self._asymmetric_stereo(device, dtype, tx_fx=zero)diff --git a/tests/geometry/test_bbox.py b/tests/geometry/test_bbox.pyindex f358b3a01..f044105a4 100644--- a/tests/geometry/test_bbox.py+++ b/tests/geometry/test_bbox.py@@ -109,9 +109,7 @@ class TestBbox2D(BaseTester):assert validate_bbox(trapezoid) is Falsedef test_convention_validate_bbox_accepts_noncontiguous_rank4_layout_4174(self, device, dtype):- # Fix pin for kornia#4174: rank-4 input is flattened with reshape, so a stride- # layout whose leading dimensions cannot be merged by view now returns a- # boolean instead of raising RuntimeError.+ # kornia#4174: a rank-4 input whose leading dimensions cannot be merged by view returns a boolean.boxes = torch.zeros(2, 3, 4, 2, device=device, dtype=dtype).transpose(0, 1)assert not boxes.is_contiguous()assert validate_bbox(boxes) is True@@ -141,18 +139,6 @@ class TestBbox2D(BaseTester):invalid_boxes[1].reshape(-1)[coordinate_index] = non_finiteassert validate_bbox(invalid_boxes) is False- def test_convention_validate_bbox_invariance_is_exact_arithmetic_only(self, device):- # In float16 the inclusive +1 rounds distinct sub-unit spans to the same- # value, although the exclusive span difference exceeds the 1e-4 threshold.- # The True below holds only with the +1 tracked in kornia#3934.- boxes = torch.tensor(- [[[0.0, 0.0], [0.0005, 0.0], [0.001, 0.001], [0.0, 0.001]]], device=device, dtype=torch.float16- )- assert validate_bbox(boxes) is True- top_span = boxes[..., 1, 0] - boxes[..., 0, 0]- bottom_span = boxes[..., 2, 0] - boxes[..., 3, 0]- assert torch.all(torch.abs(top_span - bottom_span) > 1e-4)-def test_wart_validate_bbox_returns_false_where_validate_bbox3d_raises_4013(self, device, dtype):# Wart pin for kornia#4013: for the same invalid shape, the 2D validator# returns False while the 3D validator raises.@@ -452,11 +438,8 @@ class TestTransformBoxes2D(BaseTester):class TestBbox3D(BaseTester):def test_convention_validate_bbox3d_rejects_non_finite_coordinates_4258(self, device, dtype):- # Pin kornia#4258, the 3D counterpart of the #4238 pin on validate_bbox above: a non-finite- # coordinate makes this a False predicate result, not an AssertionError. Before the fix the- # nan reached the allclose extent comparisons, which see nan != nan and raise "Boxes must- # have be cube, while get different heights", naming the wrong defect; an inf reached them- # as inf - inf = nan with the same result.+ # kornia#4258, the 3D counterpart of #4238: a non-finite coordinate is a False predicate result, not an+ # AssertionError.boxes = torch.tensor([[@@ -484,9 +467,8 @@ class TestBbox3D(BaseTester):assert validate_bbox3d(invalid_boxes[None]) is Falsedef test_convention_consumers_still_raise_on_non_finite_coordinates_4258(self, device, dtype):- # validate_bbox3d's four internal callers use it for its raise and discard the return value,- # so turning the non-finite case into a False predicate result must not quietly let NaN- # through them. All of them raised on main and all of them still do.+ # validate_bbox3d's four internal callers use it for its raise and discard the return value, so each+ # raises on a non-finite box itself.box = torch.tensor([[@@ -511,11 +493,8 @@ class TestBbox3D(BaseTester):with pytest.raises(AssertionError, match="finite"):bbox_to_mask3d(invalid, (6, 6, 6))- # The other two callers are the src_box and dst_box of _crop_by_boxes3d_to_size, reached- # through crop_by_boxes3d and crop_and_resize3d. They need their own cells: the dst_box is- # caught earlier by infer_bbox_shape3d, but the src_box is not, because crop_by_boxes3d- # sizes its output from the *dst* box. With the crop3d guard reverted both calls below- # accept the non-finite src_box without raising, while the two cells above stay green.+ # The other two callers are the src_box and dst_box of _crop_by_boxes3d_to_size. crop_by_boxes3d sizes+ # its output from the dst box, so a non-finite src box reaches only that guard.volume = torch.arange(64, device=device, dtype=dtype).reshape(1, 1, 4, 4, 4)with pytest.raises(AssertionError, match="finite"):crop_by_boxes3d(volume, invalid, box)@@ -566,9 +545,7 @@ class TestBbox3D(BaseTester):assert validate_bbox3d(bbox)def test_convention_validate_bbox3d_accepts_noncontiguous_rank4_layout_4174(self, device, dtype):- # Fix pin for kornia#4174: rank-4 input is flattened with reshape, so a stride- # layout whose leading dimensions cannot be merged by view now returns a- # boolean instead of raising RuntimeError.+ # kornia#4174: a rank-4 input whose leading dimensions cannot be merged by view returns a boolean.boxes = torch.zeros(2, 3, 8, 3, device=device, dtype=dtype).transpose(0, 1)assert not boxes.is_contiguous()assert validate_bbox3d(boxes) is True@@ -695,13 +672,9 @@ class TestBbox3D(BaseTester):@pytest.mark.parametrize("num_boxes", [1, 8])def test_convention_rank4_input_is_rejected_by_the_3d_helpers_4248(self, device, dtype, num_boxes):- # kornia#4248, the 3D twin of kornia#4180. validate_bbox3d still accepts (B, N, 8, 3) and- # reshapes internally, but infer_bbox_shape3d and bbox_to_mask3d read dim 1 as the vertex- # axis, so rank-4 input was read as if the box axis were the vertices: out-of-bounds with- # one box, and three (1, 3) tensors -- one value per coordinate rather than per box -- with- # eight. Both now reject it up front, the way the 2D helpers have since kornia#4218.+ # kornia#4248, the 3D twin of kornia#4180: validate_bbox3d accepts (B, N, 8, 3), while infer_bbox_shape3d+ # and bbox_to_mask3d reject it with a ShapeError.boxes = self._unit_cuboid(device, dtype).expand(num_boxes, 8, 3)[None].contiguous()- # The accepting half of the mismatch is unchanged and still worth pinning.assert validate_bbox3d(boxes) is Truefor call in (lambda: infer_bbox_shape3d(boxes), lambda: bbox_to_mask3d(boxes, (4, 5, 5))):with pytest.raises(ShapeError):@@ -752,8 +725,8 @@ class TestBbox3D(BaseTester):self.assert_close(bbox_to_mask3d(boxes, (5, 5, 6)), expected, atol=0.0, rtol=0.0)def test_bbox_to_mask3d_preserves_input_dtype_4250(self, device, dtype):- # kornia#4250: bbox_to_mask3d now returns a mask in the input dtype with a (B, 1, D, H, W) channel axis,- # matching bbox_to_mask (which keeps the input dtype, no channel axis). Neither carries a gradient.+ # kornia#4250: bbox_to_mask3d returns a (B, 1, D, H, W) mask in the input dtype, like bbox_to_mask (which+ # has no channel axis). Neither carries a gradient.cuboid = self._unit_cuboid(device, dtype)mask = bbox_to_mask3d(cuboid, (4, 5, 6))assert mask.shape == (1, 1, 4, 5, 6)@@ -768,35 +741,24 @@ class TestBbox3D(BaseTester):def test_convention_bbox_to_mask3d_intersects_the_axis_ranges_for_a_full_or_overhanging_axis_box_4255(self, device, dtype, case):- # kornia#4255: once one axis slab covers every index of the (4, 4, 5) volume, the OLD- # union-of-planes intermediate went all-true and its `all()`-reduction recovery lost the- # other two bounds, filling all 80 voxels where Boxes3D.to_mask correctly fills the- # intersection. bbox_to_mask3d now matches Boxes3D.to_mask exactly, including for a box- # that overhangs the volume on one axis (the normal state of a box after a crop or a- # translation). The interior box (unaffected even before the fix) is checked alongside it.- xyzxyz_plus, intersection = {- "full_width": ([0.0, 1.0, 1.0, 4.0, 2.0, 2.0], 20.0),- "full_height": ([1.0, 0.0, 1.0, 2.0, 3.0, 2.0], 16.0),- "full_depth": ([1.0, 1.0, 0.0, 2.0, 2.0, 3.0], 16.0),- "overhang": ([-1.0, 1.0, 1.0, 5.0, 2.0, 2.0], 20.0),+ # kornia#4255: a box whose slab covers (or overhangs) a whole axis of the (4, 4, 5) volume fills the+ # intersection of the three axis ranges, exactly as Boxes3D.to_mask does. The interior box is a control.+ xyzxyz_plus, region = {+ "full_width": ([0.0, 1.0, 1.0, 4.0, 2.0, 2.0], (slice(1, 3), slice(1, 3), slice(None))),+ "full_height": ([1.0, 0.0, 1.0, 2.0, 3.0, 2.0], (slice(1, 3), slice(None), slice(1, 3))),+ "full_depth": ([1.0, 1.0, 0.0, 2.0, 2.0, 3.0], (slice(None), slice(1, 3), slice(1, 3))),+ "overhang": ([-1.0, 1.0, 1.0, 5.0, 2.0, 2.0], (slice(1, 3), slice(1, 3), slice(None))),}[case]boxes = Boxes3D.from_tensor(torch.tensor([xyzxyz_plus], device=device, dtype=dtype), mode="xyzxyz_plus")- assert bbox_to_mask3d(boxes.data, (4, 4, 5)).sum().item() == intersection- assert boxes.to_mask(4, 4, 5).sum().item() == intersection+ expected = torch.zeros(1, 1, 4, 4, 5, device=device, dtype=dtype)+ expected[(0, 0, *region)] = 1.0+ self.assert_close(bbox_to_mask3d(boxes.data, (4, 4, 5)), expected, atol=0.0, rtol=0.0)+ self.assert_close(boxes.to_mask(4, 4, 5).to(dtype), expected[:, 0], atol=0.0, rtol=0.0)interior = Boxes3D.from_tensor(torch.tensor([[1.0, 1.0, 1.0, 2.0, 2.0, 2.0]], device=device, dtype=dtype), mode="xyzxyz_plus")assert bbox_to_mask3d(interior.data, (4, 4, 5)).sum().item() == interior.to_mask(4, 4, 5).sum().item() == 8.0- def test_convention_bbox_to_mask3d_intersects_the_axis_ranges_for_a_full_axis_box_4255(self, device, dtype):- # x spans the whole width 0..4, y and z cover 1..2: the intersection is 2 * 2 * 5 = 20 voxels.- boxes = Boxes3D.from_tensor(- torch.tensor([[0.0, 1.0, 1.0, 4.0, 2.0, 2.0]], device=device, dtype=dtype), mode="xyzxyz_plus"- )- expected = torch.zeros(1, 1, 4, 4, 5, device=device, dtype=dtype)- expected[0, 0, 1:3, 1:3, :] = 1.0- self.assert_close(bbox_to_mask3d(boxes.data, (4, 4, 5)), expected, atol=0.0, rtol=0.0)-class TestNMS(BaseTester):def test_convention_nms_uses_exclusive_xyxy_iou_4008(self, device, dtype):diff --git a/tests/geometry/test_boxes.py b/tests/geometry/test_boxes.pyindex 1d62830f0..a5f4212cf 100644--- a/tests/geometry/test_boxes.py+++ b/tests/geometry/test_boxes.py@@ -61,9 +61,15 @@ class TestBoxes2D(BaseTester):with pytest.raises(ValueError, match="non-finite coordinates"):Boxes.from_tensor(invalid_source, mode=mode, validate_boxes=True)- def test_convention_from_tensor_opt_out_preserves_non_finite_input_4238(self, device, dtype):- source = torch.tensor([[0.0, 0.0, float("nan"), 4.0]], device=device, dtype=dtype)- boxes = Boxes.from_tensor(source, mode="xyxy", validate_boxes=False)+ @pytest.mark.parametrize("container", ["Boxes", "Boxes3D"])+ def test_convention_from_tensor_opt_out_preserves_non_finite_input_4238(self, container, device, dtype):+ # kornia#4238 (2D) and kornia#4258 (3D): validate_boxes=False keeps a non-finite coordinate.+ if container == "Boxes":+ source = torch.tensor([[0.0, 0.0, float("nan"), 4.0]], device=device, dtype=dtype)+ boxes = Boxes.from_tensor(source, mode="xyxy", validate_boxes=False)+ else:+ source = torch.tensor([[0.0, 0.0, 0.0, float("nan"), 4.0, 4.0]], device=device, dtype=dtype)+ boxes = Boxes3D.from_tensor(source, mode="xyzxyz", validate_boxes=False)assert torch.isnan(boxes.data).any()@pytest.mark.parametrize("mode", ["xyxy", "xyxy_plus", "xywh", "vertices", "vertices_plus"])@@ -83,32 +89,20 @@ class TestBoxes2D(BaseTester):output = Boxes.from_tensor(source, mode=mode).to_tensor(mode=mode)self.assert_close(output, source, atol=0.0, rtol=0.0)- @pytest.mark.parametrize(- ("box_dtype", "source_values", "expected_values"),- [- (torch.bfloat16, [256.0, 256.0, 258.0, 258.0], [256.0, 256.0, 256.0, 256.0]),- (torch.float16, [-385.25, 0.0, 400.0, 2.0], [-385.25, 0.0, 399.75, 2.0]),- ],- )- def test_convention_round_trip_requires_exact_intermediate_arithmetic(- self, device, box_dtype, source_values, expected_values- ):- # bfloat16 cannot represent the +/-1 intermediate at 256. The float16- # case can represent its offsets, but rounds the cross-zero width first.- # Both discrepancies exist only because of the +/-1 offsets tracked in kornia#3934.- source = torch.tensor([source_values], device=device, dtype=box_dtype)+ def test_wart_bfloat16_round_trip_rounds_the_offset_intermediate_3934(self, device):+ # kornia#3934: the xyxy round trip goes through the +/-1 inclusive offsets, which bfloat16 cannot represent+ # at 256, so [256, 256, 258, 258] comes back as [256, 256, 256, 256]; without the offsets it is exact.+ source = torch.tensor([[256.0, 256.0, 258.0, 258.0]], device=device, dtype=torch.bfloat16)output = Boxes.from_tensor(source, mode="xyxy").to_tensor("xyxy")- expected = torch.tensor([expected_values], device=device, dtype=box_dtype)+ expected = torch.tensor([[256.0, 256.0, 256.0, 256.0]], device=device, dtype=torch.bfloat16)self.assert_close(output, expected, atol=0.0, rtol=0.0)assert not torch.equal(output, source)@pytest.mark.parametrize("mode", ["xyxy", "xyxy_plus", "xywh", "vertices", "vertices_plus"])def test_wart_sub_unit_extent_round_trip_boundary_4061(self, mode, device, dtype):- # Wart pin for kornia#4061: the three converting modes place the top-right- # vertex at ``xmin + width - 1``, which lands left of the top-left vertex when- # the extent is below one unit. The stored quadrilateral is inverted on both- # axes and to_tensor recovers a larger box. 'xyxy_plus' cancels the -1,- # while 'vertices_plus' bypasses offset conversion.+ # kornia#4061: the converting modes place the top-right vertex at ``xmin + width - 1``, left of the+ # top-left vertex for a sub-unit extent, so to_tensor recovers a larger box. 'xyxy_plus' cancels the -1+ # and 'vertices_plus' bypasses the conversion.source_by_mode = {"xyxy": [0.1, 0.1, 0.6, 0.9],"xyxy_plus": [0.1, 0.1, 0.6, 0.9],@@ -126,8 +120,6 @@ class TestBoxes2D(BaseTester):source = torch.tensor([source_by_mode[mode]], device=device, dtype=dtype)expected = torch.tensor([expected_by_mode[mode]], device=device, dtype=dtype)# validate_boxes=True does not reject the input: the extents are positive.- # Half-precision converting modes use dtype-aware tolerance because their- # expected decimal results are not all exactly representable.output = Boxes.from_tensor(source, mode=mode, validate_boxes=True).to_tensor(mode=mode)self.assert_close(output, expected)@@ -139,10 +131,9 @@ class TestBoxes2D(BaseTester):self.assert_close(heights, torch.tensor([2.0], device=device, dtype=dtype), atol=0.0, rtol=0.0)self.assert_close(widths, torch.tensor([4.0], device=device, dtype=dtype), atol=0.0, rtol=0.0)- def test_convention_get_boxes_shape_includes_list_padding(self, device, dtype):- # get_boxes_shape uses the padded xywh export, so padding entries appear as- # 1-by-1 boxes even though an ordinary to_tensor export trims them. The 1-by-1- # value depends on the inclusive +1 tracked in kornia#3934.+ def test_wart_get_boxes_shape_reports_list_padding_as_one_by_one_3934(self, device, dtype):+ # kornia#3934: get_boxes_shape uses the padded xywh export, so padding entries appear as 1-by-1 boxes, the+ # inclusive +1 of a zero box, even though an ordinary to_tensor export trims them.first = torch.tensor([[[1.0, 2.0], [4.0, 2.0], [4.0, 3.0], [1.0, 3.0]]], device=device, dtype=dtype)second = torch.cat([first, first])boxes = Boxes([first, second])@@ -687,10 +678,9 @@ class TestBoxes2D(BaseTester):)def test_wart_compute_area_is_shoelace_of_inclusive_vertices_4010(self, device, dtype):- # Wart pin for kornia#4010: compute_area applies shoelace to the stored- # inclusive vertices. A valid exclusive 2-by-1 box collapses to a line,- # and a raw four-by-three rectangle has area six rather than the twelve- # reported by get_boxes_shape. These are current values, not a contract.+ # kornia#4010: compute_area applies shoelace to the stored inclusive vertices, so a valid exclusive+ # 2-by-1 box collapses to a line and a raw four-by-three rectangle has area six, not the twelve that+ # get_boxes_shape reports.two_by_one = Boxes.from_tensor(torch.tensor([[[1.0, 1.0, 3.0, 2.0]]], device=device, dtype=dtype), mode="xyxy")four_by_three = Boxes(torch.tensor([[[1.0, 1.0], [4.0, 1.0], [4.0, 3.0], [1.0, 3.0]]], device=device, dtype=dtype)@@ -827,12 +817,8 @@ class TestBoxes2D(BaseTester):def test_convention_clamp_leaves_coordinates_alone_for_a_non_finite_bound_4244(self, non_finite, bound, position, device, dtype):- # clamp is comparison-based: every comparison against a non-finite bound that is NaN is- # False, so the coordinate is left alone rather than taking the bound. maximum/minimum do- # not agree here -- they propagate the NaN into every coordinate on that axis -- which is- # why this pin exists alongside the rank fix that motivated rewriting the bound broadcast.- # An infinite bound is a real clamp on one side and a no-op on the other, so it is swept- # too, and both bound tensors and both coordinate positions are covered.+ # clamp applies the lower bound, then the upper bound, by comparison: a NaN bound leaves the coordinate+ # alone (where torch.maximum/minimum would propagate the NaN), and an infinite bound clamps on one side.data = torch.tensor([[[[1.0, 2.0], [5.0, 2.0], [5.0, 4.0], [1.0, 4.0]]]], device=device, dtype=dtype)topleft = torch.tensor([[0.0, 0.0]], device=device, dtype=dtype)botright = torch.tensor([[10.0, 10.0]], device=device, dtype=dtype)@@ -843,14 +829,8 @@ class TestBoxes2D(BaseTester):out = Boxes(data.clone()).clamp(topleft, botright, inplace=False).data- # Hand-derived from the two ordered comparison passes, lower bound first:- # topleft=nan -> `c < nan` is False, so the coordinate is left alone- # topleft=+inf -> `c < inf` raises every coordinate to +inf, which the botright pass then- # lowers to botright (10), so +inf never survives- # topleft=-inf -> `c < -inf` is False, left alone- # botright=nan -> `c > nan` is False, left alone- # botright=+inf-> `c > inf` is False, left alone- # botright=-inf-> `c > -inf` lowers every coordinate to -inf+ # topleft=+inf raises every coordinate, and the botright pass lowers it to 10; botright=-inf lowers it to+ # -inf; every other case leaves the coordinate alone.expected = data.clone()if bound == "topleft" and non_finite == float("inf"):expected[..., position] = botright[0, position]@@ -917,10 +897,9 @@ class TestBoxes2D(BaseTester):@pytest.mark.parametrize("batched", [False, True])@pytest.mark.parametrize("inplace", [False, True])- def test_wart_transform_boxes_empty_copy_aliases_input_4020(self, batched, inplace, device, dtype):- # Wart pin for tracking issue #4020: transforming an empty container- # preserves its tensor storage. The non-inplace wrapper is new but- # aliases the input data; the in-place wrapper remains self.+ def test_convention_transform_boxes_empty_container_keeps_its_tensor(self, batched, inplace, device, dtype):+ # Transforming an empty container keeps its tensor: the non-inplace wrapper is new but aliases the input+ # data, and the in-place wrapper remains self.data = torch.empty((1, 0, 4, 2) if batched else (0, 4, 2), device=device, dtype=dtype)boxes = Boxes(data)original = boxes.data@@ -1105,11 +1084,8 @@ class TestTransformBoxes2D(BaseTester):class TestBbox3D(BaseTester):@pytest.mark.parametrize("mode", ["xyzxyz", "xyzxyz_plus", "xyzwhd"])def test_convention_from_tensor_rejects_non_finite_coordinates_4258(self, mode, device, dtype):- # Pin kornia#4258, the 3D counterpart of the #4238 pin on Boxes.from_tensor: eager- # validation rejects non-finite values in both the unbatched and batched layouts, even when- # a valid row is present too. Before the fix an inf passed the positive-extent checks- # outright (inf - 0 > 0) and a nan passed them because every comparison against nan is- # False, so the box was constructed with non-finite vertices.+ # kornia#4258, the 3D counterpart of #4238: eager validation rejects non-finite values in the unbatched+ # and batched layouts, even when a valid row is present too.source = torch.tensor([[0.0, 0.0, 0.0, 4.0, 4.0, 4.0], [1.0, 1.0, 1.0, 5.0, 5.0, 5.0]], device=device, dtype=dtype)@@ -1121,11 +1097,6 @@ class TestBbox3D(BaseTester):with pytest.raises(ValueError, match="non-finite coordinates"):Boxes3D.from_tensor(invalid_source, mode=mode, validate_boxes=True)- def test_convention_from_tensor_opt_out_preserves_non_finite_input_4258(self, device, dtype):- source = torch.tensor([[0.0, 0.0, 0.0, float("nan"), 4.0, 4.0]], device=device, dtype=dtype)- boxes = Boxes3D.from_tensor(source, mode="xyzxyz", validate_boxes=False)- assert torch.isnan(boxes.data).any()-def test_smoke(self, device, dtype):def _create_tensor_box():# Sample two points of the 3d rect@@ -1533,15 +1504,11 @@ class TestBbox3D(BaseTester):self.gradcheck(lambda x: Boxes3D.from_tensor(x, mode="xyzxyz_plus").data, (t_boxes_xyzxyz,))self.gradcheck(lambda x: Boxes3D.from_tensor(x, mode="xyzwhd").data, (t_boxes_xyzxyz1,))- def test_convention_to_tensor_tie_gradient_is_an_even_subgradient_1396(self, device):- # #1396: to_tensor used to raise RuntimeError whenever its input required grad, because- # gradcheck disagreed with the analytical gradient on an axis-aligned box -- every face of- # such a box has a 4-way vertex tie, and PyTorch's amin/amax backward splits the gradient- # evenly across tied vertices (1/4 each here) rather than picking one, which is a valid- # subgradient but not what central-difference gradcheck expects at a kink (it does not probe- # a genuine derivative there, since none exists in the classical sense). This pins that even- # split as the actual, correct, and now-unguarded behavior, so a future change that alters it- # (e.g. reverting to computing to_tensor without amin/amax) has to touch this test.+ def test_convention_to_tensor_gradient_reaches_the_extremal_vertices_1396(self, device):+ # #1396: to_tensor reduces the stored vertices with amin/amax and does not reject an input that+ # requires grad. d(xmin)/d(vertices) is therefore supported on the vertices attaining the minimum, shared+ # equally among them and summing to 1: a single vertex when it is unique, a tie of four on an axis-aligned+ # face (a min(dim=...) reduction would give all of it to one vertex).vertices = torch.tensor([[@@ -1557,16 +1524,18 @@ class TestBbox3D(BaseTester):],device=device,dtype=torch.float32,- requires_grad=True,)- boxes = Boxes3D(vertices)- out = boxes.to_tensor(mode="xyzxyz") # (N=1, 6): not batched, so to_tensor squeezes the batch dim- out[0, 0].backward() # d(xmin)/d(vertices): xmin ties across vertices 0, 3, 4, 7-- expected_grad = torch.zeros_like(vertices)- for tied_vertex in (0, 3, 4, 7):- expected_grad[0, tied_vertex, 0] = 0.25- self.assert_close(vertices.grad, expected_grad)+ for tied in ((0, 3, 4, 7), (4,)):+ data = vertices.clone()+ if tied == (4,):+ data[0, 4, 0] = -1.0 # vertex 4 alone attains xmin, so a fixed-index reading is caught+ data.requires_grad_()+ Boxes3D(data).to_tensor(mode="xyzxyz")[0, 0].backward()+ outside = torch.ones_like(data, dtype=torch.bool)+ outside[0, list(tied), 0] = False+ assert bool((data.grad[outside] == 0).all())+ self.assert_close(data.grad[0, list(tied), 0].sum(), torch.tensor(1.0, device=device))+ assert data.grad[0, list(tied), 0].unique().numel() == 1@staticmethoddef _asymmetric_xyzxyz(device, dtype) -> torch.Tensor:@@ -1970,24 +1939,13 @@ class TestVideoBoxes(BaseTester):self.assert_close(transformed.to_tensor(), boxes, atol=0.0, rtol=0.0)def test_wart_indexing_drops_the_temporal_size_4249(self, device, dtype):- # Wart pin for the part of kornia#4249 that survives #4176: Boxes.__getitem__ builds the result- # with type(self)(...) and never sets temporal_channel_size, so the sliced wrapper's to_tensor- # fails. get_boxes_shape and to_mask no longer raise; that half is pinned as a convention by- # test_convention_inherited_shape_and_mask_work_on_the_temporal_wrapper_4249. The inherited- # methods keep the temporal size whether they copy or update in place;- # test_convention_inherited_methods_split_copies_from_in_place_updates pins which is which.+ # kornia#4249: Boxes.__getitem__ builds the result with type(self)(...) and never sets+ # temporal_channel_size, so the sliced wrapper's to_tensor fails. Invert when #4249 is fixed.video_boxes = VideoBoxes.from_tensor(self._sample_video_boxes(device, dtype, batch=2, time=3, n_boxes=1))frame = video_boxes[0]assert isinstance(frame, VideoBoxes)with pytest.raises(AttributeError, match="temporal_channel_size"):frame.to_tensor()- bounds = torch.zeros(6, 2, device=device, dtype=dtype)- assert video_boxes.clamp(bounds, bounds + 2.0).temporal_channel_size == 3- assert video_boxes.filter_boxes_by_area(1.0).temporal_channel_size == 3- assert video_boxes.translate(bounds + 1.0).temporal_channel_size == 3- assert video_boxes.pad(torch.ones(6, 4, device=device, dtype=dtype)).temporal_channel_size == 3- assert video_boxes.merge(video_boxes).temporal_channel_size == 3- assert video_boxes.to(dtype=torch.float32).temporal_channel_size == 3def test_convention_inherited_methods_split_copies_from_in_place_updates(self, device, dtype):# Convention pin: transform_boxes, translate, clamp, filter_boxes_by_area and merge copy throughdiff --git a/tests/geometry/test_depth.py b/tests/geometry/test_depth.pyindex e3766af86..97d16c77d 100644--- a/tests/geometry/test_depth.py+++ b/tests/geometry/test_depth.py@@ -256,20 +256,10 @@ class TestDepthTo3d(BaseTester):self.gradcheck(kornia.geometry.depth.depth_to_3d, (depth, camera_matrix))def test_convention_pixel_origin_is_the_integer_centre(self, device, dtype):- # Convention pin: pixel (0, 0) unprojects as- # ((0 - cx) d / fx, (0 - cy) d / fy, d). kornia's pixel grid puts the centre of the first pixel at the- # INTEGER coordinate 0 (the OpenCV convention that create_meshgrid already pins in- # tests/geometry/test_conversions.py), and ``depth`` here is the camera-frame z, not a ray length.- # A half-pixel (COLMAP) grid, whose first pixel centre is 0.5, would give- # ((0.5 - 4) * 2 / 100, (0.5 - 3) * 2 / 100, 2) = (-0.07, -0.05, 2) instead -- a 0.01 gap in x and y,- # far outside every dtype tolerance used here. cx = 4 != cy = 3 and H = 2 != W = 3, so a transposed- # reading of the grid also changes the literal. depth_to_3d_v2 answers the same question in the- # (B, H, W, 3) layout and gives the same triple.- # Snippet used to generate expected: depth_to_3d(full((1, 1, 2, 3), 2.0), K)[0, :, 0, 0] executed- # 2026-09-06 at commit 1a96bfd1 (torch 2.14.0) -> cpu float32 and float64- # [-0.07999999821186066, -0.05999999865889549, 2.0], cpu float16 [-0.08001708984375, -0.05999755859375,- # 2.0], cpu bfloat16 [-0.080078125, -0.06005859375, 2.0]; mps float32 and float16 reproduce their cpu- # cells exactly.+ # Pixel (0, 0) unprojects as ((0 - cx) d / fx, (0 - cy) d / fy, d): the first pixel centre is at the integer+ # coordinate 0, and ``depth`` is the camera-frame z. A half-pixel (COLMAP) grid would give (-0.07, -0.05, 2).+ # cx != cy and H != W, so a transposed grid also changes the literal.+ # Snippet used to generate expected: depth_to_3d(full((1, 1, 2, 3), 2.0), K)[0, :, 0, 0]camera_matrix = _k_asymmetric(device, dtype)depth = torch.full((1, 1, 2, 3), 2.0, device=device, dtype=dtype)expected = torch.tensor([-0.08, -0.06, 2.0], device=device, dtype=dtype)@@ -291,16 +281,8 @@ class TestDepthTo3d(BaseTester):self.assert_close(points_v2[0, 0, 0], expected)def test_convention_depth_to_3d_and_v2_agree_up_to_layout(self, device, dtype):- # Convention pin: the two functions compute the same points in two- # layouts -- (B, 3, H, W) for depth_to_3d, (B, H, W, 3) for depth_to_3d_v2 -- and are byte-identical- # after the permutation, under an asymmetric camera (fx = 100 != fy = 50, cx = 4 != cy = 3), H = 3 != W- # = 5 and a depth that varies at every pixel. The permutation is load-bearing rather than decorative:- # the two flattened buffers are NOT equal, so a comparison that skipped the permute would fail here.- # The W = 1 regression (kornia#4278) is pinned below too.- # Snippet used to generate expected: torch.equal(depth_to_3d(d, K).permute(0, 2, 3, 1),- # depth_to_3d_v2(d[:, 0], K)) and torch.equal(v1.reshape(-1), v2.reshape(-1)) on the depth ramp 1..15- # executed 2026-09-06 at commit 1a96bfd1 (torch 2.14.0) -> True and False respectively, on cpu for- # float32, float64, float16 and bfloat16 and on mps for float32 and float16.+ # The two functions compute the same points in (B, 3, H, W) and (B, H, W, 3) layouts, equal after the+ # permutation; the flattened buffers differ, so a comparison that skipped the permute would fail.camera_matrix = _k_asymmetric(device, dtype, fy=50.0)depth = torch.tensor([[[[1.0, 2.0, 3.0, 4.0, 5.0], [6.0, 7.0, 8.0, 9.0, 10.0], [11.0, 12.0, 13.0, 14.0, 15.0]]]],@@ -315,9 +297,7 @@ class TestDepthTo3d(BaseTester):assert not torch.equal(v1.reshape(-1), v2.reshape(-1))def test_convention_depth_to_3d_v2_keeps_the_w_one_axis_4278(self, device, dtype):- # Regression for #4278 (repaired by #4298): a single column retains its width axis and agrees across- # layouts. warp_frame_depth also keeps the axis. depth_to_normals requires both spatial dimensions- # to be at least 2; its separate convention pin covers that contract.+ # kornia#4278: a single column keeps its width axis and agrees across layouts; warp_frame_depth keeps it too.camera_matrix = _k_asymmetric(device, dtype)depth = torch.full((1, 1, 3, 1), 2.0, device=device, dtype=dtype)v2 = depth_to_3d_v2(depth[:, 0], camera_matrix)@@ -326,13 +306,8 @@ class TestDepthTo3d(BaseTester):assert warp_frame_depth(depth, depth, _eye4(device, dtype), camera_matrix).shape == (1, 1, 3, 1)def test_convention_xyz_grid_bypasses_the_camera_matrix(self, device, dtype):- # Convention pin: with ``xyz_grid`` given, depth_to_3d_v2 never reads ``camera_matrix`` beyond its- # (*, 3, 3) guard, so the bare (3, 3) that the no-grid call rejects inside unproject_meshgrid (#4271)- # is silently accepted here and the result is the batched call's, bit for bit.- # Snippet used to generate expected: depth_to_3d_v2(ones(1, 3, 5), K[0], xyz_grid=unproject_meshgrid(3,- # 5, K)) executed 2026-09-08 at commit 089daad9 (torch 2.14.0) -> shape (1, 3, 5, 3), torch.equal to- # depth_to_3d_v2(ones(1, 3, 5), K); depth_to_3d_v2(ones(1, 3, 5), K[0]) -> ShapeError. Every cpu dtype- # and mps float32/float16.+ # With ``xyz_grid`` given, depth_to_3d_v2 reads ``camera_matrix`` only through its (*, 3, 3) guard, so the+ # bare (3, 3) that the no-grid call rejects (#4271) is accepted and gives the batched call's result.camera_matrix = _k_asymmetric(device, dtype)depth = torch.ones(1, 3, 5, device=device, dtype=dtype)grid = unproject_meshgrid(3, 5, camera_matrix, device=device, dtype=dtype)@@ -345,17 +320,10 @@ class TestDepthTo3d(BaseTester):class TestUnprojectMeshgrid(BaseTester):def test_convention_returns_b_h_w_3_and_equals_depth_to_3d_v2_at_depth_one(self, device, dtype):- # Convention pin: unproject_meshgrid is depth_to_3d_v2's- # cache: it returns the per-pixel ray through each pixel at depth 1 in the (*, H, W, 3) layout, so- # multiplying it by a depth map reproduces depth_to_3d_v2 exactly. The grid is not constant -- pixel- # (0, 0) and pixel (1, 2) differ -- so the equality is not the trivial one.- # The asymmetric arm varies ONE intrinsic: with fy = 50 instead of 100 only the y component of the- # pixel-(1, 0) ray changes, which is what fixes fy as the divisor of the ROW index.- # Snippet used to generate expected: unproject_meshgrid(2, 3, K, device=..., dtype=...) and- # torch.equal(that, depth_to_3d_v2(ones(1, 2, 3), K)) executed 2026-09-06 at commit 1a96bfd1- # (torch 2.14.0) -> shape (1, 2, 3, 3), pixel (0, 0) [-0.03999999910593033, -0.029999999329447746, 1.0]- # and True, on cpu for float32, float64, float16 and bfloat16 and on mps for float32 and float16; with- # fy = 50, pixel (0, 0) [-0.04, -0.06, 1.0] and pixel (1, 0) [-0.04, -0.04, 1.0].+ # unproject_meshgrid is depth_to_3d_v2's cache: the per-pixel ray at depth 1 in (*, H, W, 3), so multiplying+ # it by a depth map reproduces depth_to_3d_v2. The fy = 50 arm moves only the y component of the pixel-(1, 0)+ # ray, which fixes fy as the divisor of the ROW index.+ # Snippet used to generate expected: unproject_meshgrid(2, 3, K, device=..., dtype=...)camera_matrix = _k_asymmetric(device, dtype)grid = unproject_meshgrid(2, 3, camera_matrix, device=device, dtype=dtype)assert grid.shape == (1, 2, 3, 3)@@ -508,23 +476,10 @@ class TestDepthToNormals(BaseTester):self.gradcheck(kornia.geometry.depth.depth_to_normals, (depth, camera_matrix))def test_convention_normals_point_away_from_the_camera_and_x_tracks_the_column(self, device, dtype):- # Convention pin: depth_to_normals takes- # the cross product of the spatial gradients of the unprojected point cloud in the order dx x dy, so a- # fronto-parallel plane gets the unit normal (0, 0, 1) -- +z points AWAY from the camera, along the- # viewing direction, not back towards it. The two ramps fix which axis is which: a depth that grows with- # the COLUMN tilts the normal towards -x, a depth that grows with the ROW tilts it towards -y. The- # magnitudes are dtype-dependent (float32 -0.99995, float16 -1.0), so this pin asserts the sign pattern- # with separators far from every measured value, and only the flat plane as an exact triple.- # The map is 3 x 4 with fx = 100 != fy = 50, so H != W and the two focal lengths differ: a transposed- # depth map does not even have the right shape here, and a reading that swapped fx and fy would move the- # ramp normals.- # Snippet used to generate expected: depth_to_normals(depth, K)[0, :, 1, 1] on the 3 x 4 map executed- # 2026-09-06 at commit 1a96bfd1 (torch 2.14.0) -> flat plane exactly [0.0, 0.0, 1.0] (cpu- # float32/float16/bfloat16) and [0.0, -0.0, 1.0] (cpu float64, mps float32); column ramp- # [-0.9999499917030334, 0.0, -0.009999499656260014] on cpu float32, [-1.0, 0.0, -0.0099945068359375] on- # cpu float16, [-1.0, 0.0, -0.010009765625] on cpu bfloat16 and [-0.9999499917030334, 3.49e-08,- # -0.009999497793614864] on mps float32; row ramp [0.0, -1.0, 0.0] on cpu and- # [0.0, -1.0, -4.656612873077393e-10] on mps float32.+ # depth_to_normals takes dx x dy of the unprojected point cloud, so a fronto-parallel plane gets (0, 0, 1):+ # +z points AWAY from the camera. A depth growing with the COLUMN tilts the normal towards -x, one growing+ # with the ROW towards -y. The ramp magnitudes are dtype-dependent, so only their signs are asserted.+ # Snippet used to generate expected: depth_to_normals(depth, K)[0, :, 1, 1] on the 3 x 4 mapcamera_matrix = _k_asymmetric(device, dtype, fy=50.0)flat = depth_to_normals(torch.full((1, 1, 3, 4), 2.0, device=device, dtype=dtype), camera_matrix)assert flat.shape == (1, 3, 3, 4)@@ -635,12 +590,9 @@ class TestWarpFrameDepth(BaseTester):self.assert_close(image_dst, image_dst_expected, rtol=1e-3, atol=1e-3)def test_convention_subpixel_border_blends_with_zero_padding(self, device, dtype):- # Convention pin: the baked padding_mode="zeros" is a zero EXTENSION of the image, not a mask on the- # sampling point: a quarter-pixel translation samples the last column at x = 2.25, and bilinear- # interpolation blends the in-bounds neighbour (1.0, weight 0.75) with the padded zero (weight 0.25).- # Snippet used to generate expected: warp_frame_depth(ones(1, 1, 2, 3), ones, T, eye(3)) with- # T[0, 0, 3] = 0.25, executed 2026-09-08 at commit 26ddb21e (torch 2.14.0) -> [[1, 1, 0.75], [1, 1, 0.75]]- # on cpu for float32, float64, float16 and bfloat16 and on mps for float32 and float16.+ # The baked padding_mode='zeros' extends the image with zeros: a quarter-pixel translation samples the last+ # column at x = 2.25 and blends the in-bounds 1.0 (weight 0.75) with the padded zero (weight 0.25).+ # Snippet used to generate expected: warp_frame_depth(ones(1, 1, 2, 3), ones, T, eye(3)), T[0, 0, 3] = 0.25image = torch.ones(1, 1, 2, 3, device=device, dtype=dtype)camera_matrix = torch.eye(3, device=device, dtype=dtype)[None]transform = torch.eye(4, device=device, dtype=dtype)[None]@@ -704,18 +656,11 @@ class TestWarpFrameDepth(BaseTester):self.gradcheck(kornia.geometry.depth.warp_frame_depth, (image_src, depth_dst, src_trans_dst, camera_matrix))def test_convention_src_trans_dst_moves_the_sampling_point(self, device, dtype):- # Convention pin: warp_frame_depth reads the depth in- # the DESTINATION frame and the image in the SOURCE frame, and ``src_trans_dst`` maps destination-frame- # points into the source frame. With fx = fy = 1 and depth 1, a +1 translation in x therefore samples- # image_src one pixel to the RIGHT of each destination pixel: out[u] = image_src[u + 1], and the last- # column samples outside the image, which the baked ``padding_mode="zeros"`` fills with 0.- # An identity transform is frame-invariant and proves nothing about the direction, so it is used only as- # the contrast: it returns the input byte for byte, while the +1 transform moves it by up to 19.0.- # Snippet used to generate expected: warp_frame_depth(arange(20).view(1, 1, 4, 5), ones(1, 1, 4, 5), T,- # K)[0, 0, 0] with T = eye(4) except T[0, 0, 3] = 1, executed 2026-09-06 at commit 1a96bfd1- # (torch 2.14.0) -> [1.0, 2.0, 3.0, 4.0, 0.0] on cpu for float32, float64, float16 and bfloat16 and on- # mps for float32 and float16; the identity call is torch.equal to the input in every one of those- # cells, and the +1 call deviates from the input by 19.0.+ # warp_frame_depth reads the depth in the DESTINATION frame and the image in the SOURCE frame, and+ # ``src_trans_dst`` maps destination points into the source frame: with fx = fy = 1 and depth 1, a +1 x+ # translation samples one pixel to the RIGHT, out[u] = image_src[u + 1], and the last column reads the zero+ # padding. The identity transform is the contrast.+ # Snippet used to generate expected: warp_frame_depth(arange(20).view(1, 1, 4, 5), ones, T, K)[0, 0, 0]camera_matrix = _k53_warp(device, dtype)image_src = torch.arange(20.0, device=device, dtype=dtype).view(1, 1, 4, 5)depth_dst = torch.ones(1, 1, 4, 5, device=device, dtype=dtype)@@ -772,22 +717,10 @@ class TestDepthWarperConventions(BaseTester):)def test_convention_projection_matrix_is_k_dst_times_dst_trans_src(self, device, dtype):- # Convention pin: the class docstring's- # ``P_src^{dst} = K_dst * T_src^{dst}`` is exactly what compute_projection_matrix stores --- # ``_dst_proj_src == K_dst @ (E_dst @ inv(E_src))``, byte for byte, with K_dst and E_dst taken from the- # DESTINATION camera passed to the constructor and E_src from the camera passed to- # compute_projection_matrix. The extrinsics are inverted, not transposed: E_src here is a 90-degree- # rotation about z with a translation, so the transposed reading (which ignores the translation and is- # what a "R^T" shortcut would give) deviates from the stored matrix by 3.75.- # The source inverse is written out as a literal rather than computed with torch.linalg.inv, so the pin- # runs unchanged on mps and in half precision.- # Snippet used to generate expected: torch.equal(warper._dst_proj_src, K44 @ (E_dst @ E_src_inv)) and- # (K44 @ (E_dst @ E_src.transpose(-1, -2)) - K44 @ (E_dst @ E_src_inv)).abs().max() executed 2026-09-06- # at commit 1a96bfd1 (torch 2.14.0) -> True and 3.75 on cpu for float32, float64, float16 and bfloat16 and- # on mps for float32 and float16; the identity-source arm is True in the same cells.- # The identity-source arm uses the ROTATION as the destination camera on purpose: a pure x translation- # commutes with this K (K @ E - E @ K measures exactly 0.0), so it could not tell K @ E_dst from- # E_dst @ K; with the rotation the two orders differ by 4.0.+ # compute_projection_matrix stores ``K_dst @ (E_dst @ inv(E_src))``: K_dst and E_dst from the constructor's+ # camera, E_src from the argument. E_src is a rotation plus a translation, so the transposed reading+ # (``R^T``) differs. The identity-source arm uses the rotation as the destination because a pure x+ # translation commutes with this K. The inverse is a literal so the pin also runs on mps and in half.intrinsics = _k44_warp(device, dtype)dst_extrinsics = _tx_plus_one(device, dtype)src_extrinsics = torch.tensor(@@ -811,21 +744,9 @@ class TestDepthWarperConventions(BaseTester):assert (src_extrinsics @ intrinsics - intrinsics @ src_extrinsics).abs().max().item() > 0.5def test_convention_forward_returns_b_c_h_w_and_align_corners_defaults_to_true(self, device, dtype):- # Convention pin: forward takes the depth in- # the reference frame and the patch in the destination frame and returns a (B, C, H, W) tensor with the- # patch's channel count, for any C. ``align_corners`` defaults to True; DepthWarper exposes all three- # grid_sample knobs (mode, padding_mode, align_corners) while warp_frame_depth bakes all three in and has- # no such parameter at all, which this pin records rather than repairs.- # The shape claim is backed by a value: an identity camera pair returns the patch byte for byte in- # float32, so the assertion cannot be satisfied by an all-zero padded result.- # Snippet used to generate expected: DepthWarper(...).compute_projection_matrix(...)(ones(1, 1, 4, 5),- # patch) for patch = arange(40).view(1, 2, 4, 5) and arange(100).view(1, 5, 4, 5), executed 2026-09-06- # at commit 1a96bfd1 (torch 2.14.0) -> shapes (1, 2, 4, 5) and (1, 5, 4, 5) in every cell, and- # torch.equal to the patch on cpu for float32, float16 and bfloat16 and on mps for float32 and float16;- # in float64 the round trip is not bit-exact (the grid closes to 1e-12), so the value arm uses- # assert_close rather than torch.equal. The identity pair alone would be frame-invariant, so a second- # arm runs the same two channel counts through a +1 x translation and checks the output actually moved- # (measured deviation from the patch: 39.0 for C = 2 and 99.0 for C = 5, cpu float32).+ # forward takes the depth in the reference frame and the patch in the destination frame and returns+ # (B, C, H, W) for any C; ``align_corners`` defaults to True (warp_frame_depth has no such parameter).+ # The identity pair returns the patch, and a +1 x translation moves it, so the shape is backed by values.identity = _eye4(device, dtype)depth_src = torch.ones(1, 1, 4, 5, device=device, dtype=dtype)warper = self._warper(device, dtype, identity, identity)@@ -854,18 +775,9 @@ class TestDepthWarperConventions(BaseTester):assert (shifted - patch).abs().max().item() > 0.5def test_convention_warp_grid_requires_compute_projection_matrix_first(self, device, dtype):- # Convention pin: DepthWarper is a two-step API. Until- # compute_projection_matrix has been called there is no relative pose, and both warp_grid and forward- # raise ValueError("Please, call compute_projection_matrix."), while compute_subpixel_step raises- # RuntimeError from the None projection matrix instead. Afterwards warp_grid returns the- # grid_sample-ready NORMALIZED coordinates, (B, H, W, 2), in which pixel (0, 0) is (-1, -1) and pixel- # (H - 1, W - 1) is (1, 1) -- not the integer pixel grid that DepthWarper.grid itself holds.- # Snippet used to generate expected: DepthWarper(cam, 4, 5).warp_grid(ones(1, 1, 4, 5)) and the same- # instance called as a module, executed 2026-09-06 at commit 1a96bfd1 (torch 2.14.0) -> ValueError with- # that message; compute_subpixel_step on the same bare instance -> RuntimeError("Expected torch.Tensor,- # but got None Type from the projection matrix"); after compute_projection_matrix, shape (1, 4, 5, 2)- # with first pixel [-1.0, -1.0] and last pixel [1.0, 1.0]. All hold on cpu for float32, float64,- # float16 and bfloat16 and on mps for float32 and float16.+ # DepthWarper is a two-step API: before compute_projection_matrix, warp_grid and forward raise ValueError+ # and compute_subpixel_step raises RuntimeError. Afterwards warp_grid returns the NORMALIZED (B, H, W, 2)+ # grid, with pixel (0, 0) at (-1, -1) and pixel (H - 1, W - 1) at (1, 1).identity = _eye4(device, dtype)depth_src = torch.ones(1, 1, 4, 5, device=device, dtype=dtype)bare = DepthWarper(@@ -887,14 +799,8 @@ class TestDepthWarperConventions(BaseTester):self.assert_close(grid[0, -1, -1], torch.tensor([1.0, 1.0], device=device, dtype=dtype))def test_convention_depth_warp_is_byte_identical_to_depth_warper(self, device, dtype):- # Convention pin: depth_warp is a functional wrapper that constructs a- # DepthWarper, calls compute_projection_matrix and forwards -- the results are equal bit for bit, on the- # integer ramp and on the seeded random camera pair (random K, random rotation, B = 2). That is- # what makes depth_warp a wrapper rather than a second implementation, unlike warp_frame_depth (pinned- # below). The warp is a real one: it moves the image by 0.88 on the random pair.- # Snippet used to generate expected: torch.equal(depth_warp(...), warper(...)) executed 2026-09-06 on- # commit 1a96bfd1 (torch 2.14.0) -> True on cpu for float32, float64, float16 and bfloat16 and on mps for- # float32 and float16, for both fixtures; the max deviation between the two is 0.0 in every cell.+ # depth_warp builds a DepthWarper, calls compute_projection_matrix and forwards, so the results are equal+ # bit for bit, on the integer ramp and on the seeded random camera pair; the warp does move the image.intrinsics = _k44_warp(device, dtype)dst_extrinsics = _tx_plus_one(device, dtype)identity = _eye4(device, dtype)@@ -928,22 +834,11 @@ class TestDepthWarperConventions(BaseTester):assert torch.equal(by_class, by_function)assert (by_class - img).abs().max().item() > 0.1- def test_convention_warp_frame_depth_matches_depth_warper_without_being_bitwise_equal(self, device, dtype):- # Convention pin: the two APIs compute the same warp- # but not the same arithmetic -- warp_frame_depth unprojects through depth_to_3d_v2 and divides by z in- # project_points, while DepthWarper unprojects through pixel2cam with the cached intrinsics_inverse and- # divides in cam2pixel. They agree to the dtype tolerance and are NEVER bit-identical, on the- # seeded random camera pair with and without rotation. Collapsing the two implementations changes bits.- # The residual is a measured fact, not a bound, so no figure is asserted here.- # Snippet used to generate expected: torch.equal / (a - b).abs().max() on _random_warp_inputs(2, 11,- # True) and (2, 7, False), executed 2026-09-06 at commit 1a96bfd1 (torch 2.14.0) -> equal False in every- # cell; residual cpu float32 4.02e-07 and 5.36e-07, cpu float64 2.90e-12 and 2.25e-12, mps float32- # 2.98e-07 and 4.77e-07.+ def test_convention_warp_frame_depth_matches_depth_warper(self, device, dtype):+ # The two APIs compute the same warp through different arithmetic (depth_to_3d_v2 + project_points versus+ # pixel2cam + cam2pixel) and agree to the dtype tolerance on the seeded random camera pairs.if dtype in (torch.float16, torch.bfloat16):- pytest.skip(- "half precision: the two paths diverge by 4.88e-03 (float16, seed 7) and 1.95e-02 (bfloat16, "- "seed 11), outside the 2e-03 / 1.6e-02 assert_close tolerances; the claim is float32/float64"- )+ pytest.skip("half precision: the two paths diverge beyond the half-precision tolerances")for seed, rotate in ((11, True), (7, False)):img, dep, transform, k3, k4, batch_h, batch_w = self._random_warp_inputs(device, dtype, 2, seed, rotate)batch_identity = torch.eye(4, device=device, dtype=dtype)[None].repeat(2, 1, 1).contiguous()@@ -952,28 +847,14 @@ class TestDepthWarperConventions(BaseTester):by_class = warper(dep, img)by_function = warp_frame_depth(img, dep, transform, k3)self.assert_close(by_function, by_class)- assert not torch.equal(by_function, by_class)assert (by_class - img).abs().max().item() > 0.1def test_wart_warp_frame_depth_and_depth_warper_name_the_depth_frame_oppositely_4273(self, device, dtype):- # Wart pin for kornia#4273: the two APIs produce the same- # warp from OPPOSITE argument names, and this pin spells every argument as a KEYWORD so the clash is in- # the source text and not only in the prose. The identical warp is written- # warp_frame_depth(image_src=IMG, depth_dst=D, src_trans_dst=T) -- the depth is "dst"- # DepthWarper(pinhole_dst=camera(T)).compute_projection_matrix(pinhole_src=camera(I))(- # depth_src=D, patch_dst=IMG) -- the same depth is "src",- # and the image the other one calls "src" is "patch_dst" here. A reader who maps "dst" to "dst" across- # the two APIs gets the INVERSE warp, out[u] = image[u - 1], which is the swapped pair below.- # The keywords are load-bearing: #4273's Expected section is a parameter RENAME- # (depth_src -> depth_dst, patch_dst -> image_src, and the matching pinhole_dst / pinhole_src), so a- # positional version of this pin would keep passing through the repair and never force its own deletion.- # Snippet used to generate expected: the three row-0 calls executed 2026-09-06 at commit 1a96bfd1- # (torch 2.14.0) -> warp_frame_depth [1.0, 2.0, 3.0, 4.0, 0.0]; DepthWarper(pinhole_dst = +1 tx) with an- # identity pinhole_src [1.0, 2.0, 3.0, 4.0, 0.0] (float64: the last entry is 2.00e-11, hence assert_close- # and not torch.equal); DepthWarper(pinhole_dst = identity) with a +1 tx pinhole_src- # [0.0, 0.0, 1.0, 2.0, 3.0]. All three hold on cpu for float32, float64, float16 and bfloat16 and on mps- # for float32 and float16.- # Pins the CURRENT naming; NOT a contract; delete when #4273 aligns the two argument names.+ # kornia#4273: the two APIs produce the same warp from OPPOSITE argument names:+ # warp_frame_depth(image_src=IMG, depth_dst=D, src_trans_dst=T)+ # DepthWarper(pinhole_dst=cam(T)).compute_projection_matrix(pinhole_src=cam(I))(depth_src=D, patch_dst=IMG)+ # Mapping 'dst' to 'dst' across the two gives the INVERSE warp (the swapped pair). The arguments are+ # keywords on purpose: the #4273 fix is a rename, so this pin fails when it lands.image = torch.arange(20.0, device=device, dtype=dtype).view(1, 1, 4, 5)depth = torch.ones(1, 1, 4, 5, device=device, dtype=dtype)identity = _eye4(device, dtype)@@ -1006,26 +887,11 @@ class TestDepthWarperConventions(BaseTester):assert (by_class - swapped).abs().max().item() > 0.5def test_wart_warp_frame_depth_and_depth_warper_split_at_zero_transformed_depth_4267(self, device, dtype):- # Wart pin for kornia#4267: the two warps guard the z = 0 singularity differently. With K = I, unit- # depth and a transform that moves every point by (+1, 0, -1), every destination pixel lands at- # camera-frame z = 0 in the other view. warp_frame_depth projects through project_points, which SKIPS- # the homogeneous divide when abs(z) <= 1e-8, so it samples image_src at the undivided (u + 1, v) and- # returns the image shifted by one column; DepthWarper projects through cam2pixel, which divides by- # z + 1e-12, so the same pixel is sent to a coordinate of order 1e12 (inf in float16, where 1e-12- # rounds to 0) and nothing of the image comes back. One half unit closer (z = 0.5) the two agree, which- # is the claim the pin above states for float32 and float64.- # Snippet used to generate expected: warp_frame_depth(arange(1, 7).view(1, 1, 2, 3), ones, T, eye(3))- # and the DepthWarper pair built from the same T, executed 2026-09-08 at commit 26ddb21e- # (torch 2.14.0) -> warp_frame_depth [[2, 3, 0], [5, 6, 0]] in every cell (cpu float32, float64,- # float16, bfloat16; mps float32, float16); DepthWarper all zeros on cpu float32, float64 and bfloat16,- # nan on cpu float16, and backend-dependent values on mps (zeros in row 0, 1e24 in row 1 for float32) --- # so the pin asserts warp_frame_depth's value and the 1e12 grid coordinate and never samples through that- # grid: torch 2.5.1's aarch64 CPU grid_sample segfaults once one normalized coordinate exceeds 2**31 while- # the other is in range (x = 2147483648.0, y = -1.0 crashes; x = 2147483000.0 does not), which is what- # DepthWarper's grid holds here and what killed the macOS torch 2.5.1 CI legs on 2026-09-08; the- # vectorized-kernel crash is the open pytorch/pytorch#24823 (expanded from #19826).- # The z = 0.5 arm: max gap 0.0 (float32) and 2.4e-11 (float64) on cpu.- # Pins the CURRENT behavior; NOT a contract; delete when #4267 settles one z = 0 policy.+ # kornia#4267: the two warps guard z = 0 differently. With K = I, unit depth and a (+1, 0, -1) move, every+ # pixel lands at z = 0. warp_frame_depth skips the divide (abs(z) <= 1e-8) and returns the image shifted by+ # one column; DepthWarper divides by z + 1e-12, sending the pixel to a coordinate of order 1e12. At z = 0.5+ # the two agree. The pin never samples through the 1e12 grid: torch 2.5.1's aarch64 CPU grid_sample+ # segfaults on such coordinates (pytorch/pytorch#24823). Delete when #4267 settles one z = 0 policy.image = torch.arange(1.0, 7.0, device=device, dtype=dtype).view(1, 1, 2, 3)depth = torch.ones(1, 1, 2, 3, device=device, dtype=dtype)camera_matrix = torch.eye(3, device=device, dtype=dtype)[None]@@ -1151,23 +1017,13 @@ class TestDepthFromDisparity(BaseTester):self.gradcheck(kornia.geometry.depth.depth_from_disparity, (disparity, baseline, focal))def test_wart_zero_disparity_gives_a_finite_depth_4272(self, device, dtype):- # Wart pin for kornia#4272: depth_from_disparity computes- # ``baseline * focal / (disparity + 1e-8)``, so the epsilon enters the arithmetic instead of guarding a- # branch. A zero disparity -- the standard "no match here" fill value of every stereo matcher -- returns- # 5e9 for baseline 0.5 and focal 100 rather than inf, and that number is a function of the epsilon, not- # of the camera: it scales with baseline * focal and is nothing a caller can threshold against.- # The working case is asserted beside it so the pin is not just about the singular input: disparity 2- # gives 0.5 * 100 / 2 = 25.- # Snippet used to generate expected: depth_from_disparity(zeros(1, 1, 1, 1), 0.5, 100.0).item() executed- # 2026-09-06 at commit 1a96bfd1 (torch 2.14.0) -> 5000000000.0 on cpu float32 and float64 and on mps- # float32, 4999610368.0 on cpu bfloat16, and inf on cpu and mps float16 -- there the 1e-8 itself rounds- # to 0 (zeros(1, 1, 1, 1, dtype=float16) + 1e-8 is exactly 0), the divide is by zero, and the "finite- # depth" wart does not occur at all. The float16 arm asserts that inf instead of the finite value.- # Pins the CURRENT value; NOT a contract; delete when #4272 is repaired.+ # kornia#4272: depth_from_disparity computes ``baseline * focal / (disparity + 1e-8)``, so a zero+ # disparity (the usual 'no match' fill) returns 5e9 for baseline 0.5 and focal 100, a function of the+ # epsilon rather than inf. In float16 the 1e-8 rounds to 0 and the result is inf. Disparity 2 gives 25.+ # Delete when #4272 is fixed.disparity = torch.zeros(1, 1, 1, 1, device=device, dtype=dtype)depth = depth_from_disparity(disparity, 0.5, 100.0)if dtype == torch.float16:- assert (disparity + 1e-8).eq(0.0).all()assert torch.isinf(depth).all()returnassert torch.isfinite(depth).all()@@ -1180,11 +1036,9 @@ class TestDepthFromDisparity(BaseTester):@pytest.mark.parametrize("disparity_shape", [(2, 1, 2, 3), (2, 2, 3)])@pytest.mark.parametrize("per_batch", ["baseline", "focal", "both"])def test_convention_per_batch_camera_parameters_4272(self, disparity_shape, per_batch, device, dtype):- # Convention pin for kornia#4272: a (B,) baseline or focal pairs element b with disparity[b]. Until this- # landed only a shared value was accepted, and a (B,) tensor raised ShapeError. The expected result is- # built from the path that already worked, one sample at a time with (1,) parameters, so this asserts- # the pairing itself rather than a literal. The two samples use different camera values so a swapped or- # shared pairing gives different numbers; both a (B, 1, H, W) and a (B, H, W) disparity are covered.+ # kornia#4272: a (B,) baseline or focal pairs element b with disparity[b]. The expected result is built one+ # sample at a time with (1,) parameters, and the two samples use different camera values, so a swapped or+ # shared pairing fails; (B, 1, H, W) and (B, H, W) disparities are covered.disparity = torch.arange(1.0, 13.0, device=device, dtype=dtype).reshape(disparity_shape)baselines = torch.tensor([0.5, 2.0], device=device, dtype=dtype)focals = torch.tensor([100.0, 30.0], device=device, dtype=dtype)@@ -1207,8 +1061,6 @@ class TestDepthFromDisparity(BaseTester):)assert depth.shape == disparity.shapeself.assert_close(depth, per_sample, atol=0.0, rtol=0.0)- # the two samples use different camera values, so a swapped pairing gives different numbers and the- # comparison above genuinely discriminates the pairing (flip is a no-op on the shared (1,) parameter)swapped = depth_from_disparity(disparity, baseline.flip(0), focal.flip(0))assert not torch.allclose(depth, swapped)@@ -1371,18 +1223,11 @@ class TestDepthFromPlaneEquation(BaseTester):)def test_convention_plane_z_equals_two_gives_depth_two(self, device, dtype):- # Convention pin: the plane is given in the HESSIAN form- # ``n . X = d`` with the normal and the offset in the CAMERA frame, and the pixels are pixel- # coordinates that the function normalizes with the intrinsics itself. The fronto-parallel plane- # n = (0, 0, 1), d = 2 is the plane z = 2, so every pixel -- the principal point and a far off-axis one- # alike -- has depth exactly 2, and the output is (B, N), one depth per pixel, not a map.- # The tilted arm is the one-parameter-away check: rotating the normal to (0, 0.5, 1) / |.| makes the two- # pixels disagree (2.236 vs 1.491), so a reading in which the offset alone sets the depth fails.- # Snippet used to generate expected: depth_from_plane_equation(n, offsets, pixels, K) executed- # 2026-09-06 at commit 1a96bfd1 (torch 2.14.0) -> [[2.0, 2.0]] and torch.equal to full(2.0) on cpu for- # float32, float64, float16 and bfloat16 and on mps for float32 and float16; the tilted plane gives- # [2.2360680103302, 1.49071204662323] on cpu float32, [2.23606797749979, 1.4907119849998598] on cpu- # float64, [2.236328125, 1.490234375] on cpu float16 and [2.234375, 1.4921875] on cpu bfloat16.+ # The plane is in Hessian form ``n . X = d`` in the CAMERA frame, and the pixels are pixel coordinates the+ # function normalizes itself: n = (0, 0, 1), d = 2 is the plane z = 2, so every pixel has depth 2, and the+ # output is (B, N). The tilted normal makes two pixels disagree, so a reading where the offset alone sets+ # the depth fails.+ # Snippet used to generate expected: depth_from_plane_equation(n, offsets, pixels, K)camera_matrix = _k_asymmetric(device, dtype)offsets = torch.tensor([[2.0]], device=device, dtype=dtype)pixels = torch.tensor([[[4.0, 3.0], [29.0, 53.0]]], device=device, dtype=dtype)@@ -1400,27 +1245,13 @@ class TestDepthFromPlaneEquation(BaseTester):self.assert_close(tilted, torch.tensor([[2.2360679774997896, 1.4907119849998598]], device=device, dtype=dtype))def test_convention_depth_from_plane_equation_clamps_a_tiny_denominator(self, device, dtype):- # Convention pin: the ray-plane dot product is clamped, in a- # masked branch, to +/- eps when it falls inside (-eps, eps), so a nearly-grazing ray returns a large- # SIGNED finite depth (2 / 1e-8 = 2e8) instead of overflowing -- and the sign of the denominator is- # preserved, so the two arms differ by their sign rather than only by magnitude. Nothing outside the- # mask is touched, which is why the fronto-parallel pin above is exact. The mask- # also clamps exactly zero (kornia#4280), pinned below.- # ``eps`` is passed explicitly, equal to the function's own default, so the +/- 2e8 literal is a- # statement about the CLAMP and not about a default that could move: at eps = 1e-6 the same input- # returns +/- 2000000.0 instead (executed below).+ # A ray-plane dot product inside (-eps, eps) is clamped to +/- eps with its sign kept, so a nearly grazing+ # ray returns a large SIGNED finite depth (2 / 1e-8 = 2e8); eps is passed explicitly, and eps = 1e-6 gives+ # 2e6. An exact zero is covered by the #4280 pin below.# Snippet used to generate expected: depth_from_plane_equation([[0, 1, 2.384185791015625e-09]], [[2.0]],- # [[[4.0, 3.0]]], K, eps=1e-8) and the negated normal, executed 2026-09-06 at commit 1a96bfd1- # (torch 2.14.0) -> 200000000.0 and -200000000.0 on cpu float32 and float64 and on mps float32,- # 200278016.0 and -200278016.0 on cpu bfloat16; with eps=1e-6, 2000000.0 / -2000000.0 (cpu float32,- # float64, mps float32) and 2007040.0 / -2007040.0 (cpu bfloat16). float16 is skipped:- # 2.384185791015625e-09 underflows to 0 there, so the probe input is no longer inside the mask and the- # call returns inf on both signs at either eps.+ # [[[4.0, 3.0]]], K, eps=1e-8) and the negated normalif dtype == torch.float16:- pytest.skip(- "float16: the 2.384185791015625e-09 normal component underflows to 0, so the input is "- "no longer a tiny-but-non-zero denominator and both signs return inf"- )+ pytest.skip("float16: eps = 1e-8 underflows to 0 and 2e8 is past the float16 range, so the depth is inf")camera_matrix = _k_asymmetric(device, dtype)offsets = torch.tensor([[2.0]], device=device, dtype=dtype)principal_point = torch.tensor([[[4.0, 3.0]]], device=device, dtype=dtype)@@ -1435,14 +1266,10 @@ class TestDepthFromPlaneEquation(BaseTester):self.assert_close(wider, torch.full((1, 1), 2.0e6, device=device, dtype=dtype))def test_convention_depth_from_plane_equation_clamps_the_singularity_4280(self, device, dtype):- # Regression for #4280 (repaired by #4348): an exactly zero denominator is replaced by POSITIVE eps, so- # the grazing ray returns +2 / 1e-8 = +2e8 for either sign of the normal -- there is no sign to keep at- # zero, and the pin asserts the sign, not just the magnitude.- # Snippet used to generate expected: depth_from_plane_equation([[0, +-1, 0]], [[2.0]], [[[4.0, 3.0]]], K)- # executed 2026-09-08 at commit 089daad9 (torch 2.14.0) -> 200000000.0 for both normals on cpu float32,- # float64 and bfloat16 and on mps float32; float16 is skipped because 2e8 is past its range.+ # kornia#4280: an exactly zero denominator is replaced by POSITIVE eps, so the grazing ray returns +2e8 for+ # either sign of the normal.if dtype == torch.float16:- pytest.skip("float16: 2 / 1e-8 = 2e8 overflows the float16 range, so the repaired value is inf too")+ pytest.skip("float16: 2e8 overflows the float16 range")camera_matrix = _k_asymmetric(device, dtype)for sign in (1.0, -1.0):grazing = depth_from_plane_equation(diff --git a/tests/sensors/camera/test_camera_model.py b/tests/sensors/camera/test_camera_model.pyindex 2cece5dce..1e4c74884 100644--- a/tests/sensors/camera/test_camera_model.py+++ b/tests/sensors/camera/test_camera_model.py@@ -146,36 +146,23 @@ class TestPinholeCamera(BaseTester):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]].+ # The two camera type systems (#4274) share the pinhole mapping through different types: PinholeModel+ # .project takes a Vector3 and agrees with project_points on the same K. fx != fy and cx != cy, and the+ # second arm changes fy alone so only v moves. A raw Tensor is rejected.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)))+ self.assert_close(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'"):+ self.assert_close(square.data, project_points(points, _k3(device, dtype, symmetric)))+ with pytest.raises(AttributeError):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.+ # A non-dyadic depth: agreement is to roundoff, not bit for bit.points = torch.tensor([[5.0, 2.0, 3.0]], device=device, dtype=dtype)projected = cam.project(Vector3(points)).dataexpected = torch.tensor([[512.0 / 3.0, 109.0 / 3.0]], device=device, dtype=dtype)@@ -184,9 +171,9 @@ class TestPinholeCamera(BaseTester):@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.+ # Wart pin for #4267: geometry skips the divide at abs(z) <= 1e-8, sensors divides unconditionally, so+ # the two disagree at and below that threshold (float16 underflows these depths to zero, giving inf).+ # Delete or update when #4267 is repaired.cam = _pinhole(device, dtype)points = torch.tensor([[1.0, 2.0, z]], device=device, dtype=dtype)projected = cam.project(Vector3(points)).data@@ -202,19 +189,9 @@ class TestPinholeCamera(BaseTester):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.+ # depth is the camera-frame z (the result's third component), as in unproject_points without+ # normalize; the sensors API takes depth as (B,) where geometry takes (B, 1). The projected pixel differs+ # from the input's (x, y), so the round trip is not vacuous.cam = _pinhole(device, dtype)pixels = torch.tensor([[29.0, 28.0]], device=device, dtype=dtype)depth = torch.tensor([2.0], device=device, dtype=dtype)@@ -222,11 +199,11 @@ class TestPinholeCamera(BaseTester):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)))+ self.assert_close(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)+ self.assert_close(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):@@ -250,14 +227,13 @@ class TestPinholeCamera(BaseTester):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])+ @pytest.mark.parametrize("num_points", [1, 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.+ # Wart pin for #4274: sensors aligns (B,) intrinsics with the trailing axis of (B, N) points while geometry+ # inserts a point axis, so with B == N the cameras are silently reassociated, N == 1 projects to a (B, B, 2)+ # outer broadcast (unproject raises) and other N raise.+ # Hand-computed: 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]. Delete or update when #4274 is repaired.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)@@ -280,23 +256,20 @@ class TestPinholeCamera(BaseTester):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)+ elif num_points == 1:+ projected = cam.project(Vector3(points)).data+ self.assert_close(projected, per_camera_projected[None].expand(2, 2, 2), atol=0.0, rtol=0.0)+ with pytest.raises(RuntimeError):+ cam.unproject(Vector2(pixels), depth)else:- with pytest.raises(RuntimeError, match="size of tensor"):+ with pytest.raises(RuntimeError):cam.project(Vector3(points))- with pytest.raises(RuntimeError, match="size of tensor"):+ with pytest.raises(RuntimeError):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.+ # matrix() (alias K()) is the 3x3 K that kornia.geometry.camera takes, not PinholeCamera's 4x4; the+ # params batch axis is carried through. fx != fy and cx != cy, so the transpose is distinguishable.cam = _pinhole(device, dtype)expected = _k3(device, dtype)assert cam.matrix().shape == (3, 3)@@ -310,19 +283,9 @@ class TestPinholeCamera(BaseTester):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.+ # Wart pin for #4263: scale(s) gives cx' = s * cx (2.0 for cx = 4, s = 0.5), the half-pixel rule, while+ # kornia's integer pixel centres give s * cx + (s - 1) / 2 (1.75, and 1.25 for cy). PinholeCamera.scale+ # has the same wart (tests/geometry/camera/test_pinhole.py). 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)@@ -331,19 +294,8 @@ class TestPinholeCamera(BaseTester):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.+ # Wart pin for #4263 (raised in its comment thread): scale with a tensor factor turns the int ImageSize+ # fields into 0-dim floating tensors. Delete when #4263 is repaired.cam = _pinhole(device, dtype)assert isinstance(cam.image_size.height, int)assert isinstance(cam.image_size.width, int)@@ -355,14 +307,7 @@ class TestPinholeCamera(BaseTester):assert scaled.image_size.height.device == cam.params.deviceself.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.+ # The field type follows the scale factor's type: python numbers keep python numbers.from_int = cam.scale(2)assert isinstance(from_int.image_size.height, int)assert isinstance(from_int.image_size.width, int)@@ -377,8 +322,7 @@ class TestPinholeCamera(BaseTester):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.+ # The four CameraModelType members and the parameter-vector length each one enforces._LENGTHS = ((CameraModelType.PINHOLE, 4),(CameraModelType.BROWN_CONRADY, 12),@@ -387,21 +331,8 @@ class TestCameraModelTypes(BaseTester):)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.+ # params is (N,) or (B, N) with N fixed by the model type (4 PINHOLE, 12 BROWN_CONRADY,+ # 8 KANNALA_BRANDT_K3, 4 ORTHOGRAPHIC); N - 1 and (B, 1, N) raise ValueError. There is no (B, N, 4) form.assert [(m.name, m.value) for m in CameraModelType] == [("PINHOLE", 0),("BROWN_CONRADY", 1),@@ -417,8 +348,7 @@ class TestCameraModelTypes(BaseTester):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.+ # The message names the model type.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"):diff --git a/tests/sensors/camera/test_distortion_model.py b/tests/sensors/camera/test_distortion_model.pyindex 8090fa671..166b0addf 100644--- a/tests/sensors/camera/test_distortion_model.py+++ b/tests/sensors/camera/test_distortion_model.py@@ -77,37 +77,18 @@ class TestAffineTransform(BaseTester):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.+ def test_convention_distort_is_the_affine_map_and_undistort_is_its_inverse(self, device, dtype):+ # AffineTransform maps normalized z = 1 points to pixels, u = fx * x + cx, v = fy * y + cy with params+ # (fx, fy, cx, cy), as distort_points_affine does (#4274); undistort is its closed-form inverse.+ # fx != fy and cx != cy with an off-axis point, so a swap changes both components.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)+ self.assert_close(distorted.data, distort_points_affine(points, params))+ self.assert_close(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,diff --git a/tests/sensors/camera/test_projection_model.py b/tests/sensors/camera/test_projection_model.pyindex 5febca796..71140daf9 100644--- a/tests/sensors/camera/test_projection_model.py+++ b/tests/sensors/camera/test_projection_model.py@@ -77,22 +77,9 @@ class TestProjection(BaseTester):)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.+ # Wart pin for #4267: Z1Projection.project divides xy / z with no guard, so a point on the camera plane+ # gives inf (nan on a zero numerator) and a point behind the camera a finite pixel, where the geometry+ # projections mask the divide. 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()@@ -100,12 +87,7 @@ class TestProjection(BaseTester):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.+ # A zero numerator at z = 0 gives nan, which an isinf check misses.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()