π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
docs(geometry): convention blocks and pins for Keypoints, Vector3 and PLY I/O (batch 10b) (#5069)
Dmytro Mishkin0180b6fe443a
diff --git a/changelog.d/5069.added.md b/changelog.d/5069.added.mdnew file mode 100644index 000000000..055699fad--- /dev/null+++ b/changelog.d/5069.added.md@@ -0,0 +1 @@+Convention blocks for `Keypoints`, `Vector3` and the PLY writers (`(x, y)` pixel coordinates, homogeneous transformation, copy / in-place / write-through aliasing, the `double` `x y z` PLY layout), an API page for `kornia.geometry.vector`, and 13 convention and wart pins; the warts are documented and linked (#3952, #5022, #5023), not fixed.diff --git a/docs/source/geometry.keypoints.rst b/docs/source/geometry.keypoints.rstindex 7d4edf231..74f6319bf 100644--- a/docs/source/geometry.keypoints.rst+++ b/docs/source/geometry.keypoints.rst@@ -2,10 +2,11 @@ kornia.geometry.keypoints=========================.. meta::- :description: The kornia.geometry.keypoints module offers essential functionalities for the manipulation of 2D and 3D keypoints. This module provides tools for working with keypoints in both 2D and 3D space, enabling tasks such as feature detection, matching, and transformation. The module includes the `Keypoints` and `Keypoints3D` classes, which facilitate the management and processing of keypoint data, making it useful for applications like object recognition, tracking, and 3D reconstruction.+ :description: The kornia.geometry.keypoints module provides the Keypoints container for 2D (x, y) keypoints, which kornia.augmentation transforms together with the images, and the Keypoints3D container for 3D (x, y, z) points.-Object-oriented API for 2D and 3D keypoints: the :class:`~kornia.geometry.keypoints.Keypoints` and-:class:`~kornia.geometry.keypoints.Keypoints3D` classes wrap a tensor of points and provide transformations and padding.+Object-oriented API for keypoints: :class:`~kornia.geometry.keypoints.Keypoints` wraps a tensor of 2D ``(x, y)``+points and transforms and pads it; :class:`~kornia.geometry.keypoints.Keypoints3D` validates and stores 3D+``(x, y, z)`` points... autoclass:: kornia.geometry.keypoints.Keypoints:members:diff --git a/docs/source/geometry.rst b/docs/source/geometry.rstindex 584bcd9a1..d2568776a 100644--- a/docs/source/geometry.rst+++ b/docs/source/geometry.rst@@ -62,6 +62,7 @@ refinement.bbox <geometry.bbox>boxes <geometry.boxes>keypoints <geometry.keypoints>+ vector <geometry.vector>subpix <geometry.subpix>solvers <geometry.solvers>grid <geometry.grid>diff --git a/docs/source/geometry.vector.rst b/docs/source/geometry.vector.rstnew file mode 100644index 000000000..4aa04b7f1--- /dev/null+++ b/docs/source/geometry.vector.rst@@ -0,0 +1,16 @@+kornia.geometry.vector+======================++.. meta::+ :description: The kornia.geometry.vector module provides the Vector3, Vector2 and Scalar wrappers that kornia's plane, Lie-group and camera-model classes take and return for points, normals and offsets.++.. currentmodule:: kornia.geometry.vector++.. autoclass:: Vector3+ :members:++.. autoclass:: Vector2+ :members:++.. autoclass:: Scalar+ :members:diff --git a/kornia/geometry/keypoints.py b/kornia/geometry/keypoints.pyindex e016af680..dd5c59659 100644--- a/kornia/geometry/keypoints.py+++ b/kornia/geometry/keypoints.py@@ -33,11 +33,26 @@ def _merge_keypoint_list(keypoints: List[torch.torch.Tensor]) -> torch.torch.Tenclass Keypoints:- """2D Keypoints containing Nx2 or BxNx2 points.+ r"""2D keypoints, stored as an :math:`(N, 2)` or :math:`(B, N, 2)` tensor of ``(x, y)`` points.Args:- keypoints: Raw tensor or a list of torch.Tensors with the Nx2 coordinates- raise_if_not_floating_point: will raise if the torch.Tensor isn't float+ keypoints: tensor of :math:`(N, 2)` or :math:`(B, N, 2)` coordinates. A list of tensors is not implemented+ (see Known defects).+ raise_if_not_floating_point: ``True`` raises ``ValueError`` for a non-floating-point tensor, ``False`` casts+ it to ``float32``.++ Convention:+ - A point is ``(x, y)`` in pixel coordinates (:ref:`Coordinates and sizes <coordinate-conventions>`), the+ frame of the :class:`~kornia.geometry.boxes.Boxes` vertices.+ - :meth:`transform_keypoints` maps a point to :math:`M [x, y, 1]^\top` and converts it back with+ :func:`~kornia.geometry.conversions.convert_points_from_homogeneous`. ``inplace=False`` returns a new+ :class:`Keypoints`; ``inplace=True`` and :meth:`transform_keypoints_` rebind ``self`` to the transformed+ tensor and return ``self``. Neither writes into the tensor that ``self`` wrapped.+ - The constructor and :meth:`from_tensor` wrap a floating-point tensor without copying it. :meth:`pad`,+ :meth:`unpad`, item assignment and ``index_put(inplace=True)`` write into the stored tensor, so they+ change the caller's tensor; call :meth:`clone` first to keep it.+ - Known defects: list input and ``to_tensor(as_padded_sequence=True)`` raise ``NotImplementedError``+ (`#5023 <https://github.com/kornia/kornia/issues/5023>`_)."""@@ -117,6 +132,8 @@ class Keypoints:) -> "Keypoints":"""Write keypoint coordinates at selected tensor indices.+ See the Convention block on :class:`Keypoints`.+Args:indices: Index tuple or list accepted by ``Tensor.index_put_`` forthe stored coordinate tensor.@@ -164,12 +181,15 @@ class Keypoints:def pad(self, padding_size: torch.torch.Tensor) -> "Keypoints":"""Pad the keypoints in place.+ See the Convention block on :class:`Keypoints`.+``padding_size`` is ordered as ``(left, right, top, bottom)``. Only ``left`` and ``top`` shift thecoordinate origin. Both the batched :math:`(B, N, 2)` and the unbatched :math:`(N, 2)` container aresupported; the unbatched form carries a single image, so ``padding_size`` must have exactly one row.Args:- padding_size: (B, 4)+ padding_size: per-image padding in pixels, shaped :math:`(B, 4)`. A single row broadcasts across the+ batch."""if not (len(padding_size.shape) == 2 and padding_size.size(1) == 4):@@ -182,10 +202,13 @@ class Keypoints:def unpad(self, padding_size: torch.torch.Tensor) -> "Keypoints":"""Undo :meth:`pad` in place.+ See the Convention block on :class:`Keypoints`.+Accepts the same batched and unbatched containers and ``padding_size`` layout as :meth:`pad`.Args:- padding_size: (B, 4)+ padding_size: per-image padding in pixels, shaped :math:`(B, 4)`. A single row broadcasts across the+ batch."""if not (len(padding_size.shape) == 2 and padding_size.size(1) == 4):@@ -198,9 +221,12 @@ class Keypoints:def transform_keypoints(self, M: torch.torch.Tensor, inplace: bool = False) -> "Keypoints":r"""Apply a transformation matrix to the 2D keypoints.+ See the Convention block on :class:`Keypoints`.+Args:M: The transformation matrix to be applied, shape of :math:`(3, 3)` or :math:`(B, 3, 3)`.- inplace: do transform in-place and return self.+ inplace: ``True`` rebinds this object to the transformed tensor and returns it; ``False`` returns a new+ :class:`Keypoints`.Returns:The transformed keypoints.@@ -225,8 +251,8 @@ class Keypoints:"""Validate and wrap a tensor of 2D keypoint coordinates.Args:- keypoints: Tensor in :math:`(N, 2)` or :math:`(B, N, 2)` format.- The last dimension stores ``(x, y)`` coordinates.+ keypoints: Floating-point tensor in :math:`(N, 2)` or :math:`(B, N, 2)` format; an integer tensor+ raises ``ValueError``. The last dimension stores ``(x, y)`` coordinates.Returns:New :class:`Keypoints` instance containing the input coordinates.@@ -236,14 +262,12 @@ class Keypoints:def to_tensor(self, as_padded_sequence: bool = False) -> Union[torch.torch.Tensor, List[torch.torch.Tensor]]:r"""Cast :class:`Keypoints` to a tensor.- ``mode`` controls which 2D keypoints format should be use to represent keypoints in the tensor.-Args:- as_padded_sequence: whether to keep the pads for a list of keypoints. This parameter is only valid- if the keypoints are from a keypoint list.+ as_padded_sequence: not implemented; ``True`` raises ``NotImplementedError``+ (`#5023 <https://github.com/kornia/kornia/issues/5023>`_).Returns:- Keypoints tensor :math:`(B, N, 2)`+ The stored tensor itself, :math:`(N, 2)` or :math:`(B, N, 2)`."""if as_padded_sequence:@@ -262,10 +286,10 @@ class Keypoints:"""Cast stored keypoint coordinates to a target dtype.Args:- dtype: Destination floating-point dtype for the coordinate tensor.+ dtype: Destination dtype for the coordinate tensor.Returns:- ``self`` after converting the stored coordinates in place.+ ``self``, rebound to the converted tensor; the tensor it wrapped before is not modified."""self._data = self._data.type(dtype)return self@@ -309,11 +333,20 @@ class VideoKeypoints(Keypoints):class Keypoints3D:- """3D Keypoints containing Nx3 or BxNx3 points.+ """3D keypoints, stored as an :math:`(N, 3)` or :math:`(B, N, 3)` tensor of ``(x, y, z)`` points.++ The constructor validates the tensor as :class:`Keypoints` does and wraps a floating-point one without copying it.Args:- keypoints: Raw tensor or a list of torch.Tensors with the Nx3 coordinates- raise_if_not_floating_point: will raise if the torch.Tensor isn't float+ keypoints: tensor of :math:`(N, 3)` or :math:`(B, N, 3)` coordinates. A list of tensors is not implemented+ (see Known defects).+ raise_if_not_floating_point: ``True`` raises ``ValueError`` for a non-floating-point tensor, ``False`` casts+ it to ``float32``.++ Convention:+ - Known defects: list input, :meth:`pad`, :meth:`unpad`, :meth:`transform_keypoints`,+ :meth:`transform_keypoints_` and ``to_tensor(as_padded_sequence=True)`` raise ``NotImplementedError``+ (`#5023 <https://github.com/kornia/kornia/issues/5023>`_)."""@@ -375,33 +408,17 @@ class Keypoints3D:return self._datadef pad(self, padding_size: torch.torch.Tensor) -> "Keypoints3D":- """Pad a bounding keypoints.-- Args:- padding_size: (B, 6)-- """+ """Not implemented: raises ``NotImplementedError`` (`#5023 <https://github.com/kornia/kornia/issues/5023>`_)."""raise NotImplementedError("`Keypoints3D.pad` is not implemented (kornia#5023).")def unpad(self, padding_size: torch.torch.Tensor) -> "Keypoints3D":- """Pad a bounding keypoints.-- Args:- padding_size: (B, 6)-- """+ """Not implemented: raises ``NotImplementedError`` (`#5023 <https://github.com/kornia/kornia/issues/5023>`_)."""raise NotImplementedError("`Keypoints3D.unpad` is not implemented (kornia#5023).")def transform_keypoints(self, M: torch.Tensor, inplace: bool = False) -> "Keypoints3D":- r"""Apply a transformation matrix to the 3D keypoints.-- Args:- M: The transformation matrix to be applied, shape of :math:`(4, 4)` or :math:`(B, 4, 4)`.- inplace: do transform in-place and return self.-- Returns:- The transformed keypoints.+ """Not implemented: raises ``NotImplementedError`` (`#5023 <https://github.com/kornia/kornia/issues/5023>`_).+ Use :func:`~kornia.geometry.linalg.transform_points` on :attr:`data` instead."""raise NotImplementedError("`Keypoints3D.transform_keypoints` is not implemented; use "@@ -410,7 +427,7 @@ class Keypoints3D:)def transform_keypoints_(self, M: torch.Tensor) -> "Keypoints3D":- """Inplace version of :func:`Keypoints3D.transform_keypoints`."""+ """Not implemented: raises ``NotImplementedError`` (`#5023 <https://github.com/kornia/kornia/issues/5023>`_)."""return self.transform_keypoints(M, inplace=True)@classmethod@@ -427,16 +444,14 @@ class Keypoints3D:return cls(keypoints)def to_tensor(self, as_padded_sequence: bool = False) -> Union[torch.torch.Tensor, List[torch.torch.Tensor]]:- r"""Cast :class:`Keypoints` to a tensor.-- ``mode`` controls which 2D keypoints format should be use to represent keypoints in the tensor.+ r"""Cast :class:`Keypoints3D` to a tensor.Args:- as_padded_sequence: whether to keep the pads for a list of keypoints. This parameter is only valid- if the keypoints are from a keypoint list.+ as_padded_sequence: not implemented; ``True`` raises ``NotImplementedError``+ (`#5023 <https://github.com/kornia/kornia/issues/5023>`_).Returns:- Keypoints tensor :math:`(B, N, 3)`+ The stored tensor itself, :math:`(N, 3)` or :math:`(B, N, 3)`."""if as_padded_sequence:diff --git a/kornia/geometry/pointcloud.py b/kornia/geometry/pointcloud.pyindex 288a3082c..e06427a35 100644--- a/kornia/geometry/pointcloud.py+++ b/kornia/geometry/pointcloud.py@@ -35,16 +35,22 @@ __all__ = [def save_pointcloud_ply(filename: str | os.PathLike[str], pointcloud: torch.Tensor) -> None:- r"""Save to disk a pointcloud in PLY format.+ r"""Save to disk a pointcloud in ASCII PLY format.++ Convention:+ - The file holds one ``vertex`` per row of ``pointcloud.reshape(-1, 3)``, in order and with none dropped,+ and declares the properties ``x``, ``y`` and ``z`` in that order as ``double``. Each value is printed as+ the shortest text that parses back to the same float64, a non-finite one as ``nan`` / ``inf``.+ - ``pointcloud`` is channels-last. Apply ``permute(0, 2, 3, 1)`` to a+ :func:`~kornia.geometry.depth.depth_to_3d` result or use :func:`~kornia.geometry.depth.depth_to_3d_v2`:+ a channels-first tensor whose width is 3 passes the shape check and is written scrambled.+ - The PLY writers and loaders take ``filename`` as a ``str`` or ``os.PathLike[str]`` ending in ``.ply``+ (any case); another suffix raises ``TypeError``.Args:- filename: the path to save the pointcloud, as a string or ``os.PathLike[str]``.- Must end in ``.ply`` (case-insensitive).- pointcloud: tensor containing the pointcloud to save.- The tensor must be in the shape of :math:`(*, 3)` where the last- component is assumed to be a 3d point coordinate :math:`(X, Y, Z)`.- Every row is written, so the vertex count is the number of points and- row order is kept; non-finite coordinates are written as ``nan`` / ``inf``.+ filename: path of the ``.ply`` file to write, a ``str`` or ``os.PathLike[str]``.+ pointcloud: tensor of shape :math:`(*, 3)` with at least two dimensions, where the last dimension is the+ point :math:`(X, Y, Z)`."""filename = os.fspath(filename)if not (isinstance(filename, str) and filename.lower().endswith(".ply")):@@ -89,14 +95,12 @@ def save_pointcloud_ply(filename: str | os.PathLike[str], pointcloud: torch.Tensdef save_pointcloud_ply_binary(filename: str | os.PathLike[str], pointcloud: torch.Tensor) -> None:r"""Save to disk a pointcloud in binary PLY format.+ See the Convention block on :func:`save_pointcloud_ply`; the payload is little-endian float64.+Args:- filename: the path to save the pointcloud, as a string or ``os.PathLike[str]``.- Must end in ``.ply`` (case-insensitive).- pointcloud: tensor containing the pointcloud to save.- The tensor must be in the shape of :math:`(*, 3)` where the last- component is assumed to be a 3d point coordinate :math:`(X, Y, Z)`.- Every row is written, so the vertex count is the number of points and- row order is kept; non-finite coordinates are written as IEEE values.+ filename: path of the ``.ply`` file to write, a ``str`` or ``os.PathLike[str]``.+ pointcloud: tensor of shape :math:`(*, 3)` with at least two dimensions, where the last dimension is the+ point :math:`(X, Y, Z)`."""filename = os.fspath(filename)if not (isinstance(filename, str) and filename.lower().endswith(".ply")):@@ -283,11 +287,10 @@ def load_pointcloud_ply(filename: str | os.PathLike[str], header_size: Optional[``element vertex N`` declaration and the coordinates from the ``x``, ``y`` and ``z``properties, whatever other properties (normals, colours) or elements (faces) the file carries.A ``list`` property among the vertex properties is rejected, since it spans a variable number of- tokens and would shift every column after it.+ tokens and would shift every column after it. See the Convention block on :func:`save_pointcloud_ply`.Args:- filename: the path to the pointcloud, as a string or ``os.PathLike[str]``.- Must end in ``.ply`` (case-insensitive).+ filename: path of an existing ``.ply`` file, a ``str`` or ``os.PathLike[str]``.header_size: deprecated and ignored; the header is parsed instead of skipped.Return:@@ -346,11 +349,10 @@ def load_pointcloud_ply_binary(filename: str | os.PathLike[str], header_size: Opand so are elements that follow the vertices (faces). Both little- and big-endian payloads areread. A ``list`` property is only supported in elements that *follow* the vertices. Among thevertex properties, or in an element that precedes them, its byte length is unknown without- parsing it, so such a file is rejected.+ parsing it, so such a file is rejected. See the Convention block on :func:`save_pointcloud_ply`.Args:- filename: the path to the pointcloud, as a string or ``os.PathLike[str]``.- Must end in ``.ply`` (case-insensitive).+ filename: path of an existing ``.ply`` file, a ``str`` or ``os.PathLike[str]``.header_size: deprecated and ignored; the header is parsed instead of skipped.Return:diff --git a/kornia/geometry/vector.py b/kornia/geometry/vector.pyindex cc5ca85f0..fd0479ed2 100644--- a/kornia/geometry/vector.py+++ b/kornia/geometry/vector.py@@ -29,14 +29,30 @@ __all__ = ["Scalar", "Vector2", "Vector3"]# TODO: implement more functionality to validateclass Scalar(TensorWrapper):- """Wrap a tensor representing a scalar value."""+ """Wrap a tensor of scalars of any shape, such as the per-vector result of :meth:`Vector3.dot`.++ The tensor is wrapped without a copy, and the call-path type defect of :class:`Vector3` applies to it+ (`#5022 <https://github.com/kornia/kornia/issues/5022>`_).+ """def __init__(self, data: torch.Tensor) -> None:super().__init__(data)class Vector3(TensorWrapper):- """Wrap a tensor representing a 3D vector."""+ r"""Wrap a tensor of 3D vectors, shape :math:`(*, 3)`.++ Convention:+ - The tensor is wrapped without a copy; any leading shape and dtype are accepted. :attr:`x`, :attr:`y` and+ :attr:`z` are plain tensors of the leading shape :math:`(*)`, and :meth:`dot` and :meth:`squared_norm`+ return a :class:`Scalar` of that shape (for :meth:`dot`, the two operands' broadcast leading shape).+ - :meth:`random` draws vectors uniformly in the unit cube from torch's global generator, so every vector+ lies in the first octant: it is not a random direction.+ - Known defect: the returned type depends on the call path (``copy.deepcopy(v)`` and ``v.clone()`` are+ plain tensors, while a torch function rewraps its result as a ``Vector3``, so ``torch.linalg.norm(v,+ dim=-1)`` raises unless its result happens to end in 3), and a tuple index such as ``v[..., 0]`` raises+ (`#5022 <https://github.com/kornia/kornia/issues/5022>`_).+ """def __init__(self, vector: torch.Tensor) -> None:super().__init__(vector)@@ -64,12 +80,12 @@ class Vector3(TensorWrapper):return self.data[..., 2]def normalized(self) -> "Vector3":- """Return a copy with unit Euclidean length.+ """Return a copy with each vector divided by its Euclidean norm.Returns:- New :class:`Vector3` with the same leading shape as this vector.- The last dimension is normalized with the L2 norm, so each- ``(x, y, z)`` vector has length one when the input norm is nonzero.+ New :class:`Vector3` of the same shape. The norm is floored at ``1e-12``, so a shorter vector is scaled+ by ``1e12`` instead of normalized (`#3952 <https://github.com/kornia/kornia/issues/3952>`_). A zero+ vector stays zero in every dtype."""return Vector3(_normalize_last_dim(self.data, 1e-12))@@ -104,6 +120,8 @@ class Vector3(TensorWrapper):) -> "Vector3":"""Create random 3D vectors with optional leading dimensions.+ See the Convention block on :class:`Vector3`.+Args:shape: Optional leading dimensions before the final coordinatedimension. For example, ``shape=(B, N)`` creates@@ -174,7 +192,11 @@ class Vector3(TensorWrapper):class Vector2(TensorWrapper):- """Wrap a tensor representing a 2D vector."""+ r"""Wrap a tensor of 2D vectors, shape :math:`(*, 2)`.++ See the Convention block on :class:`Vector3`, which applies to ``(x, y)`` vectors; :meth:`random` fills the+ unit square.+ """def __init__(self, vector: torch.Tensor) -> None:super().__init__(vector)@@ -197,12 +219,10 @@ class Vector2(TensorWrapper):return self.data[..., 1]def normalized(self) -> "Vector2":- """Return a copy with unit Euclidean length.+ """Return a copy with each vector divided by its Euclidean norm.Returns:- New :class:`Vector2` with the same leading shape as this vector.- The last dimension is normalized so each ``(x, y)`` vector has- length one when the input norm is nonzero.+ New :class:`Vector2` of the same shape, with the norm floored as in :meth:`Vector3.normalized`."""return Vector2(_normalize_last_dim(self.data, 1e-12))@@ -236,6 +256,8 @@ class Vector2(TensorWrapper):) -> "Vector2":"""Create random 2D vectors with optional leading dimensions.+ See the Convention block on :class:`Vector3`.+Args:shape: Optional leading dimensions before the final coordinatedimension. For example, ``shape=(B, N)`` createsdiff --git a/tests/geometry/test_keypoints.py b/tests/geometry/test_keypoints.pyindex 62a7ca8b5..4547a9f5a 100644--- a/tests/geometry/test_keypoints.py+++ b/tests/geometry/test_keypoints.py@@ -18,9 +18,10 @@import pytestimport torch+import kornia.augmentation as Kfrom kornia.geometry.keypoints import Keypoints, Keypoints3D, VideoKeypoints-from testing.base import BaseTester+from testing.base import BaseTester, supports_bilinear_2d_grid_sampleclass TestKeypoints(BaseTester):@@ -415,3 +416,204 @@ class TestKeypoints3D(BaseTester):def test_module(self, device, dtype):pass++[email protected]("restore_torch_rng")+class TestConventionsKeypoints(BaseTester):+ """Pins for the coordinate, transform and aliasing conventions of :class:`Keypoints`."""++ @staticmethod+ def _has_cross_kernel(device, dtype):+ # The affine warp inverts its 3x3 matrix with kornia's closed-form inverse, built from torch.linalg.cross;+ # some torch builds have no cross kernel for a dtype (torch 2.5.1 on MPS raises for bfloat16).+ try:+ probe = torch.ones(1, 3, device=device, dtype=dtype)+ torch.linalg.cross(probe, probe, dim=-1)+ except RuntimeError:+ return False+ return True++ @staticmethod+ def _value_at(image, xy):+ # The image value at the pixel nearest to an (x, y) keypoint, or None when that pixel is outside the image.+ x, y = (int(v) for v in xy.round().tolist())+ if 0 <= x < image.shape[-1] and 0 <= y < image.shape[-2]:+ return float(image[0, 0, y, x])+ return None++ @pytest.mark.parametrize(+ "make_augmentation",+ [+ pytest.param(lambda: K.RandomAffine(degrees=(90.0, 90.0), p=1.0), id="rotate90"),+ pytest.param(lambda: K.RandomAffine(degrees=0.0, translate=(0.2, 0.0), p=1.0), id="translate_x"),+ ],+ )+ def test_convention_keypoints_are_xy_pixel_coordinates(self, make_augmentation, device, dtype):+ if not supports_bilinear_2d_grid_sample(device, dtype):+ pytest.skip(f"this torch build has no bilinear 2D grid_sample kernel for {dtype} on {device.type}")+ if not self._has_cross_kernel(device, dtype):+ pytest.skip(f"this torch build has no torch.linalg.cross kernel for {dtype} on {device.type}")+ # A keypoint is (x, y) in pixels: x indexes the columns (W) and y the rows (H). Image-content oracle: the+ # single bright pixel at row 2, column 8 of a 7 x 11 image is the keypoint (8, 2), and wherever the+ # augmentation moves that pixel, the transformed keypoint lands on it.+ height, width, row, col = 7, 11, 2, 8+ image = torch.zeros(1, 1, height, width, device=device, dtype=dtype)+ image[0, 0, row, col] = 1.0+ keypoints = torch.tensor([[[col, row]]], device=device, dtype=dtype)++ torch.manual_seed(0)+ augmentation = K.AugmentationSequential(make_augmentation(), data_keys=["input", "keypoints"])+ out_image, out_keypoints = augmentation(image, keypoints)+ landed = tuple(int(v) for v in out_keypoints[0, 0].round().tolist())+ brightest = int(out_image[0, 0].flatten().argmax())+ # rotate90 moves the pixel to (6, 6) and the seeded x-translation by +1.18 px to (9, 2)+ assert (brightest % width, brightest // width) == landed+ assert landed != (col, row)+ value = self._value_at(out_image, out_keypoints[0, 0])+ assert value is not None and value > 0.5++ # Relabel control: the same pixel read as (row, col) = (2, 8) leaves the image or lands on a dark pixel+ # ((0, 0) after rotate90, row 8 of a 7-row image after the translation).+ torch.manual_seed(0)+ augmentation = K.AugmentationSequential(make_augmentation(), data_keys=["input", "keypoints"])+ _, out_relabelled = augmentation(image, keypoints.flip(-1))+ value = self._value_at(out_image, out_relabelled[0, 0])+ assert value is None or value < 0.5++ def test_convention_keypoints_transform_is_column_vector_then_divided(self, device, dtype):+ # transform_keypoints maps a point p to M @ [x, y, 1]^T (a column vector, M on the left) and divides by the+ # third component. M != M^T and the projective row is non-zero, so for the first point the row-vector+ # reading [x, y, 1] @ M of the affine matrix ([0.2452, -0.0065]) and the undivided projective result+ # ([6.2, 3.2]) are far from the literals.+ points = torch.tensor([[8.0, 2.0], [3.0, 5.0]], device=device, dtype=dtype)+ affine = torch.tensor([[0.9, -0.3, 4.0], [0.2, 1.1, -1.0], [0.0, 0.0, 1.0]], device=device, dtype=dtype)+ projective = torch.tensor([[1.0, 0.1, -2.0], [0.05, 0.9, 1.0], [0.01, 0.02, 1.0]], device=device, dtype=dtype)++ expected_affine = torch.tensor([[10.6, 2.8], [5.2, 5.1]], device=device, dtype=dtype)+ self.assert_close(Keypoints(points.clone()).transform_keypoints(affine).data, expected_affine)++ # M @ [x, y, 1]^T = (6.2, 3.2, 1.12) and (1.5, 5.65, 1.13)+ expected_projective = torch.tensor(+ [[6.2 / 1.12, 3.2 / 1.12], [1.5 / 1.13, 5.65 / 1.13]], device=device, dtype=dtype+ )+ self.assert_close(Keypoints(points.clone()).transform_keypoints(projective).data, expected_projective)+ batched = Keypoints(points[None].clone()).transform_keypoints(projective[None])+ self.assert_close(batched.data, expected_projective[None])++ def test_convention_keypoints_transform_inplace_rebinds_copy_does_not_alias(self, device, dtype):+ # inplace=False returns a new Keypoints on new storage, so writing into the result reaches neither the+ # original container nor the caller's tensor. inplace=True, and transform_keypoints_, return self after+ # rebinding its data to the transformed tensor, so the caller's tensor keeps the old coordinates.+ original = torch.tensor([[[8.0, 2.0], [3.0, 5.0]]], device=device, dtype=dtype)+ affine = torch.tensor([[0.9, -0.3, 4.0], [0.2, 1.1, -1.0], [0.0, 0.0, 1.0]], device=device, dtype=dtype)+ expected = torch.tensor([[[10.6, 2.8], [5.2, 5.1]]], device=device, dtype=dtype)++ caller = original.clone()+ kp = Keypoints(caller)+ out = kp.transform_keypoints(affine)+ assert out is not kp+ self.assert_close(out.data, expected)+ out.data.fill_(999.0)+ assert kp.data is caller+ self.assert_close(caller, original)++ caller = original.clone()+ kp = Keypoints(caller)+ assert kp.transform_keypoints(affine, inplace=True) is kp+ self.assert_close(kp.data, expected)+ self.assert_close(caller, original)++ caller = original.clone()+ kp = Keypoints(caller)+ assert kp.transform_keypoints_(affine) is kp+ self.assert_close(kp.data, expected)+ self.assert_close(caller, original)++ @pytest.mark.parametrize("layout", ["batched", "unbatched", "strided"])+ def test_convention_keypoints_wrap_without_copy_and_edits_write_through(self, layout, device, dtype):+ # The constructor wraps the caller's tensor without copying it, a non-contiguous view included, and pad /+ # unpad shift that tensor in place and return self. padding_size rows are (left, right, top, bottom):+ # x += left and y += top. The four distinct padding values make a slot mix-up visible. clone() gives+ # independent storage. Item assignment and index_put(inplace=True) also write into the caller's tensor.+ original = torch.tensor([[8.0, 2.0], [3.0, 5.0]], device=device, dtype=dtype)+ padded = torch.tensor([[11.0, 9.0], [6.0, 12.0]], device=device, dtype=dtype)+ padding = torch.tensor([[3.0, 100.0, 7.0, 1000.0]], device=device, dtype=dtype)+ if layout == "batched":+ caller = original[None].clone()+ elif layout == "unbatched":+ caller = original.clone()+ else:+ caller = original.t().contiguous().t()+ assert not caller.is_contiguous()++ kp = Keypoints(caller)+ assert kp.pad(padding) is kp+ self.assert_close(caller.reshape(2, 2), padded)+ assert kp.unpad(padding) is kp+ self.assert_close(caller.reshape(2, 2), original)++ independent = kp.clone()+ independent.pad(padding)+ self.assert_close(independent.data.reshape(2, 2), padded)+ self.assert_close(caller.reshape(2, 2), original)++ second_point = (torch.tensor([1], device=device),)+ if layout == "batched":+ second_point = (torch.tensor([0], device=device), *second_point)+ kp.index_put(second_point, torch.tensor([100.0, 200.0], device=device, dtype=dtype), inplace=True)+ kp[..., :1, :] = Keypoints(torch.tensor([[70.0, 60.0]], device=device, dtype=dtype))+ edited = torch.tensor([[70.0, 60.0], [100.0, 200.0]], device=device, dtype=dtype)+ self.assert_close(caller.reshape(2, 2), edited)++ def test_convention_keypoints_single_padding_row_broadcasts_batch(self, device, dtype):+ caller = torch.tensor([[[8.0, 2.0], [3.0, 5.0]], [[1.0, 4.0], [6.0, 7.0]]], device=device, dtype=dtype)+ original = caller.clone()+ padding = torch.tensor([[3.0, 100.0, 7.0, 1000.0]], device=device, dtype=dtype)+ keypoints = Keypoints(caller)++ assert keypoints.pad(padding) is keypoints+ expected = torch.tensor([[[11.0, 9.0], [6.0, 12.0]], [[4.0, 11.0], [9.0, 14.0]]], device=device, dtype=dtype)+ self.assert_close(caller, expected)+ assert keypoints.unpad(padding) is keypoints+ self.assert_close(caller, original)++ @pytest.mark.parametrize(+ "path",+ [+ "keypoints_list_input",+ "keypoints_from_tensor_list",+ "keypoints_to_tensor_padded_sequence",+ "keypoints3d_list_input",+ "keypoints3d_from_tensor_list",+ "keypoints3d_to_tensor_padded_sequence",+ "keypoints3d_pad",+ "keypoints3d_unpad",+ "keypoints3d_transform_keypoints",+ "keypoints3d_transform_keypoints_",+ ],+ )+ def test_wart_keypoints_documented_paths_not_implemented_5023(self, path, device, dtype):+ # Wart pin (#5023): the API offers list input (the List[Tensor] annotation), to_tensor(as_padded_sequence=True)+ # and the Keypoints3D pad / unpad / transform_keypoints methods, and every one of these paths raises+ # NotImplementedError. Implementing a path, or removing it from the API, flips its case. The message is+ # not asserted, so rewording it leaves every case green.+ kp2d = torch.tensor([[[8.0, 2.0], [3.0, 5.0]]], device=device, dtype=dtype)+ kp3d = torch.tensor([[[8.0, 2.0, 4.0], [3.0, 5.0, 1.0]]], device=device, dtype=dtype)+ calls = {+ "keypoints_list_input": lambda: Keypoints([kp2d[0], kp2d[0, :1]]),+ "keypoints_from_tensor_list": lambda: Keypoints.from_tensor([kp2d[0], kp2d[0, :1]]),+ "keypoints_to_tensor_padded_sequence": lambda: Keypoints(kp2d).to_tensor(as_padded_sequence=True),+ "keypoints3d_list_input": lambda: Keypoints3D([kp3d[0], kp3d[0, :1]]),+ "keypoints3d_from_tensor_list": lambda: Keypoints3D.from_tensor([kp3d[0], kp3d[0, :1]]),+ "keypoints3d_to_tensor_padded_sequence": lambda: Keypoints3D(kp3d).to_tensor(as_padded_sequence=True),+ "keypoints3d_pad": lambda: Keypoints3D(kp3d).pad(torch.zeros(1, 6, device=device, dtype=dtype)),+ "keypoints3d_unpad": lambda: Keypoints3D(kp3d).unpad(torch.zeros(1, 6, device=device, dtype=dtype)),+ "keypoints3d_transform_keypoints": lambda: Keypoints3D(kp3d).transform_keypoints(+ torch.eye(4, device=device, dtype=dtype)[None]+ ),+ "keypoints3d_transform_keypoints_": lambda: Keypoints3D(kp3d).transform_keypoints_(+ torch.eye(4, device=device, dtype=dtype)[None]+ ),+ }+ with pytest.raises(NotImplementedError):+ calls[path]()diff --git a/tests/geometry/test_pointcloud_io.py b/tests/geometry/test_pointcloud_io.pyindex e6e934481..ff1d55ea8 100644--- a/tests/geometry/test_pointcloud_io.py+++ b/tests/geometry/test_pointcloud_io.py@@ -474,3 +474,66 @@ class TestLoadPointCloudPlyHeaderParsing(BaseTester):with pytest.warns(DeprecationWarning, match="header_size"):actual = getattr(kornia.geometry, loader)(str(filename), header_size=3)self.assert_close(actual, torch.tensor([[1.0, 2.0, 3.0]]))+++class TestConventionsPointCloudPly(BaseTester):+ """Pins for the column order and value type the PLY writers declare."""++ @pytest.mark.parametrize(+ "saver, loader",+ [+ ("save_pointcloud_ply", "load_pointcloud_ply"),+ ("save_pointcloud_ply_binary", "load_pointcloud_ply_binary"),+ ],+ )+ def test_convention_save_pointcloud_ply_writes_xyz_double(self, tmp_path, saver, loader, device, dtype):+ # One vertex per row, with the properties x, y and z in that order, all declared double. The ASCII file+ # prints each row's three columns in that order and the binary file packs them as little-endian float64;+ # both loaders return the float32 cast on the CPU. Every row holds three distinct values, so a column+ # permutation is visible.+ points = torch.tensor([[1.0, 2.0, 3.0], [7.25, 8.5, -9.75]], device=device, dtype=dtype)+ filename = str(tmp_path / f"xyz_{saver}.ply")+ getattr(kornia.geometry, saver)(filename, points)++ with open(filename, "rb") as f:+ raw = f.read()+ header = raw[: raw.index(b"end_header")].decode("ascii").splitlines()+ assert "element vertex 2" in header+ properties = [line for line in header if line.startswith("property")]+ assert properties == ["property double x", "property double y", "property double z"]+ payload = raw[raw.index(b"end_header") + len(b"end_header") :]+ if saver == "save_pointcloud_ply_binary":+ assert payload[:1] == b"\n"+ assert struct.unpack("<6d", payload[1:]) == (1.0, 2.0, 3.0, 7.25, 8.5, -9.75)+ else:+ # Parse the numbers rather than compare the text: the float format is not part of this convention.+ rows = [tuple(float(v) for v in line.split()) for line in payload.decode("ascii").splitlines() if line]+ assert rows == [(1.0, 2.0, 3.0), (7.25, 8.5, -9.75)]++ loaded = getattr(kornia.geometry, loader)(filename)+ assert loaded.dtype == torch.float32+ assert loaded.device.type == "cpu"+ self.assert_close(loaded, points.cpu().float(), rtol=0.0, atol=0.0)++ @pytest.mark.parametrize(+ "function",+ ["save_pointcloud_ply", "save_pointcloud_ply_binary", "load_pointcloud_ply", "load_pointcloud_ply_binary"],+ )+ def test_convention_ply_filename_ends_in_ply_any_case(self, tmp_path, function):+ # The writers and loaders take filename as a str or os.PathLike[str] ending in .ply, in any case. Another+ # suffix raises TypeError even when the file is a valid PLY file.+ points = torch.tensor([[1.0, 2.0, 3.0]])+ path = tmp_path / "upper_case.PLY"+ saver = "save_pointcloud_ply_binary" if function.endswith("_binary") else "save_pointcloud_ply"+ getattr(kornia.geometry, saver)(str(path), points)+ wrong_suffix = tmp_path / "valid_ply_contents.txt"+ wrong_suffix.write_bytes(path.read_bytes())++ if function.startswith("save"):+ getattr(kornia.geometry, function)(str(path), points)+ with pytest.raises(TypeError):+ getattr(kornia.geometry, function)(str(wrong_suffix), points)+ else:+ self.assert_close(getattr(kornia.geometry, function)(str(path)), points)+ with pytest.raises(TypeError):+ getattr(kornia.geometry, function)(str(wrong_suffix))diff --git a/tests/geometry/test_vector.py b/tests/geometry/test_vector.pyindex cd78ac1aa..d9acbbfa3 100644--- a/tests/geometry/test_vector.py+++ b/tests/geometry/test_vector.py@@ -15,9 +15,13 @@# limitations under the License.#+import copy+import pytestimport torch+from kornia.core.check import BaseError+from kornia.geometry.plane import Hyperplanefrom kornia.geometry.vector import Scalar, Vector2, Vector3from testing.base import BaseTester@@ -221,3 +225,137 @@ class TestVector2(BaseTester):@pytest.mark.skip(reason="not implemented yet")def test_gradcheck(self, device):pass++[email protected]("restore_torch_rng")+class TestConventionsVector(BaseTester):+ """Pins for the value conventions and known defects of :class:`Vector2` and :class:`Vector3`."""++ @pytest.mark.parametrize("vector_type, dim", [(Vector2, 2), (Vector3, 3)])+ def test_convention_vector_random_is_unit_box(self, vector_type, dim, device, dtype):+ # Vector.random draws every component uniformly in the unit box from torch's global generator. It is not a+ # random direction. torch.manual_seed reproduces a draw and another seed changes it.+ torch.manual_seed(0)+ vectors = vector_type.random((10000,), device=device, dtype=dtype)+ assert isinstance(vectors, vector_type)+ assert vectors.data.shape == (10000, dim)+ assert vectors.data.dtype == dtype+ assert vectors.data.device.type == device.type+ torch.manual_seed(0)+ assert torch.equal(vector_type.random((10000,), device=device, dtype=dtype).data, vectors.data)+ torch.manual_seed(1)+ assert not torch.equal(vector_type.random((10000,), device=device, dtype=dtype).data, vectors.data)+ values = vectors.data.cpu().double()+ assert float(values.min()) >= 0.0+ assert float(values.max()) <= 1.0+ norms = values.norm(dim=-1)+ assert float(norms.min()) < 0.5+ assert float(norms.max()) > 1.1+ self.assert_close(values.mean(0), torch.full((dim,), 0.5, dtype=torch.float64), rtol=0.0, atol=0.02)++ @pytest.mark.parametrize("vector_type, dim", [(Vector2, 2), (Vector3, 3)])+ def test_convention_vector_dot_returns_scalar_of_leading_shape(self, vector_type, dim, device, dtype):+ # dot and squared_norm reduce the last axis without keepdim and wrap the result as a Scalar of the leading+ # shape: two (2, dim) vectors give a (2,) Scalar; broadcastable (2, 1, dim) and (1, 4, dim) give (2, 4).+ a = vector_type(torch.tensor([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]], device=device, dtype=dtype)[..., :dim])+ b = vector_type(torch.tensor([[2.0, 3.0, 4.0], [5.0, 6.0, 7.0]], device=device, dtype=dtype)[..., :dim])++ dot = a.dot(b)+ assert isinstance(dot, Scalar)+ assert dot.data.shape == (2,)+ expected_dot = [8.0, 50.0] if dim == 2 else [20.0, 92.0]+ self.assert_close(dot.data, torch.tensor(expected_dot, device=device, dtype=dtype))++ broadcast_a = vector_type(+ torch.tensor([[[1.0, 2.0, 3.0]], [[4.0, 5.0, 6.0]]], device=device, dtype=dtype)[..., :dim]+ )+ broadcast_b = vector_type(+ torch.tensor(+ [[[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0], [1.0, 1.0, 1.0]]], device=device, dtype=dtype+ )[..., :dim]+ )+ broadcast_dot = broadcast_a.dot(broadcast_b)+ assert isinstance(broadcast_dot, Scalar)+ assert broadcast_dot.data.shape == (2, 4)+ expected_broadcast = (+ [[1.0, 2.0, 0.0, 3.0], [4.0, 5.0, 0.0, 9.0]]+ if dim == 2+ else [+ [1.0, 2.0, 3.0, 6.0],+ [4.0, 5.0, 6.0, 15.0],+ ]+ )+ self.assert_close(broadcast_dot.data, torch.tensor(expected_broadcast, device=device, dtype=dtype))++ squared_norm = a.squared_norm()+ assert isinstance(squared_norm, Scalar)+ assert squared_norm.data.shape == (2,)+ expected_squared_norm = [5.0, 41.0] if dim == 2 else [14.0, 77.0]+ self.assert_close(squared_norm.data, torch.tensor(expected_squared_norm, device=device, dtype=dtype))++ def test_wart_vector3_call_path_type_split_5022(self, device, dtype):+ # Wart pin (#5022): deepcopy and tensor methods lose the wrapper, while torch functions rewrap their result.+ # A shape-changing torch function then fails Vector3 validation. Each part flips when its path is fixed.+ wrapped = (+ Vector3(torch.tensor([[0.3, -1.2, 2.5]], device=device, dtype=dtype)),+ Vector2(torch.tensor([[0.3, -1.2]], device=device, dtype=dtype)),+ Scalar(torch.tensor([2.5], device=device, dtype=dtype)),+ )+ for obj in wrapped:+ assert type(copy.copy(obj)) is type(obj)+ deep = copy.deepcopy(obj)+ assert type(deep) is torch.Tensor+ self.assert_close(deep, obj.data)+ assert type(obj.clone()) is torch.Tensor+ assert type(torch.clone(obj)) is type(obj)++ with pytest.raises(BaseError):+ torch.linalg.norm(wrapped[0], dim=-1)+ # A reduced result with three elements instead passes shape validation and is miswrapped as a Vector3.+ lucky_shape = Vector3(torch.ones(3, 3, device=device, dtype=dtype))+ reduced = torch.linalg.norm(lucky_shape, dim=-1)+ assert type(reduced) is Vector3+ assert reduced.data.shape == (3,)++ normal = Vector3(torch.tensor([2.0, 1.0, -2.0], device=device, dtype=dtype) / 3.0)+ point = Vector3(torch.tensor([1.0, 2.0, 0.5], device=device, dtype=dtype))+ plane = Hyperplane.from_vector(normal, point)+ assert isinstance(plane.normal, Vector3)+ assert isinstance(plane.offset, Scalar)+ copied = copy.deepcopy(plane)+ assert type(copied.normal) is torch.Tensor+ assert type(copied.offset) is torch.Tensor+ with pytest.raises(AttributeError):+ _ = copied.normal.x++ def test_wart_vector3_normalized_scales_below_eps_3952(self, device, dtype):+ # Wart pin (#3952): normalized() divides by max(norm, 1e-12), so a vector shorter than 1e-12 is scaled by 1e12+ # instead of normalized: (1e-13, 0, 0) comes back with length 0.1. A fix that raises or returns a unit+ # vector flips it. float16 cannot hold 1e-13 (it underflows to the zero vector).+ if dtype == torch.float16:+ pytest.skip("1e-13 underflows to 0 in float16")+ short = Vector3(torch.tensor([1e-13, 0.0, 0.0], device=device, dtype=dtype))+ self.assert_close(short.normalized().data, torch.tensor([0.1, 0.0, 0.0], device=device, dtype=dtype))+ self.assert_close(+ Vector2(short.data[:2]).normalized().data, torch.tensor([0.1, 0.0], device=device, dtype=dtype)+ )++ @pytest.mark.parametrize("vector_type, dim", [(Vector2, 2), (Vector3, 3)])+ def test_wart_vector_tuple_index_raises_5022(self, vector_type, dim, device, dtype):+ # Wart pin (#5022): Vector.__getitem__ indexes data[idx, ...], so a tuple key is turned into an index+ # tensor and raises RuntimeError (v[..., 0], v[:, 0]), and an int index of an unbatched vector leaves a 0-d+ # tensor that fails the last-dimension check (IndexError). A fix (index data[idx] and return a Tensor when+ # the result is not (..., dim)) flips all three; indexing the batch, as in a[1], already works.+ data = torch.tensor([[0.3, -1.2, 2.5], [4.0, 0.5, -0.7]], device=device, dtype=dtype)[..., :dim]+ a = vector_type(data)+ with pytest.raises(RuntimeError):+ _ = a[..., 0]+ with pytest.raises(RuntimeError):+ _ = a[:, 0]+ single = vector_type(data[0])+ with pytest.raises(IndexError):+ _ = single[0]++ row = a[1]+ assert isinstance(row, vector_type)+ self.assert_close(row.data, data[1])