π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
docs(feature): convention blocks and pins for LAFs and patch extraction (#5827)
Dmytro Mishkin8900b93ea38c
diff --git a/changelog.d/5827.added.md b/changelog.d/5827.added.mdnew file mode 100644index 000000000..bab356a00--- /dev/null+++ b/changelog.d/5827.added.md@@ -0,0 +1 @@+Document the conventions of the local affine frame (LAF) and patch-extraction API (`kornia.feature.laf`, `get_laf_descriptors`, `LAFDescriptor` and `KORNIA_CHECK_LAF`) as Convention blocks and pointers, and add a "Local features" section to the Conventions & Pitfalls page: the `[A | c]` frame in pixels, scale and orientation, the patch a LAF samples, detector padding, and the conversion from OpenCV keypoints.diff --git a/docs/source/get-started/conventions.rst b/docs/source/get-started/conventions.rstindex 893e394ce..47ced7b29 100644--- a/docs/source/get-started/conventions.rst+++ b/docs/source/get-started/conventions.rst@@ -1104,6 +1104,69 @@ normalised camera coordinates, and :func:`~kornia.geometry.homography.find_homogleading coefficient lowers the degree- ``numpy.roots`` takes the same coefficient order, returns the complex roots too and drops leading zeros+.. _local-features-conventions:++Local features+--------------++A local affine frame (LAF) describes a keypoint by a ``2 x 3`` matrix ``[A | c]``, and a set of them is a+``(B, N, 2, 3)`` tensor. The centre ``c = (x, y)`` is in the pixel frame of+:ref:`Coordinates and sizes <coordinate-conventions>`, with pixel centres at integers: the centre of a 5-pixel axis is+``2``, not ``2.5``. ``A`` maps the patch frame onto the image, in pixels: its first column is the image of the patch's+x axis and its second column that of the patch's y axis. The Convention blocks of+:func:`~kornia.feature.laf_from_center_scale_ori` and :func:`~kornia.feature.extract_patches_from_pyramid` give the+full rules.++- The scale is :math:`\sqrt{|\det A|}` and the orientation is ``atan2(a12, a11)`` in degrees. A positive orientation+ turns the patch's x axis counter-clockwise on screen, with image y pointing down: with an orientation of ``90``, the+ ``+x`` side of the patch shows what lies above the centre.+- The region of a LAF is the ellipse ``c + A u`` over the unit vectors ``u``, and a ``PS x PS`` patch covers the+ square ``c + A [-1, 1]^2``: patch row 0 is on the patch's ``-y`` side, the top for an upright LAF, and the columns+ run along the patch's x axis.+- :func:`~kornia.feature.normalize_laf` divides the centre by ``max(W - 1, 1)`` and ``max(H - 1, 1)`` and ``A`` by+ the smaller of the two; its Convention block covers moving a LAF to an image of another size.+- kornia's LAF detectors pad the slots that no detection filled with an all-zero LAF and a zero response, so that a+ batch is one tensor. Drop those slots with :func:`~kornia.feature.laf_is_filled` before matching.++OpenCV keypoints and SIFT descriptors convert as follows:++.. list-table::+ :header-rows: 1++ * - Topic+ - kornia+ - OpenCV+ * - centre+ - ``c``, read by :func:`~kornia.feature.get_laf_center`+ - ``KeyPoint.pt``, in the same pixel frame: copy it unchanged. The default upscaling of ``cv2.SIFT`` biases+ ``pt`` by a fraction of a pixel; ``enable_precise_upscale=True`` removes the bias+ * - orientation+ - degrees, counter-clockwise on screen, read by :func:`~kornia.feature.get_laf_orientation`+ - ``KeyPoint.angle``, degrees clockwise on screen: ``angle = (-orientation) mod 360`` and+ ``orientation = -angle``+ * - scale+ - :math:`\sqrt{|\det A|}`, read by :func:`~kornia.feature.get_laf_scale`; the frames of+ :class:`~kornia.feature.SIFTFeatureScaleSpace` have the scale :math:`6 \sigma` for the detection scale+ :math:`\sigma`+ - ``KeyPoint.size``, a diameter, is :math:`2 \sigma` for ``cv2.SIFT``, so ``scale = 3 * size`` gives the frames+ of ``SIFTFeatureScaleSpace``; other detectors define ``size`` differently+ * - SIFT descriptor+ - kornia's bin layout+ - OpenCV's bin layout; :func:`~kornia.feature.convert_sift_descriptor_layout` converts between the two++For example, from the ``pt``, ``size`` and ``angle`` of ``cv2.SIFT`` keypoints:++.. code-block:: python++ import torch+ import kornia.feature as KF++ pt = torch.tensor([[70.0, 40.0], [21.5, 13.0]]) # KeyPoint.pt+ size = torch.tensor([5.3, 7.1]) # KeyPoint.size+ angle = torch.tensor([296.5, 32.2]) # KeyPoint.angle+ lafs = KF.laf_from_center_scale_ori(pt[None], 3.0 * size.view(1, -1, 1, 1), -angle.view(1, -1, 1))+ assert torch.allclose(-KF.get_laf_orientation(lafs).flatten() % 360.0, angle)+Pitfall checklist-----------------diff --git a/kornia/core/check.py b/kornia/core/check.pyindex 3275f4dea..0eade5ebd 100644--- a/kornia/core/check.py+++ b/kornia/core/check.py@@ -814,6 +814,11 @@ def KORNIA_CHECK_DM_DESC(desc1: torch.Tensor, desc2: torch.Tensor, dm: torch.Tendef KORNIA_CHECK_LAF(laf: torch.Tensor, raises: bool = True) -> bool:"""Check whether a Local Affine Frame (laf) has a valid shape.+ Convention:+ - Only the shape :math:`(B, N, 2, 3)` is checked: any dtype and any values pass, ``N = 0`` included. Use+ :func:`~kornia.feature.laf_is_valid` to check the values.+ - With ``raises=False``, a wrong shape returns ``False`` instead of raising.+Args:laf: local affine frame tensor to evaluate.raises: bool indicating whether an exception should be raised upon failure.diff --git a/kornia/feature/integrated.py b/kornia/feature/integrated.pyindex e0ec57765..d01f6b1d8 100644--- a/kornia/feature/integrated.py+++ b/kornia/feature/integrated.py@@ -138,11 +138,19 @@ def get_laf_descriptors() -> torch.Tensor:r"""Get local descriptors, corresponding to LAFs (keypoints).- The descriptor runs in eval mode, with its floating-point parameters and buffers cast to the device and dtype of- ``img`` for the call (a TorchScript module is called on a cast copy). The module keeps its device, dtype and- parameters, every submodule is switched to eval for the call and gets its train/eval mode back afterwards, and- gradients reach the module's parameters.- SOSNet and HyNet retain their final BatchNorm statistics in float32 for float16 images.+ Convention:+ - The descriptor sees the patches of :func:`~kornia.feature.extract_patches_from_pyramid` at ``patch_size``;+ see its Convention block for how they are sampled. ``patch_size`` is this argument, 32 by default, and is+ not read from the descriptor, so it has to be a size the descriptor accepts.+ - With ``grayscale_descriptor=True``, a 3-channel image is converted to grayscale first.+ - The descriptor runs in eval mode, with its floating-point parameters and buffers cast to the device and+ dtype of ``img`` for the call (a TorchScript module is called on a cast copy). SOSNet and HyNet retain their+ final BatchNorm statistics in float32 for float16 images. The module keeps its device, dtype and+ parameters, every submodule is switched to eval for the call and gets its train/eval mode back afterwards,+ and gradients reach the module's parameters.+ - An empty LAF set gives a :math:`(B, 0, D)` result, ``D`` as wide as a non-empty result, and a warning.+ That result does not require grad, so no gradient reaches ``img`` or the descriptor's parameters through+ it.Args:img: image features with shape :math:`(B,C,H,W)`.@@ -150,7 +158,8 @@ def get_laf_descriptors(patch_descriptor: patch descriptor module, e.g. :class:`~kornia.feature.SIFTDescriptor`or :class:`~kornia.feature.HardNet`.patch_size: patch size in pixels, which descriptor expects.- grayscale_descriptor: True if ``patch_descriptor`` expects single-channel image.+ grayscale_descriptor: True if ``patch_descriptor`` expects single-channel image; a 3-channel ``img`` is+ then converted to grayscale.Returns:Local descriptors of shape :math:`(B,N,D)` where :math:`D` is descriptor size.@@ -186,15 +195,18 @@ def get_laf_descriptors(class LAFDescriptor(nn.Module):r"""nn.Module to get local descriptors, corresponding to LAFs (keypoints).- Internally uses :func:`~kornia.feature.get_laf_descriptors`: the descriptor runs in eval mode with its parameters- cast to the image's device and dtype for the call; the module keeps its device, dtype and parameters, and its- train/eval modes are restored after the call.+ Convention:+ See the Convention block on :func:`~kornia.feature.get_laf_descriptors`, which ``forward`` calls with this+ module's ``patch_size`` and ``grayscale_descriptor``. The default descriptor is a pretrained+ :class:`~kornia.feature.HardNet` on ``32 x 32`` grayscale patches; :class:`~kornia.feature.SIFTDescriptor`+ defaults to 41-pixel patches, so pass ``patch_size=41`` with it.Args:patch_descriptor_module: patch descriptor module, e.g. :class:`~kornia.feature.SIFTDescriptor`or :class:`~kornia.feature.HardNet`. Default: :class:`~kornia.feature.HardNet` with pretrained weights.patch_size: patch size in pixels, which descriptor expects.- grayscale_descriptor: ``True`` if patch_descriptor expects single-channel image.+ grayscale_descriptor: ``True`` if patch_descriptor expects single-channel image; a 3-channel image is then+ converted to grayscale."""@@ -220,10 +232,7 @@ class LAFDescriptor(nn.Module):)def forward(self, img: torch.Tensor, lafs: torch.Tensor) -> torch.Tensor:- r"""Three stage local feature detection.-- First the location and scale of interest points are determined by- detect function. Then affine shape and orientation.+ r"""Describe the given LAFs with :func:`~kornia.feature.get_laf_descriptors`.Args:img: image features with shape :math:`(B,C,H,W)`.diff --git a/kornia/feature/laf.py b/kornia/feature/laf.pyindex dc3e6a62e..6531442e5 100644--- a/kornia/feature/laf.py+++ b/kornia/feature/laf.py@@ -44,8 +44,10 @@ def _laf_product_dtype(dtype: torch.dtype) -> torch.dtype:def get_laf_scale(LAF: torch.Tensor) -> torch.Tensor:"""Return a scale of the LAFs.- The determinant of a float16 LAF is formed in float32, so that a LAF whose entry products leave the float16 range- does not overflow; the scale is returned in the LAF dtype.+ Convention:+ - See the Convention block on :func:`~kornia.feature.laf_from_center_scale_ori`, which defines the scale.+ - The determinant of a float16 LAF is formed in float32, so that a LAF whose entry products leave the float16+ range does not overflow; the scale is returned in the LAF dtype.Args:LAF: :math:`(B, N, 2, 3)`@@ -71,9 +73,13 @@ def get_laf_scale(LAF: torch.Tensor) -> torch.Tensor:def laf_is_valid(laf: torch.Tensor) -> torch.Tensor:"""Check that each LAF is finite and has a finite, nonzero determinant.- The determinant of a float16 LAF is formed in float32, so the LAF is not judged by an intermediate outside the- float16 range: one whose entry products overflow float16 (for instance any LAF of scale 256 px or more) is valid,- and so is one whose determinant is too small for float16.+ Convention:+ - A LAF with a negative determinant, a mirrored frame, is valid. The all-zero padding LAF (see+ :func:`~kornia.feature.laf_is_filled`), a rank-1 ``A`` and an ``A`` whose determinant overflows are not.+ - The determinant of a float16 LAF is formed in float32, so the LAF is not judged by an intermediate outside+ the float16 range: one whose entry products overflow float16 (for instance any LAF of scale 256 px or more)+ is valid, and so is one whose determinant is too small for float16. The determinant of a float32, float64+ or bfloat16 LAF is formed in that dtype, where it can overflow.Args:laf: :math:`(B, N, 2, 3)`.@@ -96,14 +102,15 @@ def laf_is_valid(laf: torch.Tensor) -> torch.Tensor:def laf_is_filled(laf: torch.Tensor) -> torch.Tensor:"""Check which slots hold a detection rather than the zero-LAF padding.- Detectors return a fixed number of slots and pad the ones no detection filled with an all-zero- LAF and a zero response, so that the output shape does not depend on the image. Drop those- slots before matching: the padding frames are identical to one another, so a mutual- nearest-neighbour test does not reject them and they match each other at zero distance.-- Occupancy cannot be read off the response instead, because a pluggable signed response may have- a genuine maximum at exactly zero. Only an all-zero frame is padding: a detection at the image- origin has a zero centre but a nonzero shape, so it is filled.+ Convention:+ - kornia's LAF detectors pad the slots no detection filled with an all-zero LAF and a zero response, so that a+ batch is one tensor. Drop those slots before matching: the padding frames are identical to one another, so a+ mutual nearest-neighbour test does not reject them and they match each other at zero distance.+ - Only an all-zero frame is padding. Any other frame is filled: a detection at the image origin, which has a+ zero centre but a nonzero shape, and also a singular or non-finite frame, which+ :func:`~kornia.feature.laf_is_valid` screens out.+ - Occupancy cannot be read off the response instead, because a pluggable signed response may have a genuine+ maximum at exactly zero.Args:laf: :math:`(B, N, 2, 3)`.@@ -124,7 +131,9 @@ def laf_is_filled(laf: torch.Tensor) -> torch.Tensor:def get_laf_center(LAF: torch.Tensor) -> torch.Tensor:"""Return a center (keypoint) of the LAFs.- The convention is that center of 5-pixel image (coordinates from 0 to 4) is 2, and not 2.5.+ Convention:+ The centre is ``(x, y)`` in pixels, with pixel centres at integers; see+ :ref:`Local features <local-features-conventions>`.Args:LAF: :math:`(B, N, 2, 3)`@@ -144,6 +153,9 @@ def get_laf_center(LAF: torch.Tensor) -> torch.Tensor:def get_laf_orientation(LAF: torch.Tensor) -> torch.Tensor:"""Return orientation of the LAFs, in degrees.+ Convention:+ See the Convention block on :func:`~kornia.feature.laf_from_center_scale_ori`, which defines the orientation.+Args:LAF: :math:`(B, N, 2, 3)`@@ -163,7 +175,11 @@ def get_laf_orientation(LAF: torch.Tensor) -> torch.Tensor:def rotate_laf(LAF: torch.Tensor, angles_degrees: torch.Tensor) -> torch.Tensor:"""Apply additional rotation to the LAFs.- Compared to `set_laf_orientation`, the resulting rotation is original LAF orientation plus angles_degrees.+ Convention:+ - The result is ``[A @ R | c]``, with ``R`` the rotation matrix of ``angles_degrees`` from+ :func:`~kornia.geometry.conversions.angle_to_rotation_matrix`. The orientation grows by ``angles_degrees``+ (:func:`~kornia.feature.set_laf_orientation` sets it instead), and the centre and the upright factor that+ :func:`~kornia.feature.make_upright` returns are kept.Args:LAF: :math:`(B, N, 2, 3)`@@ -184,6 +200,10 @@ def rotate_laf(LAF: torch.Tensor, angles_degrees: torch.Tensor) -> torch.Tensor:def set_laf_orientation(LAF: torch.Tensor, angles_degrees: torch.Tensor) -> torch.Tensor:"""Change the orientation of the LAFs.+ Convention:+ See the Convention block on :func:`~kornia.feature.rotate_laf`. This rotates by ``angles_degrees`` minus the+ current orientation, so the orientation reads back as ``angles_degrees`` wrapped into ``[-180, 180]``.+Args:LAF: :math:`(B, N, 2, 3)`angles_degrees: :math:`(B, N, 1)` in degrees.@@ -201,9 +221,23 @@ def set_laf_orientation(LAF: torch.Tensor, angles_degrees: torch.Tensor) -> torcdef laf_from_center_scale_ori(xy: torch.Tensor, scale: Optional[torch.Tensor] = None, ori: Optional[torch.Tensor] = None) -> torch.Tensor:- """Create a LAF from keypoint center, scale and orientation.-- Useful to create kornia LAFs from OpenCV keypoints.+ r"""Create a LAF from keypoint center, scale and orientation.++ Convention:+ - A LAF is a :math:`(B, N, 2, 3)` tensor ``[A | c]``, with the centre ``c = (x, y)`` and ``A`` in pixels.+ ``A`` maps the patch frame onto the image: its first column is the image of the patch's x axis and its+ second column that of the patch's y axis. :ref:`Local features <local-features-conventions>` gives the+ pixel frame, the patch that :func:`~kornia.feature.extract_patches_from_pyramid` samples and the+ conversion of OpenCV keypoints.+ - This function returns ``A = scale * R``, with ``R = [[cos, sin], [-sin, cos]]`` of ``ori`` in degrees, the+ matrix of :func:`~kornia.geometry.conversions.angle_to_rotation_matrix`. A positive ``ori`` turns the+ patch's x axis counter-clockwise on screen, with image y pointing down.+ - For any LAF, the scale is :math:`\sqrt{|\det A|}` (:func:`~kornia.feature.get_laf_scale`, which adds+ ``1e-10`` to the determinant) and the orientation is ``atan2(a12, a11)`` in degrees+ (:func:`~kornia.feature.get_laf_orientation`), within ``[-180, 180]``: a LAF made with ``ori = 181`` reads+ back ``-179``. For :math:`\det A > 0`, ``A = U R`` with ``U`` the upright ``A`` that+ :func:`~kornia.feature.make_upright` returns, up to its stabilizers, and ``R`` the rotation matrix of that+ orientation.Args:xy: :math:`(B, N, 2)`.@@ -213,6 +247,12 @@ def laf_from_center_scale_ori(Returns:LAF :math:`(B, N, 2, 3)`+ Example:+ >>> xy = torch.tensor([[[5.0, 7.0]]])+ >>> laf_from_center_scale_ori(xy, torch.full((1, 1, 1, 1), 2.0), torch.tensor([[[30.0]]]))+ tensor([[[[ 1.7321, 1.0000, 5.0000],+ [-1.0000, 1.7321, 7.0000]]]])+"""KORNIA_CHECK_SHAPE(xy, ["B", "N", "2"])device = xy.device@@ -231,7 +271,12 @@ def laf_from_center_scale_ori(def scale_laf(laf: torch.Tensor, scale_coef: Union[float, torch.Tensor]) -> torch.Tensor:"""Multiplies region part of LAF ([:, :, :2, :2]) by a scale_coefficient.- So the center, shape and orientation of the local feature stays the same, but the region area changes.+ Convention:+ - The result is ``[k A | c]`` for ``k = scale_coef``, a product taken elementwise: the centre is kept. With one+ coefficient per LAF, the scale is multiplied by ``|k|``, and a negative ``k`` also turns the frame by 180+ degrees.+ - ``scale_coef`` is a ``float`` or a tensor that broadcasts against :math:`(B, N, 2, 2)`, such as one+ coefficient per LAF in a :math:`(B, N, 1, 1)` tensor; an ``int`` is rejected.Args:laf: :math:`(B, N, 2, 3)`@@ -240,6 +285,9 @@ def scale_laf(laf: torch.Tensor, scale_coef: Union[float, torch.Tensor]) -> torcReturns:LAF :math:`(B, N, 2, 3)`+ Raises:+ TypeError: if ``scale_coef`` is neither a ``float`` nor a tensor.+Example:>>> input = torch.ones(1, 5, 2, 3) # BxNx2x3>>> scale = 0.5@@ -254,11 +302,23 @@ def scale_laf(laf: torch.Tensor, scale_coef: Union[float, torch.Tensor]) -> torcdef make_upright(laf: torch.Tensor, eps: float = 1e-9) -> torch.Tensor:- """Rectify the affine matrix, so that it becomes upright.-- The all-zero LAF that pads an unfilled detector slot (see :func:`laf_is_filled`) is returned unchanged, so the- padding stays recognizable. A float16 LAF is rectified in float32, so that a LAF whose entry products leave the- float16 range does not overflow; the result is returned in the LAF dtype.+ r"""Rectify the affine matrix, so that it becomes upright.++ Convention:+ - The result is ``[U | c]``: the centre is kept, and ``U`` is the lower-triangular matrix with a positive+ diagonal and :math:`U U^\top = A A^\top`. The region, the ellipse ``c + A u`` over the unit vectors ``u``,+ and the scale are therefore kept, and the orientation becomes 0.+ - For :math:`\det A > 0`, ``A = U R`` with ``R`` the rotation matrix of the LAF's orientation, as in+ :func:`~kornia.feature.laf_from_center_scale_ori`. For :math:`\det A < 0` the reflection is dropped too:+ ``U`` has the determinant :math:`|\det A|`.+ - The equalities above hold up to two stabilizers: ``U`` is built from the norm of the first row of ``A``+ plus ``eps``, and from the scale of :func:`~kornia.feature.get_laf_scale`, which adds ``1e-10`` to the+ determinant. Both are negligible for a LAF in pixels, but a tiny frame such as ``A = diag(1e-12, 1)`` keeps+ neither its region nor its scale. The centre and the zero orientation are exact.+ - The all-zero LAF that pads an unfilled detector slot (see :func:`~kornia.feature.laf_is_filled`) is+ returned unchanged, so the padding stays recognizable.+ - A float16 LAF is rectified in float32, so that a LAF whose entry products leave the float16 range does not+ overflow; the result is returned in the LAF dtype.Args:laf: :math:`(B, N, 2, 3)`@@ -283,8 +343,8 @@ def make_upright(laf: torch.Tensor, eps: float = 1e-9) -> torch.Tensor:laf = torch.where(filled, laf, eye)det = get_laf_scale(laf)scale = det- # The function is equivalent to doing 2x2 SVD and resetting rotation- # matrix to an identity: U, S, V = svd(LAF); LAF_upright = U * S.+ # The result is the lower-triangular factor of the LQ decomposition A = U Q (Q orthogonal): for the rows r0, r1+ # of A, U = [[|r0|, 0], [r1 . r0 / |r0|, |det A| / |r0|]], built at unit scale and multiplied back by the scale.b2a2 = torch.sqrt(laf[..., 0:1, 1:2] ** 2 + laf[..., 0:1, 0:1] ** 2) + epslaf1_ell = torch.cat([(b2a2 / det).contiguous(), torch.zeros_like(det)], dim=3)laf2_ell = torch.cat(@@ -304,12 +364,24 @@ def make_upright(laf: torch.Tensor, eps: float = 1e-9) -> torch.Tensor:def ellipse_to_laf(ells: torch.Tensor) -> torch.Tensor:- """Convert ellipse regions to LAF format.-- The returned LAF holds the upright, lower-triangular ``A`` with ``A @ A.T == inverse([[a, b], [b, c]])``: the- Cholesky factor of the inverse ellipse matrix, not the symmetric inverse square root (the two differ by a- rotation). Either one maps the unit circle onto the ellipse :math:`a x^2 + 2 b x y + c y^2 = 1` centred at- ``(x, y)``; the upright one is what :func:`make_upright` returns for a LAF of that region with positive determinant.+ r"""Convert ellipse regions to LAF format.++ Convention:+ - An ellipse ``[x, y, a, b, c]`` is the region :math:`a u^2 + 2 b u v + c v^2 \le 1` in the coordinates+ ``(u, v)`` relative to its centre ``(x, y)``, as in the Oxford affine-region files. ``(x, y)`` becomes the+ LAF centre unchanged.+ - ``A`` is the lower-triangular matrix with a positive diagonal and ``A @ A.T == inverse([[a, b], [b, c]])``:+ the Cholesky factor of the inverse ellipse matrix, as VLFeat's ``vl_frame2oell.m`` builds it, not the+ symmetric inverse square root (the two differ by a rotation). Either one maps the unit circle onto the+ ellipse; the lower-triangular one is what :func:`~kornia.feature.make_upright` returns, up to its+ stabilizers, for any LAF of that region.+ - The conversion checks only the shape :math:`(B, N, 5)`; it does not check the ellipse values and does not+ raise on them. An ellipse that is degenerate or indefinite (``a``, ``c`` or ``a * c - b * b`` not positive)+ is not a bounded region; its LAF has ``inf`` or ``nan`` entries, or huge finite ones where rounding leaves+ ``a - b * b / c`` barely positive. Rounding also works the other way: a nearly singular valid ellipse can+ give ``inf`` or ``nan``. :func:`~kornia.feature.laf_is_valid` screens out the ``inf`` and ``nan`` results,+ which an ``isnan`` test misses for ``inf``; the huge finite ones pass it, so check the ellipse itself where+ that matters.See also https://github.com/vlfeat/vlfeat/blob/master/toolbox/sift/vl_frame2oell.m@@ -319,15 +391,6 @@ def ellipse_to_laf(ells: torch.Tensor) -> torch.Tensor:Returns:LAF :math:`(B, N, 2, 3)`- Note:- The conversion does not raise and does not check its input. An ellipse that is degenerate or indefinite- (``a``, ``c`` or ``a * c - b * b`` not positive) is not a bounded region; its LAF has ``inf`` or ``nan``- entries, or huge finite ones where rounding leaves ``a - b * b / c`` barely positive. Rounding also works the- other way: a nearly singular valid ellipse can give ``inf`` or ``nan``. Screen results with- :func:`laf_is_valid` rather than an ``isnan`` test. In ``float16`` an- ``a`` or ``c`` below roughly ``3e-8`` (half the smallest subnormal) rounds to ``0``, and a backend that- flushes subnormals to zero raises that cutoff to the smallest normal, about ``6e-5``.-Example:>>> input = torch.ones(1, 10, 5) # BxNx5>>> output = ellipse_to_laf(input) # BxNx2x3@@ -335,11 +398,6 @@ def ellipse_to_laf(ells: torch.Tensor) -> torch.Tensor:"""KORNIA_CHECK_SHAPE(ells, ["B", "N", "5"])B, N, _ = ells.shape- # Previous implementation was incorrectly using Cholesky decomp as matrix sqrt- # ell_shape = torch.cat([torch.cat([ells[..., 2:3], ells[..., 3:4]], dim=2).unsqueeze(2),- # torch.cat([ells[..., 3:4], ells[..., 4:5]], dim=2).unsqueeze(2)], dim=2).view(-1, 2, 2)- # out = torch.matrix_power(torch.cholesky(ell_shape, False), -1).view(B, N, 2, 2)-# The LAF is the upright (lower-triangular) A with A @ A.T == inverse([[a, b], [b, c]]), i.e. the# Cholesky factor of the inverse ellipse matrix, written with the Schur complement a - b^2 / c# (= det / c) so that b == 0 reduces to the plain 1 / sqrt(a), 1 / sqrt(c) diagonal.@@ -363,13 +421,16 @@ def ellipse_to_laf(ells: torch.Tensor) -> torch.Tensor:def laf_to_boundary_points(LAF: torch.Tensor, n_pts: int = 50) -> torch.Tensor:- """Convert LAFs to boundary points of the regions + center.+ r"""Convert LAFs to boundary points of the regions + center.- Used for local features visualization, see visualize_laf function.+ Convention:+ - The first point is the centre ``c``. The other ``n_pts - 1`` points are ``c + A @ (sin t, cos t)`` for ``t``+ from 0 to :math:`2 \pi` in equal steps: they start and end at ``c + A[:, 1]``, the tip of the patch's y+ axis, and so close the outline of the region.Args:LAF: :math:`(B, N, 2, 3)`- n_pts: number of points to output.+ n_pts: number of points to output, the centre included.Returns:torch.Tensor of boundary points LAF: :math:`(B, N, n_pts, 2)`@@ -426,8 +487,6 @@ def get_laf_pts_to_draw(LAF: torch.Tensor, img_idx: int = 0) -> Tuple[List[int],def denormalize_laf(LAF: torch.Tensor, images: torch.Tensor) -> torch.Tensor:"""Denormalize LAFs from the [0, 1] scale to image (pixel) scale.- The convention is that center of 5-pixel image (coordinates from 0 to 4) is 2, and not 2.5.-B,CH,H,W = images.size()MIN_SIZE = min(H - 1, W -1)[a11 a12 x]@@ -439,6 +498,9 @@ def denormalize_laf(LAF: torch.Tensor, images: torch.Tensor) -> torch.Tensor:A singleton axis (``H == 1`` or ``W == 1``) has no spatial extent and counts as one pixel, sothe conversion stays finite and round-trips with :func:`normalize_laf`.+ Convention:+ See the Convention block on :func:`~kornia.feature.normalize_laf`, which this inverts.+Args:LAF: :math:`(B, N, 2, 3)`images: :math:`(B, CH, H, W)`@@ -477,12 +539,21 @@ def normalize_laf(LAF: torch.Tensor, images: torch.Tensor) -> torch.Tensor:A singleton axis (``H == 1`` or ``W == 1``) has no spatial extent and counts as one pixel, sothe conversion stays finite instead of dividing by zero.+ Convention:+ - The centre becomes ``(x / max(W - 1, 1), y / max(H - 1, 1))``, which lies in ``[0, 1]`` for+ ``0 <= x <= W - 1`` and ``0 <= y <= H - 1``. ``A`` is divided by the smaller of the two denominators as a+ whole, not per axis, and can exceed 1.+ - Taken to an image of another size with :func:`~kornia.feature.denormalize_laf`, ``x`` becomes+ ``x max(W' - 1, 1) / max(W - 1, 1)``, which maps corner to corner when neither width is 1. A resize with+ ``align_corners=False``, the default of :func:`~kornia.geometry.transform.resize` in bilinear mode, maps+ pixel ``x`` to ``(x + 0.5) W' / W - 0.5`` instead, so the two disagree away from the image centre.+Args:LAF: :math:`(B, N, 2, 3)`images: :math:`(B, CH, H, W)`Returns:- the normalized LAF: :math:`(B, N, 2, 3)`, scale in image percentage (0, 1)+ the normalized LAF: :math:`(B, N, 2, 3)`"""KORNIA_CHECK_LAF(LAF)@@ -720,13 +791,16 @@ def extract_patches_simple() -> torch.Tensor:"""Extract patches defined by LAFs from image torch.Tensor.- No smoothing applied, huge aliasing (better use extract_patches_from_pyramid).+ Convention:+ See the Convention block on :func:`~kornia.feature.extract_patches_from_pyramid`. This function samples the+ same positions, always from ``img`` itself: a LAF larger than the patch is not smoothed first, so it aliases.Args:img: images, LAFs are detected in :math:`(B, CH, H, W)`.laf: :math:`(B, N, 2, 3)`.PS: patch size.- normalize_lafs_before_extraction: if True, lafs are normalized to image size.+ normalize_lafs_before_extraction: if True, lafs are normalized to image size; if False, ``laf`` must already+ be in the frame that :func:`~kornia.feature.normalize_laf` gives for ``img``.Returns:patches with shape :math:`(B, N, CH, PS,PS)`.@@ -771,14 +845,29 @@ def extract_patches_from_pyramid() -> torch.Tensor:"""Extract patches defined by LAFs from image torch.Tensor.- Patches are extracted from the appropriate pyramid level. A LAF whose scale selects a level- smaller than ``PS`` is sampled from the coarsest level that can still provide a full patch.+ Patches are extracted from the appropriate pyramid level.++ Convention:+ - Cell ``(i, j)`` of a ``PS x PS`` patch samples the image at ``c + A @ (u_j, u_i)``, with+ ``u_k = (2 k + 1) / PS - 1`` and the LAF ``[A | c]`` in pixels, pixel centres at integers. Row 0 is on the+ patch's ``-y`` side, the top for an upright LAF, the columns run along the patch's x axis, and the cells+ tile the square ``c + A [-1, 1]^2``. For an odd ``PS``, a LAF with ``A = (PS / 2) I`` centred on a pixel+ returns the image crop around that pixel.+ - The pyramid level is ``floor(log2(2 s / PS))`` for the scale ``s = sqrt(|det A|)``, clamped to the levels+ that exist: :func:`~kornia.geometry.transform.pyrdown` builds them while the shorter side stays at least+ ``PS``, so a larger LAF is sampled from the coarsest level that can still provide a full patch. Level 0,+ the image itself, always exists: an image whose shorter side is below ``PS`` has only that level, so even a+ large LAF is sampled from it. A level samples the same image positions as level 0, in its own pixels.+ - A cell outside the image reads the nearest border pixel of the level it samples.+ - The patches have the image's dtype. The sampling runs in the promoted dtype of the image and the LAF, and+ in at least ``float32``. A LAF with a non-finite entry gives a zero patch.Args:img: images, LAFs are detected in :math:`(B, CH, H, W)`.laf: :math:`(B, N, 2, 3)`.PS: patch size.- normalize_lafs_before_extraction: if True, lafs are normalized to image size.+ normalize_lafs_before_extraction: if True, lafs are normalized to image size; if False, ``laf`` must already+ be in the frame that :func:`~kornia.feature.normalize_laf` gives for ``img``.Returns:patches with shape :math:`(B, N, CH, PS,PS)`.@@ -915,10 +1004,13 @@ def extract_patches_from_pyramid(def laf_is_inside_image(laf: torch.Tensor, images: torch.Tensor, border: int = 0) -> torch.Tensor:"""Check which LAFs lie fully inside the image.- The region of a LAF ``[A | c]`` is the ellipse ``c + A u`` over the unit vectors ``u``. Along image axis- ``i`` (0 for x, 1 for y) it spans exactly ``c_i - r_i`` to ``c_i + r_i``, where ``r_i`` is the Euclidean norm- of row ``i`` of ``A``. A LAF is inside when both spans lie in ``border <= x <= w - 1 - border`` and- ``border <= y <= h - 1 - border``, so a region that touches the last valid pixel coordinate is inside.+ Convention:+ - The region of a LAF ``[A | c]`` is the ellipse ``c + A u`` over the unit vectors ``u``. Along image axis+ ``i`` (0 for x, 1 for y) it spans exactly ``c_i - r_i`` to ``c_i + r_i``, where ``r_i`` is the Euclidean+ norm of row ``i`` of ``A``. A LAF is inside when both spans lie in ``border <= x <= w - 1 - border`` and+ ``border <= y <= h - 1 - border``, so a region that touches the last valid pixel coordinate is inside.+ - The all-zero padding LAF is a point at the origin, so it counts as inside for ``border <= 0``, the default+ included; combine the mask with :func:`~kornia.feature.laf_is_filled` to drop the padding.Args:laf: :math:`(B, N, 2, 3)`.@@ -943,8 +1035,12 @@ def laf_is_inside_image(laf: torch.Tensor, images: torch.Tensor, border: int = 0def laf_to_three_points(laf: torch.Tensor) -> torch.Tensor:- """Convert local affine frame(LAF) to alternative representation: coordinates of LAF center, LAF-x unit vector,- LAF-y unit vector.+ """Convert local affine frames (LAFs) to three points: the tips of the patch's x and y axes, and the centre.++ Convention:+ - The columns of the result are the points ``c + A[:, 0]``, ``c + A[:, 1]`` and ``c``, in that order: the+ images of the patch points ``(1, 0)``, ``(0, 1)`` and ``(0, 0)``, at the frame's scale rather than of unit+ length. :func:`~kornia.feature.laf_from_three_points` is the inverse.Args:laf: :math:`(B, N, 2, 3)`.@@ -952,7 +1048,7 @@ def laf_to_three_points(laf: torch.Tensor) -> torch.Tensor:Returns:threepts :math:`(B, N, 2, 3)`.- """ # noqa:D205+ """KORNIA_CHECK_LAF(laf)return torch.stack([laf[..., 2] + laf[..., 0], laf[..., 2] + laf[..., 1], laf[..., 2]], dim=-1)@@ -960,7 +1056,9 @@ def laf_to_three_points(laf: torch.Tensor) -> torch.Tensor:def laf_from_three_points(threepts: torch.Tensor) -> torch.Tensor:"""Convert three points to local affine frame.- Order is (0,0), (0, 1), (1, 0).+ Convention:+ See the Convention block on :func:`~kornia.feature.laf_to_three_points`, which this inverts: the columns of+ ``threepts`` are the images of the patch points ``(1, 0)``, ``(0, 1)`` and ``(0, 0)``, in that order.Args:threepts: :math:`(B, N, 2, 3)`.@@ -978,12 +1076,20 @@ def laf_from_three_points(threepts: torch.Tensor) -> torch.Tensor:def perspective_transform_lafs(trans_01: torch.Tensor, lafs_1: torch.Tensor) -> torch.Tensor:r"""Apply perspective transformations to a set of local affine frames (LAFs).+ Convention:+ - ``trans_01`` maps pixels of frame 1 to pixels of frame 0, as in+ :func:`~kornia.geometry.linalg.transform_points`, and the centre maps through it exactly. The new ``A``+ is the chord through the mapped tips of the patch axes: the three points of+ :func:`~kornia.feature.laf_to_three_points` are transformed and turned back into a LAF. For an affine+ ``trans_01`` this equals the Jacobian of ``trans_01`` at the centre times ``A``; for a perspective one the+ two differ, the more so the larger the LAF.+Args:trans_01: torch.Tensor for perspective transformations of shape :math:`(B, 3, 3)`.lafs_1: torch.Tensor of lafs of shape :math:`(B, N, 2, 3)`.Returns:- torch.Tensor of N-dimensional points of shape :math:`(B, N, 2, 3)`.+ the transformed LAFs in frame 0, of shape :math:`(B, N, 2, 3)`.Examples:>>> rng = torch.manual_seed(0)diff --git a/tests/feature/test_integrated.py b/tests/feature/test_integrated.pyindex 3b165b3f5..dbf3aae5c 100644--- a/tests/feature/test_integrated.py+++ b/tests/feature/test_integrated.py@@ -1088,3 +1088,37 @@ class TestSIFTDescriptorLayoutArgument(BaseTester):def test_invalid_layout(self, preset):with pytest.raises(ValueError, match="layout"):preset(descriptor_layout="vlfeat")+++class TestConventionsSIFTScaleSpaceKeypointSize(BaseTester):+ @pytest.mark.parametrize("backend, backend_rtol", [("pyramid", 1e-3), ("patch", 2e-2)])+ def test_convention_sift_scale_space_frames_are_three_times_the_opencv_keypoint_size(+ self, device, dtype, backend, backend_rtol+ ):+ from testing.base import supports_reflect_padding++ if backend == "patch" and not supports_reflect_padding(device, dtype):+ pytest.skip("the patch backend's scale pyramid needs a reflection-padding kernel for this dtype")+ # Four Gaussian blobs (sigma 2.5, 3.5, 5 and 4.2 px) at non-integer centres x != y of a 150 x 230 uint8 image.+ # OpenCV 5.0.0 finds one keypoint on the sigma-5 blob, of size 2 sigma for its detection scale sigma:+ # cv2.SIFT_create(enable_precise_upscale=True).detect(img_u8, None) -> size 8.871075630187988+ # (the same image built with numpy; pixel sum 97820). SIFTFeatureScaleSpace frames have scale 6 sigma, so its+ # frame on that blob has scale 3 * size. The sigma-5 blob is the one both backends find in every dtype.+ h, w, cx, cy = 150, 230, 186.25, 101.4+ blobs = [(41.3, 37.6, 2.5), (118.7, 44.2, 3.5), (cx, cy, 5.0), (60.5, 110.8, 4.2)]+ yy, xx = torch.meshgrid(+ torch.arange(h, dtype=torch.float64), torch.arange(w, dtype=torch.float64), indexing="ij"+ )+ img = sum(torch.exp(-((xx - bx) ** 2 + (yy - by) ** 2) / (2.0 * s * s)) for bx, by, s in blobs)+ img = (torch.round(img.clamp(0.0, 1.0) * 255.0) / 255.0)[None, None].to(device, dtype)+ feature = kornia.feature.SIFTFeatureScaleSpace(64, descriptor_backend=backend).to(device, dtype).eval()+ with torch.no_grad():+ lafs, _, _ = feature(img)+ centres = kornia.feature.get_laf_center(lafs)[0].cpu().double()+ distance = (centres - torch.tensor([cx, cy], dtype=torch.float64)).norm(dim=-1)+ nearest = int(distance.argmin())+ assert distance[nearest] < 1.0+ scale = kornia.feature.get_laf_scale(lafs)[0, nearest, 0, 0].cpu().double()+ # the frame's own rounding on top of the backend's detection error+ rtol = backend_rtol + 2.0 * torch.finfo(dtype).eps+ self.assert_close(scale, torch.tensor(3.0 * 8.871075630187988, dtype=torch.float64), rtol=rtol, atol=0.0)diff --git a/tests/feature/test_laf.py b/tests/feature/test_laf.pyindex 908cc9591..047df8eab 100644--- a/tests/feature/test_laf.py+++ b/tests/feature/test_laf.py@@ -1959,3 +1959,380 @@ class TestTransformLAFs(BaseTester):dst_homo_src = create_random_homography(points_src, eye_size)# evaluate function gradientself.gradcheck(kornia.feature.perspective_transform_lafs, (dst_homo_src, points_src))+++class TestConventionsLAF(BaseTester):+ """Conventions of the LAF geometry, patch-extraction and LAF-descriptor helpers.++ Most pins share one sheared LAF ``[A | c]`` with ``A = U @ R(30)``, the upright factor ``U = [[3, 0], [1.5, 2]]``,+ ``R(t) = [[cos t, sin t], [-sin t, cos t]]`` and the centre ``c = (11, 3)``: ``a12 != a21``, a non-zero orientation+ and ``x != y``.+ """++ # [[3 cos 30, 3 sin 30, 11], [1.5 cos 30 - 2 sin 30, 1.5 sin 30 + 2 cos 30, 3]], in float64+ _SHEARED = [[2.598076211353316, 1.5, 11.0], [0.299038105676658, 2.482050807568877, 3.0]]+ # the same A centred at (21, 13.5), off the centre row and column of the 40 x 57 images below+ _SHEARED_IN_IMAGE = [[2.598076211353316, 1.5, 21.0], [0.299038105676658, 2.482050807568877, 13.5]]++ @staticmethod+ def _lafs(rows, device, dtype):+ return torch.tensor(rows, device=device, dtype=dtype).view(1, -1, 2, 3)++ @staticmethod+ def _transposed(laf):+ # the LAF of the transposed image: [[a22, a21, y], [a12, a11, x]]+ return laf[..., [1, 0], :][..., [1, 0, 2]]++ def test_convention_laf_orientation_turns_the_patch_x_axis_counter_clockwise_on_screen(self, device, dtype):+ laf = kornia.feature.laf_from_center_scale_ori(+ torch.tensor([[[5.0, 7.0]]], device=device, dtype=dtype),+ torch.full((1, 1, 1, 1), 2.0, device=device, dtype=dtype),+ torch.tensor([[[30.0]]], device=device, dtype=dtype),+ )+ # [A | c] with A = s * [[cos, sin], [-sin, cos]]. Column 0 of A is the patch x axis, s * (cos 30, -sin 30): with+ # image y pointing down it points up-right, so a positive orientation turns it counter-clockwise on screen.+ a11 = 2.0 * math.cos(math.pi / 6)+ self.assert_close(laf[0, 0], torch.tensor([[a11, 1.0, 5.0], [-1.0, a11, 7.0]], device=device, dtype=dtype))++ def test_convention_laf_scale_is_the_square_root_of_the_absolute_determinant(self, device, dtype):+ laf = self._lafs(self._SHEARED, device, dtype)+ # negating the patch y axis mirrors the frame: det A = 6 becomes -6+ mirrored = laf * torch.tensor([[1.0, -1.0, 1.0], [1.0, -1.0, 1.0]], device=device, dtype=dtype)+ scale = kornia.feature.get_laf_scale(torch.cat([laf, mirrored], dim=1))+ self.assert_close(scale.flatten(), torch.full((2,), math.sqrt(6.0), device=device, dtype=dtype))++ def test_convention_laf_orientation_is_atan2_of_a12_and_a11_in_degrees(self, device, dtype):+ # atan2(a12, a11) = 30, the rotation the sheared LAF was built with; atan2(a21, a11) would read 6.57+ laf = self._lafs(self._SHEARED, device, dtype)+ ori = kornia.feature.get_laf_orientation(laf)+ self.assert_close(ori.flatten(), torch.tensor([30.0], device=device, dtype=dtype))+ # the range is [-180, 180]: a LAF made with orientation 181 reads -179+ wrapped = kornia.feature.laf_from_center_scale_ori(+ torch.tensor([[[5.0, 7.0]]], device=device, dtype=dtype),+ None,+ torch.tensor([[[181.0]]], device=device, dtype=dtype),+ )+ ori = kornia.feature.get_laf_orientation(wrapped)+ self.assert_close(ori.flatten(), torch.tensor([-179.0], device=device, dtype=dtype))++ def test_convention_make_upright_keeps_the_lower_triangular_factor_and_drops_rotation_and_reflection(+ self, device, dtype+ ):+ laf = self._lafs(self._SHEARED, device, dtype)+ mirrored = laf * torch.tensor([[1.0, -1.0, 1.0], [1.0, -1.0, 1.0]], device=device, dtype=dtype)+ # U @ R(30) (det 6) and its mirror image U @ R(30) @ diag(1, -1) (det -6) both come back as U, centre kept+ expected = torch.tensor([[3.0, 0.0, 11.0], [1.5, 2.0, 3.0]], device=device, dtype=dtype).expand(1, 2, 2, 3)+ self.assert_close(kornia.feature.make_upright(torch.cat([laf, mirrored], dim=1)), expected)++ def test_convention_rotate_laf_right_multiplies_a_and_set_laf_orientation_rotates_by_the_difference(+ self, device, dtype+ ):+ laf = self._lafs(self._SHEARED, device, dtype)+ # rotate_laf(laf, t) = [A @ R(t) | c]: U @ R(30) becomes U @ R(45), so the upright factor U is kept;+ # [[3 cos 45, 3 sin 45, 11], [1.5 cos 45 - 2 sin 45, 1.5 sin 45 + 2 cos 45, 3]]+ u_r45 = [[2.1213203435596424, 2.1213203435596424, 11.0], [-0.35355339059327373, 2.4748737341529163, 3.0]]+ rotated = kornia.feature.rotate_laf(laf, torch.tensor([[[15.0]]], device=device, dtype=dtype))+ self.assert_close(rotated, self._lafs(u_r45, device, dtype))+ # set_laf_orientation rotates by (target - current): U @ R(-75)+ u_rm75 = [[0.7764571353075622, -2.897777478867205, 11.0], [2.3200802202319177, -0.931250649228561, 3.0]]+ reset = kornia.feature.set_laf_orientation(laf, torch.tensor([[[-75.0]]], device=device, dtype=dtype))+ self.assert_close(reset, self._lafs(u_rm75, device, dtype))+ # and an orientation set outside [-180, 180] reads back wrapped+ reset = kornia.feature.set_laf_orientation(laf, torch.tensor([[[200.0]]], device=device, dtype=dtype))+ self.assert_close(+ kornia.feature.get_laf_orientation(reset).flatten(), torch.tensor([-160.0], device=device, dtype=dtype)+ )++ def test_convention_scale_laf_multiplies_a_and_keeps_the_centre(self, device, dtype):+ laf = self._lafs(self._SHEARED, device, dtype)+ scaled = [[6.49519052838329, 3.75, 11.0], [0.747595264191645, 6.2051270189221925, 3.0]] # 2.5 * A+ self.assert_close(kornia.feature.scale_laf(laf, 2.5), self._lafs(scaled, device, dtype))+ # a (B, N, 1, 1) tensor scales each LAF by its own coefficient+ per_laf = torch.tensor([2.0, 3.0], device=device, dtype=dtype).view(1, 2, 1, 1)+ scales = kornia.feature.get_laf_scale(kornia.feature.scale_laf(laf.expand(1, 2, 2, 3), per_laf))+ self.assert_close(scales.flatten(), math.sqrt(6.0) * per_laf.flatten())+ # a negative coefficient turns the frame by 180 degrees: orientation 30 reads -150+ flipped = kornia.feature.scale_laf(laf, -1.0)+ self.assert_close(+ kornia.feature.get_laf_orientation(flipped).flatten(), torch.tensor([-150.0], device=device, dtype=dtype)+ )+ # the coefficient is a float or a tensor; an int is rejected+ with pytest.raises(TypeError, match=r"scale_coef should be float or torch\.Tensor"):+ kornia.feature.scale_laf(laf, 2)++ @pytest.mark.parametrize("theta, cv_angle", [(60.0, 296.5505), (-30.0, 32.1606), (150.0, 210.3108)])+ def test_convention_opencv_keypoint_angle_is_the_negated_laf_orientation(self, device, dtype, theta, cv_angle):+ # A Gaussian blob (sigma 5) at (70, 40) of a 96 x 128 uint8 image, bright on its half towards the on-screen+ # counter-clockwise angle theta. OpenCV 5.0.0 SIFT finds one KeyPoint on it whose `angle` is cv_angle, close to+ # (-theta) mod 360, because KeyPoint.angle turns clockwise on screen:+ # cv2.SIFT_create().detect(img_uint8, None)[0].angle (the same image built with numpy; pixel sum 19982)+ # A kornia LAF with orientation -cv_angle has to put the bright half on its patch +x axis. The LAF sits on the+ # blob centre, where the bright half's centroid points along theta by symmetry.+ h, w, cx, cy = 96, 128, 70.0, 40.0+ yy, xx = torch.meshgrid(+ torch.arange(h, dtype=torch.float64), torch.arange(w, dtype=torch.float64), indexing="ij"+ )+ t = math.radians(theta)+ side = (xx - cx) * math.cos(t) - (yy - cy) * math.sin(t)+ blob = torch.exp(-((xx - cx) ** 2 + (yy - cy) ** 2) / 50.0) * (1.0 + torch.tanh(side / 2.0)) / 2.0+ img = (torch.round(blob * 255.0) / 255.0)[None, None].to(device, dtype)+ laf = kornia.feature.laf_from_center_scale_ori(+ torch.tensor([[[cx, cy]]], device=device, dtype=dtype),+ torch.full((1, 1, 1, 1), 12.0, device=device, dtype=dtype),+ torch.tensor([[[-cv_angle]]], device=device, dtype=dtype),+ )+ patch = kornia.feature.extract_patches_from_pyramid(img, laf, 32)[0, 0, 0].cpu().double()+ u = (2.0 * torch.arange(32, dtype=torch.float64) + 1.0) / 32.0 - 1.0+ bright = math.degrees(math.atan2((patch * u[:, None]).sum().item(), (patch * u[None, :]).sum().item()))+ # within OpenCV's own orientation error (3.4, -2.2, -0.3 degrees); orientation +cv_angle reads -123, 63, 61+ assert abs(bright) < 10.0, bright++ def test_convention_three_points_are_the_images_of_patch_points_1_0_then_0_1_then_0_0(self, device, dtype):+ laf = self._lafs(self._SHEARED, device, dtype)+ # columns c + A[:, 0], c + A[:, 1], c. OpenCV 5.0.0 maps the patch points (1, 0), (0, 1), (0, 0) onto them with+ # [A | c]: cv2.getAffineTransform(np.float32([[1, 0], [0, 1], [0, 0]]), np.float32(points.T)) == [A | c]+ points = [[13.598076211353316, 12.5, 11.0], [3.299038105676658, 5.482050807568877, 3.0]]+ self.assert_close(kornia.feature.laf_to_three_points(laf), self._lafs(points, device, dtype))+ # back from points near x = 13, which half precision rounds to one ULP of 8 eps+ half = dtype in (torch.float16, torch.bfloat16)+ tol = {"rtol": 0.0, "atol": 8.0 * torch.finfo(dtype).eps} if half else {}+ self.assert_close(kornia.feature.laf_from_three_points(self._lafs(points, device, dtype)), laf, **tol)++ def test_convention_ellipse_to_laf_returns_the_lower_triangular_factor_of_the_inverse_ellipse(self, device, dtype):+ # Oxford [x, y, a, b, c] for a x^2 + 2 b x y + c y^2 = 1. Expected: VLFeat's mapFromS (vl_frame2oell.m, 1b9075f)+ # of S = inv([[a, b], [b, c]]), A = [[sqrt(S11), 0], [S12 / sqrt(S11), sqrt(S22 - S12^2 / S11)]], with (x, y)+ # passed through. Row 0 is the region of the sheared LAF: its symmetric root [[2.873, 0.862], [0.862, 2.347]] is+ # not what comes back. Row 2 is row 0 transposed, (y, x, c, b, a): it gives make_upright of the transposed LAF,+ # not the transposed U = [[2, 1.5], [0, 3]].+ ells = torch.tensor(+ [+ [+ [11.0, 3.0, 25.0 / 144.0, -0.125, 0.25],+ [20.0, 10.0, 0.04, 0.01, 0.0625],+ [3.0, 11.0, 0.25, -0.125, 25.0 / 144.0],+ ]+ ],+ device=device,+ dtype=dtype,+ )+ expected = [+ [[3.0, 0.0, 11.0], [1.5, 2.0, 3.0]],+ [[5.103103630798288, 0.0, 20.0], [-0.816496580927726, 4.0, 10.0]],+ [[2.5, 0.0, 3.0], [1.8, 2.4, 11.0]],+ ]+ self.assert_close(kornia.feature.ellipse_to_laf(ells), self._lafs(expected, device, dtype))++ def test_convention_normalize_laf_divides_by_the_last_pixel_index(self, device, dtype):+ img = torch.zeros(1, 1, 9, 13, device=device, dtype=dtype) # x in 0 .. 12, y in 0 .. 8+ laf = self._lafs(self._SHEARED, device, dtype)+ # centre (x / (W - 1), y / (H - 1)) = (11 / 12, 3 / 8); A / min(H - 1, W - 1) = A / 8+ expected = [[0.3247595264191645, 0.1875, 11.0 / 12.0], [0.03737976320958225, 0.31025635094610963, 0.375]]+ normalized = kornia.feature.normalize_laf(laf, img)+ self.assert_close(normalized, self._lafs(expected, device, dtype))+ # relabelling: the transposed LAF in the transposed image normalizes to the transposed result+ self.assert_close(+ kornia.feature.normalize_laf(self._transposed(laf), img.transpose(-1, -2)),+ self._transposed(self._lafs(expected, device, dtype)),+ )+ # moved to another resolution, a normalized LAF maps corner to corner: 9 x 13 -> 17 x 25 doubles x, y and A+ # (an align_corners=False resize maps x to (x + 0.5) W' / W - 0.5: the centre would land at (21.62, 6.11))+ doubled = [[5.196152422706632, 3.0, 22.0], [0.598076211353316, 4.964101615137754, 6.0]]+ moved = kornia.feature.denormalize_laf(normalized, torch.zeros(1, 1, 17, 25, device=device, dtype=dtype))+ self.assert_close(moved, self._lafs(doubled, device, dtype))+ # a singleton axis counts as one pixel: on a 1 x 13 image y and A are divided by 1+ row = [[2.598076211353316, 1.5, 11.0 / 12.0], [0.299038105676658, 2.482050807568877, 3.0]]+ single = kornia.feature.normalize_laf(laf, torch.zeros(1, 1, 1, 13, device=device, dtype=dtype))+ self.assert_close(single, self._lafs(row, device, dtype))++ def test_convention_laf_is_inside_image_is_a_closed_box_of_pixel_indices(self, device, dtype):+ img = torch.zeros(1, 1, 40, 57, device=device, dtype=dtype) # x in 0 .. 56, y in 0 .. 39+ # The rows of A = [[3, 4], [-1.5, 2]] (orientation 53.13) have norms 5 and 2.5, so the region spans c_x -+ 5 and+ # c_y -+ 2.5. The first LAF touches x = 56 and y = 39, the fourth x = 0 and y = 0; the others pass an edge by+ # 0.25 px.+ centres = [(51.0, 36.5), (51.25, 36.5), (51.0, 36.75), (5.0, 2.5), (4.75, 2.5), (5.0, 2.25)]+ rows = [[[3.0, 4.0, x], [-1.5, 2.0, y]] for x, y in centres]+ # the all-zero padding LAF counts as inside; a 0.25-px LAF centred on the last column does not+ rows += [[[0.0, 0.0, 0.0], [0.0, 0.0, 0.0]], [[0.25, 0.0, 56.0], [0.0, 0.25, 20.0]]]+ laf = self._lafs(rows, device, dtype)+ expected = torch.tensor([[True, False, False, True, False, False, True, False]], device=device)+ assert torch.equal(kornia.feature.laf_is_inside_image(laf, img), expected)+ # relabelling: the transposed LAFs in the transposed image get the same verdicts+ assert torch.equal(kornia.feature.laf_is_inside_image(self._transposed(laf), img.transpose(-1, -2)), expected)++ @staticmethod+ def _degenerate_lafs(device, dtype):+ big = 2.0 * math.sqrt(torch.finfo(dtype).max) # finite entries whose product overflows this dtype+ nan = float("nan")+ rows = [+ [[2.0, 1.0, 5.0], [0.5, 3.0, 7.0]], # det 5.5+ [[2.0, 1.0, 5.0], [0.5, -3.0, 7.0]], # det -6.5: mirrored+ [[1.0, 2.0, 5.0], [2.0, 4.0, 7.0]], # rank 1: det 0+ [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0]], # the padding of an unfilled detector slot+ [[2.0, 1.0, nan], [0.5, 3.0, 7.0]], # NaN centre+ [[big, 0.0, 5.0], [0.0, big, 7.0]], # det 4 * max: overflows to inf in this dtype+ [[0.0, 0.0, 3.0], [0.0, 0.0, 4.0]], # zero A, non-zero centre+ ]+ return torch.tensor([rows], device=device, dtype=dtype)++ def test_convention_laf_is_valid_needs_finite_entries_and_a_finite_non_zero_determinant(self, device, dtype):+ laf = self._degenerate_lafs(device, dtype)+ # A float16 LAF's determinant is formed in float32, which holds the product of any two float16 entries, so+ # the big frame is invalid in every other dtype and valid in float16.+ big_is_valid = dtype == torch.float16+ expected = torch.tensor([[True, True, False, False, False, big_is_valid, False]], device=device)+ assert torch.equal(kornia.feature.laf_is_valid(laf), expected)++ def test_convention_laf_is_filled_treats_only_the_all_zero_frame_as_padding(self, device, dtype):+ # every frame with a non-zero entry is filled, including the singular, non-finite and overflowing ones+ laf = self._degenerate_lafs(device, dtype)+ expected = torch.tensor([[True, True, True, False, True, True, True]], device=device)+ assert torch.equal(kornia.feature.laf_is_filled(laf), expected)++ def test_convention_kornia_check_laf_checks_the_shape_only(self, device, dtype):+ check = kornia.core.check.KORNIA_CHECK_LAF+ # any (B, N, 2, 3) tensor passes, whatever its values and dtype, including N = 0+ assert check(torch.full((1, 1, 2, 3), float("nan"), device=device, dtype=dtype)) is True+ assert check(torch.ones(1, 1, 2, 3, device=device, dtype=torch.int64)) is True+ assert check(torch.zeros(2, 0, 2, 3, device=device, dtype=dtype)) is True+ # a 3 x 3 homogeneous frame is not a LAF+ homogeneous = torch.eye(3, device=device, dtype=dtype).view(1, 1, 3, 3)+ with pytest.raises(ShapeError):+ check(homogeneous)+ assert check(homogeneous, raises=False) is False++ @pytest.mark.parametrize("extract", _EXTRACTORS)+ def test_convention_patch_cell_samples_the_laf_image_of_its_centre(self, extract, device, dtype):+ # Cell (i, j) of a PS x PS patch samples the image at c + A @ (u_j, u_i) with u_k = (2k + 1) / PS - 1: row 0 is+ # the patch's -y side (the top for an upright LAF), columns run along the patch x axis, and the cells tile the+ # square [-1, 1]^2 of the patch frame. On the x and y ramps a bilinear sample is that coordinate itself.+ h, w, ps = 40, 57, 7+ xs = torch.arange(w, dtype=torch.float64).expand(h, w)+ ys = torch.arange(h, dtype=torch.float64)[:, None].expand(h, w)+ img = torch.stack([xs, ys])[None].to(device, dtype)+ laf = self._lafs(self._SHEARED_IN_IMAGE, device, dtype)+ a = laf[0, 0].cpu().double() # the LAF as rounded to dtype+ u = (2.0 * torch.arange(ps, dtype=torch.float64) + 1.0) / ps - 1.0+ expected = torch.stack(+ [a[k, 2] + a[k, 0] * u[None, :] + a[k, 1] * u[:, None] for k in range(2)]+ ) # (x, y) of every cell+ patch = extract(img, laf, ps)[0, 0]+ self.assert_close(patch, expected.to(device, dtype))+ # relabelling: transposing the image (and so swapping the ramps) and the LAF transposes the patch+ patch_t = extract(img.transpose(-1, -2).flip(1), self._transposed(laf), ps)[0, 0]+ self.assert_close(patch_t.flip(0).transpose(-1, -2), patch)++ @pytest.mark.parametrize("extract", _EXTRACTORS)+ def test_convention_patch_cells_outside_the_image_read_the_nearest_border_pixel(self, extract, device, dtype):+ # Ramps offset by 10, so that zero padding or a reflection would show: a cell sampling (x, y) reads+ # 10 + clamp(x, 0, W - 1) and 10 + clamp(y, 0, H - 1). The two LAFs straddle the top-left and the bottom-right+ # corner.+ h, w, ps = 40, 57, 9+ xs = torch.arange(w, dtype=torch.float64).expand(h, w)+ ys = torch.arange(h, dtype=torch.float64)[:, None].expand(h, w)+ img = (torch.stack([xs, ys])[None] + 10.0).to(device, dtype)+ a = self._SHEARED[0][:2], self._SHEARED[1][:2]+ lafs = self._lafs([[[*a[0], 1.0], [*a[1], 2.0]], [[*a[0], 54.5], [*a[1], 37.0]]], device, dtype)+ u = (2.0 * torch.arange(ps, dtype=torch.float64) + 1.0) / ps - 1.0+ patches = extract(img, lafs, ps)[0]+ for n in range(2):+ m = lafs[0, n].cpu().double()+ x = (m[0, 2] + m[0, 0] * u[None, :] + m[0, 1] * u[:, None]).clamp(0.0, w - 1.0)+ y = (m[1, 2] + m[1, 0] * u[None, :] + m[1, 1] * u[:, None]).clamp(0.0, h - 1.0)+ self.assert_close(patches[n], (torch.stack([x, y]) + 10.0).to(device, dtype))++ def test_convention_pyramid_level_is_the_floor_of_log2_of_twice_the_scale_over_ps(self, device, dtype):+ # extract_patches_from_pyramid samples level floor(log2(2 s / PS)), s = sqrt(|det A|), clamped to the coarsest+ # level that still holds a PS x PS patch: 70 x 90, 35 x 45, 17 x 22 and 8 x 11 for PS = 8. The level read back+ # is the one whose plain extraction the patch matches; input pixel x is pixel (x + 0.5) W_l / W - 0.5 of+ # level l. The references go two levels deeper, to 4 x 5 and 2 x 2, so that a pyramid without the clamp shows.+ ps = 8+ ref_dtype = dtype if dtype in (torch.float32, torch.float64) else torch.float32+ g = torch.Generator().manual_seed(0)+ levels = [torch.rand(1, 1, 70, 90, generator=g, dtype=torch.float64).to(device, ref_dtype)]+ for _ in range(5):+ levels.append(kornia.geometry.transform.pyrdown(levels[-1]))+ t = math.radians(30.0)+ rot = torch.tensor([[math.cos(t), math.sin(t)], [-math.sin(t), math.cos(t)]], dtype=torch.float64)+ ratios = (1.9, 2.1, 3.9, 4.1, 8.4, 40.0) # 2 s / PS+ a = [r * ps / 2.0 * rot for r in ratios]+ # sqrt(det) gives 2 s / PS = 2.1 (level 1), while its axes alone, 33.6 and 2.1, would give levels 3 and 0+ a.append(torch.diag(torch.tensor([33.6, 2.1], dtype=torch.float64)) @ rot)+ centre = torch.tensor([[37.3], [30.6]], dtype=torch.float64)+ laf = torch.stack([torch.cat([m, centre], dim=1) for m in a])[None].to(device, ref_dtype)+ patches = kornia.feature.extract_patches_from_pyramid(levels[0].to(dtype), laf.to(dtype), ps).to(ref_dtype)+ misses = []+ for level in levels:+ sx, sy = level.shape[-1] / 90.0, level.shape[-2] / 70.0+ level_laf = laf.clone()+ level_laf[..., 0, :] *= sx+ level_laf[..., 1, :] *= sy+ level_laf[..., 0, 2] += 0.5 * sx - 0.5+ level_laf[..., 1, 2] += 0.5 * sy - 0.5+ plain = kornia.feature.extract_patches_simple(level, level_laf, ps)+ misses.append((patches - plain).abs().amax(dim=(-3, -2, -1)).flatten())+ assert torch.stack(misses).argmin(dim=0).tolist() == [0, 1, 1, 2, 3, 3, 1]++ @pytest.mark.parametrize("extract", _EXTRACTORS)+ def test_convention_unnormalized_extraction_takes_the_laf_in_normalize_laf_frame(self, extract, device, dtype):+ g = torch.Generator().manual_seed(0)+ img = torch.rand(1, 1, 40, 57, generator=g, dtype=torch.float64).to(device, dtype)+ laf = kornia.feature.scale_laf(self._lafs(self._SHEARED_IN_IMAGE, device, dtype), 4.0)+ expected = extract(img, laf, 16)+ # normalized in float32 for a half LAF, as the default path does, so that both read the same coordinates+ wide = laf.float() if dtype in (torch.float16, torch.bfloat16) else laf+ self.assert_close(extract(img, kornia.feature.normalize_laf(wide, img), 16, False), expected)+ # a pixel LAF passed with False is read as a normalized one and samples elsewhere+ assert (extract(img, laf, 16, False) - expected).abs().max().item() > 0.1++ def test_convention_get_laf_descriptors_converts_only_three_channel_images_to_gray(self, device, dtype):+ class _Recorder(torch.nn.Module):+ patch_size = 41 # a descriptor attribute get_laf_descriptors must not read++ def __init__(self):+ super().__init__()+ self.shapes = []++ def forward(self, patches):+ self.shapes.append(tuple(patches.shape))+ return patches.flatten(1)++ g = torch.Generator().manual_seed(0)+ lafs = self._lafs([self._SHEARED_IN_IMAGE, [[1.5, -2.598076211353316, 30.0], [2.6, 1.5, 22.0]]], device, dtype)+ # grayscale_descriptor=True converts an RGB image to one channel; with False the three channels pass through+ for channels, gray, seen in ((3, True, 1), (3, False, 3), (1, True, 1)):+ img = torch.rand(1, channels, 40, 57, generator=g, dtype=torch.float64).to(device, dtype)+ recorder = _Recorder()+ out = kornia.feature.get_laf_descriptors(img, lafs, recorder, 13, gray)+ assert recorder.shapes == [(2, seen, 13, 13)]+ assert out.shape == (1, 2, seen * 13 * 13)+ # the patch size is the argument, 32 by default, never read from the descriptor+ recorder = _Recorder()+ kornia.feature.get_laf_descriptors(img, lafs, recorder)+ assert recorder.shapes == [(2, 1, 32, 32)]++ def test_convention_laf_descriptor_defaults_to_pretrained_hardnet_on_32_pixel_gray_patches(+ self, device, dtype, monkeypatch+ ):+ # A stand-in records the arguments, so that no weights are loaded.+ made = []++ class _HardNetStub(torch.nn.Module):+ def __init__(self, pretrained: bool = False):+ super().__init__()+ made.append(pretrained)+ self.shapes = []++ def forward(self, patches):+ self.shapes.append(tuple(patches.shape))+ return patches.flatten(1)[:, :128]++ monkeypatch.setattr(kornia.feature.integrated, "HardNet", _HardNetStub)+ descriptor = kornia.feature.LAFDescriptor()+ assert made == [True]+ assert descriptor.patch_size == 32+ assert descriptor.grayscale_descriptor is True+ g = torch.Generator().manual_seed(0)+ img = torch.rand(1, 3, 40, 57, generator=g, dtype=torch.float64).to(device, dtype)+ laf = self._lafs(self._SHEARED_IN_IMAGE, device, dtype)+ assert descriptor(img, laf).shape == (1, 1, 128)+ assert descriptor.descriptor.shapes == [(1, 1, 32, 32)]