π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
docs(feature): convention blocks and pins for responses, detectors and orientation (#5835)
Dmytro Mishkin6ddd46103cd8
diff --git a/changelog.d/5835.added.md b/changelog.d/5835.added.mdnew file mode 100644index 000000000..239f282d5--- /dev/null+++ b/changelog.d/5835.added.md@@ -0,0 +1 @@+Document the conventions of the `kornia.feature` response functions, detectors, orientation and affine-shape estimators as Convention blocks and pointers: the sign and intensity scaling of each response, the candidates, frame and padding of `ScaleSpaceDetector`, the level-pixel frame of `MultiResolutionDetector`, the input range of `KeyNet`, the orientation sign, and the layout of the `PatchAffineShapeEstimator` output.diff --git a/kornia/feature/affine_shape.py b/kornia/feature/affine_shape.pyindex 18dccbf7f..3cebe044e 100644--- a/kornia/feature/affine_shape.py+++ b/kornia/feature/affine_shape.py@@ -53,6 +53,17 @@ class PatchAffineShapeEstimator(nn.Module):in float32.The output keeps the input dtype.+ Convention:+ - The output :math:`(a, b, c)` is :math:`(\langle g_x^2 \rangle, \langle g_x g_y \rangle,+ \langle g_y^2 \rangle)`, the means over the patch of the products of its Sobel gradients, x right and+ y down, each gradient weighted by a Gaussian centred on the patch. It is divided by its largest entry, which+ is therefore 1. When two of the three entries are below ``eps`` before that division -- a flat or+ low-contrast patch, or one whose gradient lies along an image axis -- the output is :math:`(1, 0, 1)`, a+ circle.+ - The patch must be ``patch_size`` pixels square.+ - Known defects: a negative :math:`b` counts as below ``eps``, so a patch and its mirror image can get a thin+ ellipse and a circle (`#5824 <https://github.com/kornia/kornia/issues/5824>`_).+Args:patch_size: the input image patch size.eps: for safe division.@@ -176,17 +187,21 @@ def _finalize_laf(class LAFAffineShapeEstimator(nn.Module):- """Module, which extracts patches using input images and local affine frames (LAFs).+ r"""Module, which extracts patches using input images and local affine frames (LAFs).Then runs :class:`~kornia.feature.PatchAffineShapeEstimator` on patches to estimate LAFs shape.- Each patch is sampled through the upright form of its LAF (:func:`~kornia.feature.make_upright`), so the shape- is estimated in the coordinates of that frame, and the output region is the frame composed with the estimated- shape. For an isotropic input LAF (a circle), that is the estimated shape itself. An input whose shape already- matches the local structure gives a nearly isotropic patch, so its shape changes little: one call is one step of- the iterative shape adaptation of :cite:`baumberg2000`. The centre and the scale of the input LAF are kept. With- ``preserve_orientation=True`` its orientation is kept too; otherwise the output is upright, and an orientation- estimator such as :class:`~kornia.feature.LAFOrienter` can be run after this module.+ Convention:+ - Each patch is sampled through the upright form of its LAF (:func:`~kornia.feature.make_upright`), so the+ shape is estimated in the coordinates of that frame, and the output region is the frame composed with the+ estimated shape. The estimated shape's ellipse :math:`A A^\top` is proportional to the inverse of the second+ moment matrix that ``affine_shape_detector`` returns. For an isotropic input LAF (a circle), the output shape+ is the estimated shape itself. An input whose shape already matches the local structure gives a nearly+ isotropic patch, so its shape changes little: one call is one step of the iterative shape adaptation of+ :cite:`baumberg2000`.+ - The centre and the scale of the input LAF are kept. With ``preserve_orientation=True`` (the default) its+ orientation is kept too; otherwise the output is upright, and an orientation estimator such as+ :class:`~kornia.feature.LAFOrienter` can be run after this module.Args:patch_size: the input image patch size.@@ -258,11 +273,10 @@ class LAFAffNetShapeEstimator(nn.Module):"Repeatability Is Not Enough: Learning Discriminative Affine Regions via Discriminability"".See :cite:`AffNet2018` for more details.- Each patch is sampled through the upright form of its LAF (:func:`~kornia.feature.make_upright`), so AffNet- predicts the shape in the coordinates of that frame, and the output region is the frame composed with the- prediction. For an isotropic input LAF (a circle), that is the predicted shape itself. The centre and the scale of- the input LAF are kept. With ``preserve_orientation=True`` its orientation is kept too; otherwise the output is- upright, and an orientation estimator such as :class:`~kornia.feature.LAFOrienter` can be run after this module.+ Convention:+ As :class:`~kornia.feature.LAFAffineShapeEstimator`, with AffNet's prediction on a 32 x 32 patch in place of+ the second moment estimate; see its Convention block for the frame the patch is sampled through and for what+ the output keeps of the input LAF.Args:pretrained: Download and set pretrained weights to the model.diff --git a/kornia/feature/keynet.py b/kornia/feature/keynet.pyindex dc94edc6d..796e7e902 100644--- a/kornia/feature/keynet.py+++ b/kornia/feature/keynet.py@@ -144,9 +144,15 @@ class KeyNet(nn.Module):.. image:: _static/img/KeyNet.png+ Convention:+ - The input is a grayscale image, and the pretrained weights expect it in ``[0, 1]``, as the Key.Net+ reference scales its images. The response is not proportional to the intensity, so an image in+ ``[0, 255]`` gives other detections.+ - The response is a non-negative map of the input's size.+Args:pretrained: Download and set pretrained weights to the model.- keynet_conf: Dict with initialization parameters. Do not pass it, unless you know what you are doing`.+ keynet_conf: Dict with initialization parameters. Do not pass it, unless you know what you are doing.Returns:KeyNet response score.@@ -201,10 +207,14 @@ class KeyNetDetector(MultiResolutionDetector):.. image:: _static/img/keynet.jpg+ Convention:+ A :class:`~kornia.feature.MultiResolutionDetector` with :class:`~kornia.feature.KeyNet` as its response; see+ their Convention blocks for the frame of the detections and for the input range.+Args:pretrained: Download and set pretrained weights to the model.num_features: Number of features to detect.- keynet_conf: Dict with initialization parameters. Do not pass it, unless you know what you are doing`.+ keynet_conf: Dict with initialization parameters. Do not pass it, unless you know what you are doing.ori_module: for local feature orientation estimation. Default: :class:`~kornia.feature.PassLAF`,which does nothing. See :class:`~kornia.feature.LAFOrienter` for details.aff_module: for local feature affine shape estimation. Default: :class:`~kornia.feature.PassLAF`,diff --git a/kornia/feature/orientation.py b/kornia/feature/orientation.pyindex 566f0c467..894271311 100644--- a/kornia/feature/orientation.py+++ b/kornia/feature/orientation.py@@ -38,14 +38,18 @@ urls["orinet"] = [class PassLAF(nn.Module):- """Dummy module to use instead of local feature orientation or affine shape estimator."""+ """Dummy module to use instead of local feature orientation or affine shape estimator.++ Convention:+ Returns its ``laf`` argument itself, not a copy, and does not use ``img``.+ """def forward(self, laf: torch.Tensor, img: torch.Tensor) -> torch.Tensor:"""Run forward.Args:laf: :math:`(B, N, 2, 3)`- img: :math:`(B, 1, H, W)`+ img: not used.Returns:LAF, unchanged :math:`(B, N, 2, 3)`@@ -55,10 +59,18 @@ class PassLAF(nn.Module):class PatchDominantGradientOrientation(nn.Module):- """Module, which estimates the dominant gradient orientation of the given patches, in radians.+ r"""Module, which estimates the direction of the dominant gradient of the given patches, as an angle in radians.Zero angle points towards right.+ Convention:+ - The angle is that of the dominant gradient, which points toward brighter values, counter-clockwise on+ screen with image y pointing down: :math:`-\operatorname{atan2}(g_y, g_x)` in pixel coordinates. A gradient+ pointing down the patch gives :math:`-\pi / 2`. :class:`~kornia.feature.LAFOrienter` adds the angle to the+ LAF orientation.+ - The angle is not wrapped into :math:`(-\pi, \pi]`: it can exceed :math:`\pi` by up to+ ``pi / num_angular_bins``.+Args:patch_size: size of the (square) input patch.num_angular_bins: number of histogram bins.@@ -188,6 +200,15 @@ class OriNet(nn.Module):"Repeatability Is Not Enough: Learning Discriminative Affine Regions via Discriminability"".See :cite:`AffNet2018` for more details.+ Convention:+ - With the pretrained weights, the angle turns with the patch content, in the sense of+ :class:`~kornia.feature.PatchDominantGradientOrientation`: content turned counter-clockwise on screen+ increases the angle. See :class:`~kornia.feature.LAFOrienter` for its use.+ - Each patch is normalised first: its mean is subtracted and the result is divided by its standard deviation+ plus ``1e-6``. An offset of its intensity therefore does not change the angle, and a positive gain changes it+ only through that ``1e-6``: little on a textured patch, more as the patch flattens, up to ``pi`` rad on a+ nearly flat one. An inverted patch generally gets a different angle.+Args:pretrained: Download and set pretrained weights to the model.eps: to avoid division by zero in atan2.@@ -270,9 +291,20 @@ class LAFOrienter(nn.Module):Then runs :class:`~kornia.feature.PatchDominantGradientOrientation` or:class:`~kornia.feature.OriNet` on patches and then rotates the LAFs by the estimated angles+ Convention:+ - Each LAF's patch (:func:`~kornia.feature.extract_patches_from_pyramid`) gives an angle, measured in the+ patch, and the output orientation is the input orientation plus that angle, converted to degrees, modulo+ 360 degrees. :func:`~kornia.feature.get_laf_orientation` reads it back in ``[-180, 180]``. The centre, the+ scale and the upright shape (:func:`~kornia.feature.make_upright`) of the LAF are kept.+ - For an isotropic LAF, the default angle detector therefore turns the LAF's x axis onto the dominant+ gradient, whatever the input orientation: content turned 30 degrees counter-clockwise on screen turns the+ output orientation by +30, the sign of :func:`~kornia.feature.laf_from_center_scale_ori`+ (see :ref:`Local features <local-features-conventions>`).+Args:- patch_size:- num_angular_bins:+ patch_size: side of the square patch sampled for each LAF.+ num_angular_bins: number of histogram bins of the default angle detector; not used when ``angle_detector``+ is given.angle_detector: Patch orientation estimator, e.g. :class:`~kornia.feature.PatchDominantGradientOrientation`or OriNet.diff --git a/kornia/feature/responses.py b/kornia/feature/responses.pyindex 571af9416..a1bc3d6e8 100644--- a/kornia/feature/responses.py+++ b/kornia/feature/responses.py@@ -46,30 +46,41 @@ def harris_response(.. image:: _static/img/harris_response.png- Function does not do any normalization or nms. The response map is computed according the following formulation:+ The function does no non-maxima suppression. The response map is computed according to the following+ formulation:.. math::- R = max(0, det(M) - k \cdot trace(M)^2)+ R = det(M) - k \cdot trace(M)^2- where:+ where :math:`w` are the weights of a window :math:`W`:.. math::- M = \sum_{(x,y) \in W}+ M = \sum_{(x,y) \in W} w(x, y)\begin{bmatrix}I^{2}_x & I_x I_y \\I_x I_y & I^{2}_y \\\end{bmatrix}- and :math:`k` is an empirically determined constant- :math:`k β [ 0.04 , 0.06 ]`+ and :math:`k` is an empirically determined constant, usually in :math:`[0.04, 0.06]`.++ Convention:+ - :math:`R` is signed and not clamped: positive at a corner, negative along an edge.+ - :math:`I_x` and :math:`I_y` come from :func:`~kornia.filters.spatial_gradient` with ``mode=grads_mode``,+ in intensity per pixel for both modes, and :math:`W` is a :math:`7 \times 7` Gaussian window of+ :math:`\sigma = 1` whose weights sum to one. A linear ramp of gradient :math:`g` therefore gives+ :math:`R = -k \|g\|^4` away from the border.+ - Apart from ``sigmas``, the response depends on the image's intensity scale: multiplying the image by ``c``+ multiplies the response by ``c ** 4``, and an offset does not change it, so a threshold tuned on images in+ ``[0, 1]`` does not carry over to ``[0, 255]``.+ - ``k`` is not validated.Args:input: input image with shape :math:`(B, C, H, W)`.k: the Harris detector free parameter.grads_mode: can be ``'sobel'`` for standalone use or ``'diff'`` for use on Gaussian pyramid.- sigmas: coefficients to be multiplied by multichannel response. Should be shape of :math:`(B)`- It is necessary for performing non-maxima-suppression across different scale pyramid levels.- See `vlfeat <https://github.com/vlfeat/vlfeat/blob/master/vl/covdet.c#L874>`_.+ sigmas: per-image scales with shape :math:`(B)`. The response of image ``b`` is multiplied by+ ``sigmas[b] ** 4``, so that non-maxima suppression can compare the levels of a scale pyramid, as in+ `vlfeat <https://github.com/vlfeat/vlfeat/blob/master/vl/covdet.c>`_.Return:the response map per channel with shape :math:`(B, C, H, W)`.@@ -132,26 +143,29 @@ def gftt_response(.. image:: _static/img/gftt_response.png- Function does not do any normalization or nms. The response map is computed according the following formulation:+ The function does no non-maxima suppression. The response map is computed according to the following+ formulation:.. math::R = min(eig(M))- where:+ where :math:`M` is the windowed structure tensor of :func:`~kornia.feature.harris_response`, with the same+ gradients and window.- .. math::- M = \sum_{(x,y) \in W}- \begin{bmatrix}- I^{2}_x & I_x I_y \\- I_x I_y & I^{2}_y \\- \end{bmatrix}+ Convention:+ - :math:`R` is not negative, up to roundoff. It is large at a corner and near zero along an edge, where the+ Harris response is negative.+ - Multiplying the image by ``c`` multiplies the response by ``c ** 2``, and an offset does not change it.+ - ``sigmas`` multiplies the response by ``sigmas ** 4``, the same power used by+ :func:`~kornia.feature.harris_response`. This is the function's scale-weighting convention, not a guarantee+ of scale invariance. The integration window :math:`W` stays fixed as the image blur changes; the response's+ decay with blur depends on the image structure, including the corner geometry.Args:input: input image with shape :math:`(B, C, H, W)`.grads_mode: can be ``'sobel'`` for standalone use or ``'diff'`` for use on Gaussian pyramid.- sigmas: coefficients to be multiplied by multichannel response. Should be shape of :math:`(B)`- It is necessary for performing non-maxima-suppression across different scale pyramid levels.- See `vlfeat <https://github.com/vlfeat/vlfeat/blob/master/vl/covdet.c#L874>`_.+ sigmas: per-image scales with shape :math:`(B)`. The response of image ``b`` is multiplied by+ ``sigmas[b] ** 4``, so that non-maxima suppression can compare the levels of a scale pyramid.Return:the response map per channel with shape :math:`(B, C, H, W)`.@@ -212,11 +226,12 @@ def gftt_response(def hessian_response(input: torch.Tensor, grads_mode: str = "sobel", sigmas: Optional[torch.Tensor] = None) -> torch.Tensor:- r"""Compute the absolute of determinant of the Hessian matrix.+ r"""Compute the determinant of the Hessian matrix... image:: _static/img/hessian_response.png- Function does not do any normalization or nms. The response map is computed according the following formulation:+ The function does no non-maxima suppression. The response map is computed according to the following+ formulation:.. math::R = det(H)@@ -224,18 +239,23 @@ def hessian_response(where:.. math::- M = \sum_{(x,y) \in W}+ H =\begin{bmatrix}I_{xx} & I_{xy} \\I_{xy} & I_{yy} \\\end{bmatrix}+ Convention:+ - :math:`R = I_{xx} I_{yy} - I_{xy}^2` is signed and pointwise, without a window: positive at bright and dark+ blobs alike, negative at a saddle. The second derivatives come from+ :func:`~kornia.filters.spatial_gradient` with ``mode=grads_mode`` and ``order=2``.+ - Multiplying the image by ``c`` multiplies the response by ``c ** 2``, and an offset does not change it.+Args:input: input image with shape :math:`(B, C, H, W)`.grads_mode: can be ``'sobel'`` for standalone use or ``'diff'`` for use on Gaussian pyramid.- sigmas: coefficients to be multiplied by multichannel response. Should be shape of :math:`(B)`- It is necessary for performing non-maxima-suppression across different scale pyramid levels.- See `vlfeat <https://github.com/vlfeat/vlfeat/blob/master/vl/covdet.c#L874>`_.+ sigmas: per-image scales with shape :math:`(B)`. The response of image ``b`` is multiplied by+ ``sigmas[b] ** 4``, so that non-maxima suppression can compare the levels of a scale pyramid.Return:the response map per channel with shape :math:`(B, C, H, W)`.@@ -290,6 +310,11 @@ def hessian_response(def dog_response(input: torch.Tensor) -> torch.Tensor:r"""Compute the Difference-of-Gaussian response.+ Convention:+ - Output level ``i`` is ``input[:, :, i + 1] - input[:, :, i]`` along the level axis ``D`` (dim 2), so ``D``+ levels give ``D - 1``. For a stack blurred from fine to coarse, this is Lowe's+ :math:`L(k\sigma) - L(\sigma)`: negative at a bright blob, positive at a dark one.+Args:input: a given the gaussian 5d torch.Tensor :math:`(B, C, D, H, W)`.@@ -307,6 +332,12 @@ def dog_response_single(input: torch.Tensor, sigma1: float = 1.0, sigma2: float.. image:: _static/img/dog_response_single.png+ Convention:+ - Returns the Gaussian blur of ``sigma2`` minus that of ``sigma1``, the order of+ :func:`~kornia.feature.dog_response`; see its Convention block. Each kernel has the size+ ``int(8 * sigma + 1)``, rounded up to an odd number. The order of ``sigma1`` and ``sigma2`` is not checked:+ swapping them flips the sign.+Args:input: a given the gaussian 4d torch.Tensor :math:`(B, C, H, W)`.sigma1: lower gaussian sigma@@ -327,8 +358,9 @@ def dog_response_single(input: torch.Tensor, sigma1: float = 1.0, sigma2: floatclass BlobDoG(nn.Module):r"""nn.Module that calculates Difference-of-Gaussians blobs.- See- :func: `~kornia.feature.dog_response` for details.+ Convention:+ Returns :func:`~kornia.feature.dog_response` of the :math:`(B, C, D, H, W)` scale stack; see its Convention+ block. ``sigmas`` is ignored."""def __init__(self) -> None:@@ -341,7 +373,7 @@ class BlobDoG(nn.Module):"""Compute Difference-of-Gaussians response maps.Args:- input: Input tensor of shape :math:`(B, C, H, W)`.+ input: Input scale stack of shape :math:`(B, C, D, H, W)`.sigmas: Unused in this wrapper; kept for API compatibility.Returns:@@ -355,7 +387,9 @@ class BlobDoGSingle(nn.Module):.. image:: _static/img/dog_response_single.png- See :func:`~kornia.feature.dog_response_single` for details.+ Convention:+ Returns :func:`~kornia.feature.dog_response_single` with the constructor's ``sigma1`` and ``sigma2``; see its+ Convention block. ``sigmas`` is ignored."""def __init__(self, sigma1: float = 1.0, sigma2: float = 1.6) -> None:@@ -385,7 +419,9 @@ class CornerHarris(nn.Module):.. image:: _static/img/harris_response.png- See :func:`~kornia.feature.harris_response` for details.+ Convention:+ Returns :func:`~kornia.feature.harris_response` with the constructor's ``k`` and ``grads_mode``; see its+ Convention block. Unlike the function's, this ``k`` has no default."""k: torch.Tensor@@ -406,8 +442,8 @@ class CornerHarris(nn.Module):Args:input: Input tensor of shape :math:`(B, C, H, W)`.- sigmas: Optional Gaussian smoothing values forwarded to- :func:`harris_response`.+ sigmas: Optional per-image scales forwarded to :func:`harris_response`, which multiplies the+ response by ``sigmas ** 4``.Returns:Harris response map tensor.@@ -420,7 +456,8 @@ class CornerGFTT(nn.Module):.. image:: _static/img/gftt_response.png- See :func:`~kornia.feature.gftt_response` for details.+ Convention:+ Returns :func:`~kornia.feature.gftt_response` with the constructor's ``grads_mode``; see its Convention block."""def __init__(self, grads_mode: str = "sobel") -> None:@@ -435,7 +472,8 @@ class CornerGFTT(nn.Module):Args:input: Input tensor of shape :math:`(B, C, H, W)`.- sigmas: Optional smoothing sigmas for multi-scale workflows.+ sigmas: Optional per-image scales forwarded to :func:`gftt_response`, which multiplies the+ response by ``sigmas ** 4``.Returns:GFTT response map tensor from :func:`gftt_response`.@@ -448,7 +486,9 @@ class BlobHessian(nn.Module):.. image:: _static/img/hessian_response.png- See :func:`~kornia.feature.hessian_response` for details.+ Convention:+ Returns :func:`~kornia.feature.hessian_response` with the constructor's ``grads_mode``; see its Convention+ block."""def __init__(self, grads_mode: str = "sobel") -> None:@@ -463,8 +503,8 @@ class BlobHessian(nn.Module):Args:input: Input tensor of shape :math:`(B, C, H, W)`.- sigmas: Optional smoothing values passed to- :func:`hessian_response`.+ sigmas: Optional per-image scales forwarded to :func:`hessian_response`, which multiplies the+ response by ``sigmas ** 4``.Returns:Hessian response map tensor.diff --git a/kornia/feature/scale_space_detector.py b/kornia/feature/scale_space_detector.pyindex 8c89214a7..3eb67753f 100644--- a/kornia/feature/scale_space_detector.py+++ b/kornia/feature/scale_space_detector.py@@ -202,19 +202,41 @@ def _subpix_dispatch(module: nn.Module) -> Tuple[bool, bool]:class ScaleSpaceDetector(nn.Module):r"""nn.Module for differentiable local feature detection.- As close as possible to classical local feature detectors- like Harris, Hessian-Affine or SIFT (DoG).-It has 5 modules inside: scale pyramid generator, response ("cornerness") function,sub-pixel localization, affine shape estimator and patch orientation estimator.Each of those modules could be replaced with a learned custom one, as long asthey respect output shape.+ Convention:+ - The candidates are the strict :math:`3 \times 3 \times 3` maxima of the response over level, row and column+ (:func:`~kornia.geometry.subpix.nms3d_minmax`) on the levels given under ``scale_pyr_module``, whatever their+ sign. With ``minima_are_also_good`` a strict minimum is a candidate too when its negated response after+ sub-pixel refinement exceeds the response the maxima pass reports at that voxel, which the built-in refiners+ leave at its sampled value: in effect every minimum below zero, and a minimum above zero only when the+ refinement extrapolates it below minus its sampled value. There is no response threshold. The+ ``num_features`` strongest candidates of all octaves are kept; a minimum is ranked and returned with its+ refined response negated.+ - The default Hessian response is a maximum at bright and dark blobs alike. A DoG response+ (:class:`~kornia.feature.BlobDoG`) is a maximum at a dark blob and a minimum at a bright one, which only+ ``minima_are_also_good=True`` detects.+ - A LAF centre is the refined sub-pixel position, mapped to input pixels as given under+ ``scale_pyr_module``, in the frame of :func:`~kornia.feature.laf_from_center_scale_ori`+ (see :ref:`Local features <local-features-conventions>`). Before ``aff_module`` and ``ori_module`` run, the+ frame is diagonal: ``mr_size`` times the detection scale, mapped to input pixels along each axis like the+ centre.+ - A candidate is kept when half its frame lies at least 5 octave pixels inside the octave's outer pixel+ centres; the whole frame can reach outside the image.+ - The output has ``num_features`` slots: the detections by decreasing response, then the unfilled slots, which+ hold a zero response and a zero LAF.+ - Known defects: an octave passes only its ``num_features`` strongest candidates to the border test and to the+ mask check of their refined centres, so the slot of a candidate rejected there stays empty even when a+ weaker valid candidate exists (`#5741 <https://github.com/kornia/kornia/issues/5741>`_).+Args:num_features: Number of features to detect. In order to keep everything batchable,output would always have num_features output, even for completely homogeneous images.- mr_size: multiplier for local feature scale compared to the detection scale.- 6.0 is matching OpenCV 12.0 convention for SIFT.+ mr_size: multiplier from the detection scale to the LAF scale. The default 6.0 gives a frame of about six+ times the :math:`\sigma` of a detected Gaussian blob.scale_pyr_module: generates scale pyramid. See :class:`~kornia.geometry.ScalePyramid` for details.Default: ``ScalePyramid(3, 1.6, 16, extra_levels=3)`` with a scale-space response,``extra_levels=2`` without. A detection at octave pixel :math:`(u, v)` is reported at@@ -224,23 +246,29 @@ class ScaleSpaceDetector(nn.Module):``1..n_levels``; the levels below and above them are NMS neighbours only, and any furtherlevel is ignored. A per-level response therefore needs ``extra_levels >= 2``, and DoG,which has one level fewer than its pyramid, ``extra_levels >= 3``.- resp_module: calculates ``'cornerness'`` of the pixel.- subpix_module: performs non-maximum suppression and refines keypoint location to sub-pixel /- sub-scale accuracy. See :class:`~kornia.geometry.subpix.ConvQuadInterp3d` for details.- ori_module: for local feature orientation estimation. Default:class:`~kornia.feature.PassLAF`,+ resp_module: calculates ``'cornerness'`` of the pixel. Default: :class:`~kornia.feature.BlobHessian`.+ subpix_module: refines the position and scale of each candidate to sub-pixel / sub-scale accuracy. The+ candidates are those of the Convention block, whatever the module. Default:+ :class:`~kornia.geometry.subpix.AdaptiveQuadInterp3d` with ``allow_scale_steps=True``.+ ori_module: for local feature orientation estimation. Default: :class:`~kornia.feature.PassLAF`,which does nothing. See :class:`~kornia.feature.LAFOrienter` for details.aff_module: for local feature affine shape estimation. Default: :class:`~kornia.feature.PassLAF`,which does nothing. See :class:`~kornia.feature.LAFAffineShapeEstimator` for details.minima_are_also_good: if True, then both response function minima and maxima are detected.- Useful for symmetric response functions like DoG or Hessian. Default is False.+ A DoG response needs it to detect bright blobs. Default is False.With a built-in ``subpix_module`` both signs are refined in one stacked call, whichroughly doubles the peak memory of the refinement step: the response volume and itsthree coordinate maps are materialised for ``2B`` images at once.+ scale_space_response: if True, ``resp_module`` gets each whole octave :math:`(B, C, L, H, W)` with its+ sigmas :math:`(B \cdot L)` and returns a :math:`(B, 1, L', H, W)` scale-space response, as+ :class:`~kornia.feature.BlobDoG` does. If False (the default), it gets the octave's levels+ ``0 .. n_levels + 1`` as :math:`(B \cdot L, C, H, W)` images, :math:`L = n_{levels} + 2`, with their sigmas+ and returns :math:`(B \cdot L, 1, H, W)`.compile_modules: selects which sub-modules to wrap with :func:`torch.compile`.Pass ``True`` to compile every sub-module, ``False`` (default) for none, or a listcontaining any subset of ``["scale_pyr", "resp", "subpix", "ori", "aff"]``.- Compiling ``subpix`` gives ~5x GPU speedup for the default- :class:`~kornia.geometry.subpix.ConvQuadInterp3d` backend by fusing its iteration loop.+ Compiling ``subpix`` fuses the iteration loop of :func:`~kornia.geometry.subpix.conv_quad_interp3d`, which+ the default :class:`~kornia.geometry.subpix.AdaptiveQuadInterp3d` runs on CUDA.The first call incurs a one-time compilation cost; subsequent calls are fast."""@@ -659,8 +687,8 @@ class ScaleSpaceDetector(nn.Module):Returns:Tuple containing detection scores and local affine frames, shaped `(B, num_feats)` and `(B, num_feats,- 2, 3)`. A slot that no detection filled -- there were fewer candidates than requested, or a candidate's- frame reached outside the image -- carries a zero response and a zero LAF, and sorts after every real+ 2, 3)`. A slot that no detection filled -- there were fewer candidates than requested, or the border or+ mask test rejected a candidate -- carries a zero response and a zero LAF, and sorts after every realdetection. The converse does not hold: a signed response function can peak at exactly zero, and thatslot keeps its frame."""@@ -718,7 +746,7 @@ def get_default_detector_config() -> Detector_config:class MultiResolutionDetector(nn.Module):- """Multi-scale feature detector, based on code from KeyNet. Can be used with any response function.+ """Multi-scale feature detector, based on KeyNet, for a response function that returns one map of its input's size.This is based on the original code from paper"Key.Net: Keypoint Detection by Handcrafted and Learned CNN Filters".@@ -729,8 +757,17 @@ class MultiResolutionDetector(nn.Module):detector suppresses on the whole response and removes the strip from the suppression output instead;see :meth:`detect_features_on_single_level`.- Detections are maxima of the response. For a signed response whose minima are features as well, such as a- difference of Gaussians, pass its magnitude, as :class:`~kornia.feature.SIFTFeature` does.+ Convention:+ - Detections are maxima of the response above ``score_threshold``. For a signed response whose minima are+ features as well, such as a difference of Gaussians, pass its magnitude, as+ :class:`~kornia.feature.SIFTFeature` does.+ - A detection is an integer pixel :math:`(u, v)` of a pyramid level of size :math:`(H_l, W_l)`, without a+ sub-pixel step. It is reported at :math:`(u W / W_l, v H / H_l)` of the :math:`(H, W)` input, in the frame+ of :func:`~kornia.feature.laf_from_center_scale_ori` (see :ref:`Local features <local-features-conventions>`),+ and not at the level pixel's centre :math:`((u + 0.5) W / W_l - 0.5, (v + 0.5) H / H_l - 0.5)`; the Key.Net+ reference maps it the same way.+ - Before ``aff_module`` and ``ori_module`` run, the frame is upright and isotropic, with the scale+ ``s_mult * (W / W_l + H / H_l) / 2`` whatever the response; ``s_mult`` of ``config`` is 22 by default.Args:model: response function, such as KeyNet or BlobHessian@@ -740,7 +777,7 @@ class MultiResolutionDetector(nn.Module):of the vector for any larger one. Which detection carries a given response is not pinnedwhen responses tie: ``topk`` breaks a tie by position, and the positions it ranks overdepend on ``num_features``.- conf: Dict with initialization parameters. Do not pass it, unless you know what you are doing`.+ config: Dict with initialization parameters. Do not pass it, unless you know what you are doing.ori_module: for local feature orientation estimation. Default: :class:`~kornia.feature.PassLAF`,which does nothing. See :class:`~kornia.feature.LAFOrienter` for details.aff_module: for local feature affine shape estimation. Default: :class:`~kornia.feature.PassLAF`,@@ -832,8 +869,8 @@ class MultiResolutionDetector(nn.Module):Args:level_img: Image tensor for a single pyramid level.num_kp: Number of keypoints requested from this pyramid level.- factor: Scale factor mapping coordinates from the current pyramid level back to the original image- resolution.+ factor: Per-axis factor ``(W / W_l, H / H_l)`` from the current pyramid level to the original image:+ level pixel :math:`(u, v)` is reported at ``(u * factor[0], v * factor[1])``.mask: Optional mask with shape :math:`(1, 1, H, W)` at the *original* image resolution, saying where adetection may be. It is resampled onto this level conservatively and applied to the non-maximasuppression output, so a zero region drops every maximum within one level pixel of it and a@@ -933,8 +970,7 @@ class MultiResolutionDetector(nn.Module):response, descending. The shape holds even when the image yields fewer above-threshold maximathan requested: those slots carry a zero response and a zero LAF, and sort after every real detection.LAF centres are pixel coordinates cast to the image dtype, so a half-precision image gives centres at- that dtype's integer resolution: exact up to 256 in bfloat16 and up to 2048 in float16, and coarser- beyond.+ that dtype's integer resolution."""KORNIA_CHECK_SHAPE(img, ["1", "C", "H", "W"])if mask is not None:@@ -1006,8 +1042,7 @@ class MultiResolutionDetector(nn.Module):Then affine shape and orientation.Args:- img: image to extract features with shape [1xCxHxW]. KeyNetDetector does not support batch processing,- because the number of detections is different on each image.+ img: image to extract features with shape [1xCxHxW]. Only a batch of one image is accepted.mask: a mask saying where a detection may be, shape [1x1xHxW]. A boolean or integer mask is binary, afloating-point mask weights the detection scores; see :meth:`detect`.diff --git a/tests/feature/test_affine_shape_estimator.py b/tests/feature/test_affine_shape_estimator.pyindex a42c448fa..4f1256967 100644--- a/tests/feature/test_affine_shape_estimator.py+++ b/tests/feature/test_affine_shape_estimator.py@@ -622,3 +622,34 @@ class TestLAFAffNetShapeEstimator(BaseTester):self.assert_close(out[..., 2], laf[..., 2])actual_scale, expected_scale = get_laf_scale(out.cpu().double()), get_laf_scale(laf.cpu().double())self.assert_close(actual_scale, expected_scale, rtol=_SCALE_RTOL[dtype], atol=0.0)+++class TestConventionsAffineShape(BaseTester):+ def test_convention_patch_affine_shape_is_the_normalised_gradient_second_moment(self, device, dtype):+ # The output (a, b, c) is (<gx^2>, <gx gy>, <gy^2>) of the Gaussian-weighted patch gradients (x right, y down),+ # divided by its largest entry. On the ramp I = x / 4 - y / 8 the gradient is (1/4, -1/8), so (a, b, c) is+ # (1, -1/2, 1/4) up to the replicate-padded border rows and columns: (1.0, -0.4903902, 0.25), CPU float64.+ # The ramp is exact in every dtype.+ yy, xx = torch.meshgrid(+ torch.arange(19, dtype=torch.float64), torch.arange(19, dtype=torch.float64), indexing="ij"+ )+ patch = (0.25 * xx - 0.125 * yy).view(1, 1, 19, 19).to(device, dtype)+ estimator = PatchAffineShapeEstimator(19).to(device, dtype)+ expected = torch.tensor([[[1.0, -0.4903902, 0.25]]], device=device, dtype=dtype)+ self.assert_close(estimator(patch), expected)+ # relabelling: the transposed patch swaps a and c and keeps b+ self.assert_close(estimator(patch.transpose(-1, -2)), expected.flip(-1))++ def test_wart_patch_affine_shape_counts_a_negative_b_as_below_eps_5824(self, device, dtype):+ # The degeneracy test counts the entries below eps with their sign, so a negative b always counts (#5824). The+ # ramp 0.25 x + 1e-3 y gives the thin ellipse (1, +0.0039, 1.6e-5) (CPU float64), while its vertical mirror+ # 0.25 x - 1e-3 y, whose b is negative, gives the circle (1, 0, 1) instead of (1, -0.0039, 1.6e-5).+ yy, xx = torch.meshgrid(+ torch.arange(19, dtype=torch.float64), torch.arange(19, dtype=torch.float64), indexing="ij"+ )+ estimator = PatchAffineShapeEstimator(19).to(device, dtype)+ shape = estimator((0.25 * xx + 1e-3 * yy).view(1, 1, 19, 19).to(device, dtype))[0, 0]+ mirror = estimator((0.25 * xx - 1e-3 * yy).view(1, 1, 19, 19).to(device, dtype))[0, 0]+ assert shape[1] > 0+ assert shape[2] < 1e-3+ self.assert_close(mirror, torch.tensor([1.0, 0.0, 1.0], device=device, dtype=dtype), rtol=0.0, atol=0.0)diff --git a/tests/feature/test_keynet.py b/tests/feature/test_keynet.pyindex 96b4f2de4..c30556bd7 100644--- a/tests/feature/test_keynet.py+++ b/tests/feature/test_keynet.py@@ -15,11 +15,19 @@# limitations under the License.#+import pytestimport torchfrom kornia.feature import KeyNet-from testing.base import BaseTester+from testing.base import BaseTester, supports_reflect_padding, supports_replicate_padding+++def _skip_without_half_padding(device: torch.device, dtype: torch.dtype) -> None:+ # torch 2.5.1 has no float16 CPU reflection_pad2d or replication_pad2d; these pins blur (reflect) and take+ # gradients (replicate).+ if not (supports_reflect_padding(device, dtype) and supports_replicate_padding(device, dtype)):+ pytest.skip(f"no reflection or replication padding kernel for {dtype} on {device.type}")class TestKeyNet(BaseTester):@@ -44,3 +52,23 @@ class TestKeyNet(BaseTester):patches = torch.rand(2, 1, 16, 16, device=device, dtype=torch.float64)keynet = KeyNet().to(patches.device, patches.dtype)self.gradcheck(keynet, (patches,), eps=1e-4, atol=1e-4, nondet_tol=1e-8)+++class TestConventionsKeyNet(BaseTester):+ def test_convention_keynet_response_is_non_negative_at_the_input_size(self, device, dtype):+ # KeyNet ends in a ReLU and resamples every pyramid level's features, so the response is a non-negative+ # (B, 1, H, W) map at the input size, also for an odd, non-square size. With the random+ # weights of seed 0 and the last bias set to -0.01, the last pre-activation spans [-0.014, 0.013] (CPU float64),+ # so the ReLU clips about a tenth of the map and the bound below is not met by an all-zero map.+ _skip_without_half_padding(device, dtype)+ with torch.random.fork_rng(devices=[]):+ torch.manual_seed(0)+ model = KeyNet()+ with torch.no_grad():+ model.last_conv[0].bias.fill_(-0.01)+ img = torch.rand(2, 1, 37, 53, generator=torch.Generator().manual_seed(0)).to(device, dtype)+ out = model.to(device, dtype)(img)+ assert out.shape == (2, 1, 37, 53)+ assert bool((out >= 0).all())+ assert bool((out == 0).any())+ assert bool((out > 0).any())diff --git a/tests/feature/test_local_features_orientation.py b/tests/feature/test_local_features_orientation.pyindex 78dc28c1e..91d9cd7f5 100644--- a/tests/feature/test_local_features_orientation.py+++ b/tests/feature/test_local_features_orientation.py@@ -15,13 +15,23 @@# limitations under the License.#+import math+import pytestimport torch+import korniafrom kornia.feature.orientation import LAFOrienter, OriNet, PassLAF, PatchDominantGradientOrientationfrom kornia.geometry.conversions import rad2deg-from testing.base import BaseTester, supports_replicate_padding+from testing.base import BaseTester, supports_reflect_padding, supports_replicate_padding+++def _skip_without_half_padding(device: torch.device, dtype: torch.dtype) -> None:+ # torch 2.5.1 has no float16 CPU reflection_pad2d or replication_pad2d; these pins blur (reflect) and take+ # gradients (replicate).+ if not (supports_reflect_padding(device, dtype) and supports_replicate_padding(device, dtype)):+ pytest.skip(f"no reflection or replication padding kernel for {dtype} on {device.type}")class TestPassLAF(BaseTester):@@ -349,3 +359,101 @@ class TestLAFOrienter(BaseTester):laf[:, :, 0, 1] = 0laf[:, :, 1, 0] = 0self.gradcheck(LAFOrienter(8).to(device), (laf, patches), rtol=1e-3, atol=1e-3, nondet_tol=1e-3)+++def _conv_ramp(angle: float, height: int, width: int, x0: float, y0: float) -> torch.Tensor:+ """Float64 CPU ramp through ``(x0, y0)`` whose gradient is ``angle`` degrees counter-clockwise from +x on screen.++ With y pointing down that direction is ``(cos angle, -sin angle)`` in pixel coordinates.+ """+ yy, xx = torch.meshgrid(+ torch.arange(height, dtype=torch.float64), torch.arange(width, dtype=torch.float64), indexing="ij"+ )+ t = math.radians(angle)+ return (0.05 * (math.cos(t) * (xx - x0) - math.sin(t) * (yy - y0))).view(1, 1, height, width)+++class TestConventionsOrientation(BaseTester):+ @pytest.mark.parametrize("content_angle", [0.0, 30.0])+ def test_convention_laf_orienter_turns_the_frame_counter_clockwise_with_the_content(+ self, device, dtype, content_angle+ ):+ # The output orientation is the input orientation plus the patch angle, which turns the LAF's x axis onto the+ # dominant gradient: content turned +30 degrees counter-clockwise on screen reads +30, the sign of+ # laf_from_center_scale_ori, whatever the input orientation (0, 40 or -75). Centre and scale are kept.+ # Measured on CPU float32: at most 0.005 degrees off. Half precision rounds the ramp, its gradients, which vote+ # into the 10-degree histogram and set the parabolic peak refinement, and the returned angle (bfloat16 spaces+ # angles near 120 degrees by 0.5); the bound is one histogram bin in bfloat16, 2 degrees in float16.+ _skip_without_half_padding(device, dtype)+ tol = {torch.float16: 2.0, torch.bfloat16: 10.0}.get(dtype, 0.05)+ orienter = LAFOrienter(32).to(device, dtype)+ img = _conv_ramp(content_angle, 61, 83, 47.0, 26.0).to(device, dtype)+ centre = torch.tensor([[[47.0, 26.0]]], device=device, dtype=dtype)+ scale = torch.full((1, 1, 1, 1), 12.0, device=device, dtype=dtype)+ for input_angle in (0.0, 40.0, -75.0):+ laf = kornia.feature.laf_from_center_scale_ori(+ centre, scale, torch.tensor([[[input_angle]]], device=device, dtype=dtype)+ )+ out = orienter(laf, img)+ self.assert_close(+ kornia.feature.get_laf_orientation(out).flatten(),+ torch.tensor([content_angle], device=device, dtype=dtype),+ rtol=0.0,+ atol=tol,+ )+ self.assert_close(out[..., 2], laf[..., 2], rtol=0.0, atol=0.0)+ self.assert_close(kornia.feature.get_laf_scale(out), scale)+ # relabelling: transposing the image mirrors the gradient direction a onto -90 - a+ img_t = _conv_ramp(content_angle, 61, 83, 47.0, 26.0).transpose(-1, -2).contiguous().to(device, dtype)+ laf_t = kornia.feature.laf_from_center_scale_ori(+ centre.flip(-1), scale, torch.tensor([[[40.0]]], device=device, dtype=dtype)+ )+ self.assert_close(+ kornia.feature.get_laf_orientation(orienter(laf_t, img_t)).flatten(),+ torch.tensor([-90.0 - content_angle], device=device, dtype=dtype),+ rtol=0.0,+ atol=tol,+ )++ def test_convention_orinet_offset_cancels_and_gain_acts_through_eps(self, device, dtype):+ # OriNet subtracts each patch's mean and divides by its standard deviation plus 1e-6 before its layers, so an+ # offset does not change the angle and a positive gain changes it only through that 1e-6; no pretrained+ # weights are needed for that. With a standard deviation of 0.29, x and 3 x + 2 are 3.5e-7 rad apart in CPU+ # float64.+ with torch.random.fork_rng(devices=[]):+ torch.manual_seed(0)+ model = OriNet()+ patches = torch.rand(3, 1, 32, 32, generator=torch.Generator().manual_seed(1)).to(device, dtype)+ model = model.to(device, dtype)+ # half precision rounds the returned angle: bfloat16 spaces the angles here (-1.78 to -1.94 rad) by 1 / 128+ atol = 2e-2 if dtype in (torch.float16, torch.bfloat16) else 1e-5+ self.assert_close(model(3 * patches + 2), model(patches), rtol=0.0, atol=atol)+ if dtype not in (torch.float32, torch.float64):+ return+ # At a standard deviation of 1e-6 the 1e-6 halves the normalised contrast, and a gain of 3 raises that factor+ # to 3 / 4: each angle moves by 1.65e-2 to 3.44e-2 rad (CPU and MPS float32, CPU float64).+ low = 1e-6 * (patches - patches.mean(dim=(1, 2, 3), keepdim=True)) / patches.std(dim=(1, 2, 3), keepdim=True)+ assert ((model(3 * low) - model(low)).abs() > 5e-3).all()+ if dtype == torch.float64:+ # The offset still cancels at that contrast (2.7e-12 rad); in float32, rounding 2 + low already changes it.+ self.assert_close(model(low + 2), model(low), rtol=0.0, atol=1e-9)++ def test_convention_pass_laf_returns_its_input_object(self, device, dtype):+ # PassLAF returns the very tensor it was given, not a copy: an in-place edit of the output edits the input.+ 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),+ )+ img = torch.zeros(1, 1, 12, 17, device=device, dtype=dtype)+ assert PassLAF()(laf, img) is laf++ def test_convention_dominant_gradient_angle_is_not_wrapped_past_pi(self, device, dtype):+ # The angle is not wrapped into (-pi, pi]: a peak in the bin at pi refines up to half a bin past it, so the+ # angle can exceed pi by up to pi / num_angular_bins. With 8 bins of 45 degrees, a ramp whose gradient points+ # 195 degrees counter-clockwise on screen reads 192.8 degrees (CPU float64; 192.8 to 195.2 in every dtype, CPU+ # and MPS), not -167.2.+ _skip_without_half_padding(device, dtype)+ patch = _conv_ramp(195.0, 32, 32, 15.5, 15.5).to(device, dtype)+ angle = PatchDominantGradientOrientation(32, num_angular_bins=8).to(device, dtype)(patch).item()+ assert math.pi < angle <= math.pi + math.pi / 8diff --git a/tests/feature/test_responces_local_features.py b/tests/feature/test_responces_local_features.pyindex 9a6ecffd4..c18a27b55 100644--- a/tests/feature/test_responces_local_features.py+++ b/tests/feature/test_responces_local_features.py@@ -15,12 +15,21 @@# limitations under the License.#+import math+import pytestimport torchimport kornia-from testing.base import BaseTester+from testing.base import BaseTester, supports_reflect_padding, supports_replicate_padding+++def _skip_without_half_padding(device: torch.device, dtype: torch.dtype) -> None:+ # torch 2.5.1 has no float16 CPU reflection_pad2d or replication_pad2d; these pins blur (reflect) and take+ # gradients (replicate).+ if not (supports_reflect_padding(device, dtype) and supports_replicate_padding(device, dtype)):+ pytest.skip(f"no reflection or replication padding kernel for {dtype} on {device.type}")def _response_atol(expected: torch.Tensor, dtype: torch.dtype) -> float:@@ -455,3 +464,196 @@ class TestBlobDoGSingle(BaseTester):batch_size, channels, height, width = 1, 2, 9, 11img = torch.rand(batch_size, channels, height, width, device=device, dtype=torch.float64)self.gradcheck(kornia.feature.dog_response_single, (img), nondet_tol=1e-4)+++def _conv_grid(height: int, width: int) -> tuple[torch.Tensor, torch.Tensor]:+ """Return the float64 CPU ``(y, x)`` pixel-centre grids of a ``height x width`` image."""+ return torch.meshgrid(+ torch.arange(height, dtype=torch.float64), torch.arange(width, dtype=torch.float64), indexing="ij"+ )+++def _conv_rectangle_and_blob(device: torch.device, dtype: torch.dtype) -> torch.Tensor:+ """48 x 64 image: a bright rectangle (rows 10-25, columns 14-41) and a 0.5-high blob of sigma 3 at (52, 36)."""+ yy, xx = _conv_grid(48, 64)+ img = torch.zeros(48, 64, dtype=torch.float64)+ img[10:26, 14:42] = 1.0+ img = img + 0.5 * torch.exp(-((xx - 52.0) ** 2 + (yy - 36.0) ** 2) / 18.0)+ return img.view(1, 1, 48, 64).to(device, dtype)+++def _conv_blob(x0: float, y0: float, sigma: float) -> torch.Tensor:+ """Float64 CPU Gaussian blob of ``sigma`` centred at pixel ``(x0, y0)`` of a 48 x 64 image, ``(1, 1, 48, 64)``."""+ yy, xx = _conv_grid(48, 64)+ return torch.exp(-((xx - x0) ** 2 + (yy - y0) ** 2) / (2 * sigma**2)).view(1, 1, 48, 64)+++class TestConventionsResponses(BaseTester):+ @pytest.mark.parametrize(+ "response, factor",+ [+ (kornia.feature.harris_response, 16.0),+ (kornia.feature.gftt_response, 4.0),+ (kornia.feature.hessian_response, 4.0),+ ],+ ids=["harris", "gftt", "hessian"],+ )+ def test_convention_response_scales_with_image_intensity(self, device, dtype, response, factor):+ # Harris is quartic in the gradients, the smaller structure-tensor eigenvalue and the Hessian determinant are+ # quadratic, and none of them sees an offset: f(2 x + 1) = factor * f(x), so a threshold tuned on images in+ # [0, 1] keeps nothing or everything on images in [0, 255]. Factors: response(2 * x) / response(x), CPU float64.+ _skip_without_half_padding(device, dtype)+ img = _conv_rectangle_and_blob(device, dtype)+ expected = factor * response(img)+ # half precision rounds the offset image; the bound is relative to the peak response+ scale = 1e-2 if dtype in (torch.float16, torch.bfloat16) else 1e-6+ self.assert_close(response(2 * img + 1), expected, rtol=0.0, atol=scale * expected.abs().max().item())++ def test_convention_harris_response_is_negative_on_an_edge_and_positive_at_a_corner(self, device, dtype):+ # R = det(M) - k trace(M) ** 2 is not clamped: positive at a corner, negative along an edge.+ # harris_response(img)[0, 0, 10, [14, 28]] on CPU float64: the rectangle's top-left corner and its top edge.+ _skip_without_half_padding(device, dtype)+ img = _conv_rectangle_and_blob(device, dtype)+ response = kornia.feature.harris_response(img)+ expected = torch.tensor([5.2460662e-03, -1.0274798e-03], device=device, dtype=dtype)+ rtol = {torch.float16: 2e-3, torch.bfloat16: 2e-2}.get(dtype, 1e-5)+ self.assert_close(response[0, 0, 10, [14, 28]], expected, rtol=rtol, atol=0.0)+ # relabelling: the response of the transposed image is the transposed response, to a rounding of the peak+ scale = 1e-2 if dtype in (torch.float16, torch.bfloat16) else 1e-5+ transposed = kornia.feature.harris_response(img.transpose(-1, -2))+ self.assert_close(transposed, response.transpose(-1, -2), rtol=0.0, atol=scale * response.abs().max().item())++ @pytest.mark.parametrize("grads_mode", ["sobel", "diff"])+ def test_convention_harris_response_on_a_ramp_is_minus_k_times_the_gradient_norm_to_the_fourth(+ self, device, dtype, grads_mode+ ):+ # Both gradient modes return intensity per pixel and the 7 x 7 window is a weighted mean, so on the ramp+ # I = x / 4 + y / 8 the structure tensor is the outer product of (1/4, 1/8): det = 0 and+ # R = -k (1/16 + 1/64) ** 2 = -2.44140625e-4 for k = 0.04. The ramp is exact in every dtype; the outer four+ # rows and columns see the replicate-padded Sobel border.+ _skip_without_half_padding(device, dtype)+ yy, xx = _conv_grid(48, 64)+ ramp = (0.25 * xx + 0.125 * yy).view(1, 1, 48, 64).to(device, dtype)+ interior = kornia.feature.harris_response(ramp, 0.04, grads_mode)[..., 4:-4, 4:-4]+ self.assert_close(interior, torch.full_like(interior, -2.44140625e-4), rtol=1e-3, atol=0.0)++ def test_convention_hessian_response_is_positive_at_bright_and_dark_blobs_and_negative_at_a_saddle(+ self, device, dtype+ ):+ # The signed determinant Ixx Iyy - Ixy ** 2: a blob of either polarity is a positive maximum, a saddle negative.+ # hessian_response(...)[:, 0, 20, 30] on CPU float64: blob of sigma 3 at (30, 20), bright and dark,+ # 8.9222449e-03 each; saddle (x - 30)(y - 20) / 100, -(1 / 100) ** 2.+ _skip_without_half_padding(device, dtype)+ blob = _conv_blob(30.0, 20.0, 3.0)+ yy, xx = _conv_grid(48, 64)+ saddle = ((xx - 30.0) * (yy - 20.0) / 100.0).view(1, 1, 48, 64)+ imgs = torch.cat([blob, 1.0 - blob, saddle]).to(device, dtype)+ response = kornia.feature.hessian_response(imgs)[:, 0, 20, 30]+ expected = torch.tensor([8.9222449e-03, 8.9222449e-03, -1.0e-04], device=device, dtype=dtype)+ rtol = 1e-2 if dtype in (torch.float16, torch.bfloat16) else 1e-5+ self.assert_close(response, expected, rtol=rtol, atol=1e-7)++ @pytest.mark.parametrize(+ "response",+ [kornia.feature.harris_response, kornia.feature.gftt_response, kornia.feature.hessian_response],+ ids=["harris", "gftt", "hessian"],+ )+ def test_convention_sigmas_multiply_the_response_by_sigma_to_the_fourth(self, device, dtype, response):+ # sigmas[b] multiplies the response of image b by sigmas[b] ** 4 in all three (VLFeat covdet.c's scale+ # normalisation of Harris and of the Hessian determinant; GFTT takes the same power): 2 ** 4 = 16 and+ # 0.5 ** 4 = 1 / 16. The bound is 2 * eps relative per element: the power itself may round (MPS gives 0.5 ** 4+ # as 1 / 16 minus 2 ** -27 in float32), the product rounds once more.+ _skip_without_half_padding(device, dtype)+ img = _conv_rectangle_and_blob(device, dtype).repeat(2, 1, 1, 1)+ sigmas = torch.tensor([2.0, 0.5], device=device, dtype=dtype)+ expected = response(img) * torch.tensor([16.0, 0.0625], device=device, dtype=dtype).view(-1, 1, 1, 1)+ self.assert_close(response(img, sigmas=sigmas), expected, rtol=2 * torch.finfo(dtype).eps, atol=0.0)++ @pytest.mark.parametrize("angle, exponent_bounds", [(30.0, (2.0, 3.0)), (90.0, (3.0, 4.0))])+ def test_convention_gftt_blur_scaling_depends_on_corner_geometry(self, device, dtype, angle, exponent_bounds):+ # These binary wedges give effective peak-decay exponents 2.53 and 3.31 over sigma=1.6..4 on CPU float64.+ # They lie on opposite sides of 3: sigma ** 4 is not a universally closer correction than sigma ** 2.+ # The bounds describe these fixtures only; the separate sigmas pin checks the actual fourth-power multiplier.+ _skip_without_half_padding(device, dtype)+ n = 97+ yy, xx = _conv_grid(n, n)+ wedge = torch.atan2(yy - n // 2, xx - n // 2).abs() <= math.radians(angle / 2)+ img = wedge[None, None].to(device, dtype)+ peaks = []+ for sigma, ksize in ((1.6, 15), (4.0, 33)):+ blurred = kornia.filters.gaussian_blur2d(img, (ksize, ksize), (sigma, sigma))+ response = kornia.feature.gftt_response(blurred)[..., n // 2 - 20 : n // 2 + 21, n // 2 - 20 : n // 2 + 21]+ peaks.append(response.max().cpu().double())+ exponent = (torch.log(peaks[0] / peaks[1]) / math.log(4.0 / 1.6)).item()+ assert exponent_bounds[0] < exponent < exponent_bounds[1]++ def test_convention_dog_response_is_each_level_minus_the_previous_one(self, device, dtype):+ # The level axis of (B, C, D, H, W) is dim 2, and output level i is L[i + 1] - L[i]: D - 1 levels.+ # Level d holds d ** 2 (plus 10 in channel 1), so the differences are 1, 3, 5 in both channels.+ levels = torch.arange(4, dtype=torch.float64) ** 2+ stack = levels.view(1, 1, 4, 1, 1) + torch.tensor([0.0, 10.0], dtype=torch.float64).view(1, 2, 1, 1, 1)+ out = kornia.feature.dog_response(stack.expand(1, 2, 4, 5, 7).to(device, dtype))+ assert out.shape == (1, 2, 3, 5, 7)+ expected = torch.tensor([1.0, 3.0, 5.0], device=device, dtype=dtype).view(1, 1, 3, 1, 1).expand(1, 2, 3, 5, 7)+ self.assert_close(out, expected)++ def test_convention_dog_is_negative_at_a_bright_blob(self, device, dtype):+ # Both DoG functions subtract the finer blur from the coarser (Lowe's D = L(k sigma) - L(sigma)), so a bright+ # blob is a minimum and a dark one a maximum. dog_response_single(img, 1.0, 1.6)[:, 0, 20, 30] at a blob of+ # sigma 3 centred at (30, 20), CPU float64: -0.1214043 (bright), +0.1214043 (dark).+ _skip_without_half_padding(device, dtype)+ blob = _conv_blob(30.0, 20.0, 3.0)+ imgs = torch.cat([blob, 1.0 - blob]).to(device, dtype)+ single = kornia.feature.dog_response_single(imgs, 1.0, 1.6)+ expected = torch.tensor([-0.1214043, 0.1214043], device=device, dtype=dtype)+ rtol = 1e-2 if dtype in (torch.float16, torch.bfloat16) else 1e-5+ self.assert_close(single[:, 0, 20, 30], expected, rtol=rtol, atol=0.0)+ # The stack form agrees: the same two blurs (kernel int(8 sigma + 1), made odd: 9 and 13) as levels 0 and 1.+ stack = torch.stack(+ [+ kornia.filters.gaussian_blur2d(imgs, (9, 9), (1.0, 1.0)),+ kornia.filters.gaussian_blur2d(imgs, (13, 13), (1.6, 1.6)),+ ],+ dim=2,+ )+ self.assert_close(kornia.feature.dog_response(stack)[:, :, 0], single)++ @pytest.mark.parametrize("name", ["harris", "gftt", "hessian", "dog_single", "dog"])+ def test_convention_response_modules_return_their_functions(self, device, dtype, name):+ # Each module is its function with the constructor arguments bound; BlobDoG and BlobDoGSingle ignore `sigmas`.+ _skip_without_half_padding(device, dtype)+ img = torch.rand(2, 1, 24, 30, generator=torch.Generator().manual_seed(0), dtype=torch.float64)+ img = img.to(device, dtype)+ sigmas = torch.tensor([2.0, 0.5], device=device, dtype=dtype)+ if name == "harris": # k = 1 / 16 is exact in every dtype, so the buffer cast does not round it+ module = kornia.feature.CornerHarris(0.0625, grads_mode="diff")+ expected = kornia.feature.harris_response(img, 0.0625, "diff", sigmas)+ elif name == "gftt":+ module = kornia.feature.CornerGFTT(grads_mode="diff")+ expected = kornia.feature.gftt_response(img, "diff", sigmas)+ elif name == "hessian":+ module = kornia.feature.BlobHessian(grads_mode="diff")+ expected = kornia.feature.hessian_response(img, "diff", sigmas)+ elif name == "dog_single":+ module = kornia.feature.BlobDoGSingle(1.2, 2.0)+ expected = kornia.feature.dog_response_single(img, 1.2, 2.0)+ else: # BlobDoG takes the (B, C, D, H, W) scale stack+ img = img.view(1, 1, 2, 24, 30)+ module = kornia.feature.BlobDoG()+ expected = kornia.feature.dog_response(img)+ out = module.to(device, dtype)(img, sigmas)+ self.assert_close(out, expected, rtol=0.0, atol=0.0)++ def test_convention_dog_kernel_size_is_eight_sigma_plus_one_rounded_up_to_odd(self, device, dtype):+ # Each blur of dog_response_single has int(8 * sigma + 1) taps, rounded up to an odd number: sigma 0.875 gives+ # int(8.0) = 8, so 9 taps reaching 4 pixels (rounding down would give 7, reaching 3), and sigma 0.5 gives 5.+ # On an impulse at (13, 9) the response is therefore positive 4 pixels away and exactly zero 5 pixels away,+ # along x and along y.+ _skip_without_half_padding(device, dtype)+ img = torch.zeros(1, 1, 23, 31, device=device, dtype=dtype)+ img[..., 9, 13] = 1.0+ out = kornia.feature.dog_response_single(img, 0.5, 0.875)[0, 0]+ reach_4 = out[[9, 9, 13, 5], [17, 9, 13, 13]]+ reach_5 = out[[9, 9, 14, 4], [18, 8, 13, 13]]+ assert bool((reach_4 > 0).all())+ assert bool((reach_5 == 0).all())diff --git a/tests/feature/test_scale_space_detector.py b/tests/feature/test_scale_space_detector.pyindex 52813eb2e..870b42065 100644--- a/tests/feature/test_scale_space_detector.py+++ b/tests/feature/test_scale_space_detector.py@@ -35,11 +35,19 @@ from testing.base import (BaseTester,dynamo_is_available,supports_conv2d,+ supports_reflect_padding,supports_replicate_padding,supports_topk,)+def _skip_without_half_padding(device: torch.device, dtype: torch.dtype) -> None:+ # torch 2.5.1 has no float16 CPU reflection_pad2d or replication_pad2d; these pins blur (reflect) and take+ # gradients (replicate).+ if not (supports_reflect_padding(device, dtype) and supports_replicate_padding(device, dtype)):+ pytest.skip(f"no reflection or replication padding kernel for {dtype} on {device.type}")++def _require_affine_orientation_kernels(device: torch.device, dtype: torch.dtype) -> None:if dtype not in (torch.float16, torch.bfloat16):return@@ -1424,3 +1432,319 @@ class TestMultiResolutionDetector(BaseTester):lafs, resps = det(inp)assert lafs.shape == torch.Size([1, 5, 2, 3])assert resps.abs().max().item() > 0+++def _conv_blob(x0: float, y0: float, sigma: float, height: int, width: int, device, dtype) -> torch.Tensor:+ """Gaussian blob of ``sigma`` centred at pixel ``(x0, y0)`` (pixel centres at integers), ``(1, 1, H, W)``."""+ yy, xx = torch.meshgrid(+ torch.arange(height, dtype=torch.float64), torch.arange(width, dtype=torch.float64), indexing="ij"+ )+ blob = torch.exp(-((xx - x0) ** 2 + (yy - y0) ** 2) / (2 * sigma**2))+ return blob.view(1, 1, height, width).to(device, dtype)+++class _TwoMaxima(torch.nn.Module):+ """A scale-space response with two maxima at level 2 of the 64 x 96 octave: A at (40, 50), a weaker B at (30, 20).++ ``pull`` sets A's right neighbour (41, 50) so that the sub-pixel step moves A's centre towards x = 41.+ """++ def __init__(self, pull: float | None = None) -> None:+ super().__init__()+ self.pull = pull++ def forward(self, x: torch.Tensor, sigmas: torch.Tensor) -> torch.Tensor:+ out = -torch.ones_like(x)+ if x.shape[-1] == 96: # the first octave only+ out[:, :, 2, 50, 40] = 0.0+ if self.pull is not None:+ out[:, :, 2, 50, 41] = self.pull+ out[:, :, 2, 20, 30] = -0.5+ return out+++class _Extrema(torch.nn.Module):+ """A scale-space response on a constant background with single-voxel extrema at level 2 of the 64 x 96 octave.++ ``items`` holds ``((u, v), value, box)``: the voxel's value and, unless ``box`` is None, the value of the rest of+ its 3 x 3 x 3 neighbourhood.+ """++ def __init__(self, items: list, background: float) -> None:+ super().__init__()+ self.items = items+ self.background = background++ def forward(self, x: torch.Tensor, sigmas: torch.Tensor) -> torch.Tensor:+ out = torch.full_like(x[:, :1], self.background)+ if x.shape[-1] == 96: # the first octave only+ for (u, v), value, box in self.items:+ if box is not None:+ out[:, :, 1:4, v - 1 : v + 2, u - 1 : u + 2] = box+ out[:, :, 2, v, u] = value+ return out+++class _QuadraticMinimum(torch.nn.Module):+ """A scale-space response ``(d - 2.375)^2 + (y - 30.375)^2 + (x - 20.375)^2 - 0.3`` on the 64 x 96 octave.++ Every other octave is 1. Its minimum, -0.3 at level 2.375 and pixel (20.375, 30.375), lies between samples: every+ sampled value is at least 3 * 0.375^2 - 0.3 = 0.121875, at the strict minimum voxel (2, 30, 20). The offsets are+ exact in bfloat16.+ """++ def forward(self, x: torch.Tensor, sigmas: torch.Tensor) -> torch.Tensor:+ out = torch.ones_like(x[:, :1])+ if x.shape[-1] == 96: # the first octave only+ d, y, xx = torch.meshgrid(+ *(torch.arange(n, device=x.device, dtype=x.dtype) for n in out.shape[-3:]), indexing="ij"+ )+ out[:] = (d - 2.375) ** 2 + (y - 30.375) ** 2 + (xx - 20.375) ** 2 - 0.3+ return out+++class _LevelPeaks(torch.nn.Module):+ """A response map with one peak per pyramid level, looked up by the level's ``(H, W)``.++ Each peak has one lower neighbour, ``0.9`` of it, at the offset ``(du, dv)`` = ``neighbour``. Non-maxima+ suppression removes the neighbour, but it makes the peak asymmetric, so any sub-pixel step would move the peak+ towards it (a parabolic fit by 0.41 pixel).+ """++ def __init__(self, peaks: dict, neighbour: tuple[int, int]) -> None:+ super().__init__()+ self.peaks = peaks+ self.neighbour = neighbour++ def forward(self, x: torch.Tensor) -> torch.Tensor:+ out = torch.zeros_like(x[:, :1])+ peak = self.peaks.get(tuple(x.shape[-2:]))+ if peak is not None:+ (u, v), value = peak+ out[..., v, u] = value+ out[..., v + self.neighbour[1], u + self.neighbour[0]] = 0.9 * value+ return out+++class TestConventionsScaleSpaceDetector(BaseTester):+ def test_convention_scale_space_detector_centre_is_sub_pixel_in_the_laf_frame(self, device, dtype):+ # A blob of sigma 2.5 centred at x = 25.4, y = 18.6 (pixel centres at integers, LAF frame) on a 48 x 72 image is+ # found at its centre to sub-pixel accuracy, and the other 15 slots are padding: zero LAF, zero response.+ # Measured on CPU: (25.4001, 18.5999) in float32 and float64. bfloat16 spaces values in [16, 32) by 0.125.+ _skip_without_half_padding(device, dtype)+ tol = 0.15 if dtype == torch.bfloat16 else 0.05+ img = _conv_blob(25.4, 18.6, 2.5, 48, 72, device, dtype)+ det = ScaleSpaceDetector(16).to(device, dtype)+ # relabelling: the transposed image swaps the centre's coordinates+ for image, centre in ((img, (25.4, 18.6)), (img.transpose(-1, -2).contiguous(), (18.6, 25.4))):+ lafs, resps = det(image)+ expected = torch.tensor(centre, device=device, dtype=dtype)+ self.assert_close(lafs[0, 0, :, 2], expected, rtol=0.0, atol=tol)+ assert resps[0, 0] > 0+ assert bool((lafs[0, 1:] == 0).all())+ assert bool((resps[0, 1:] == 0).all())++ @pytest.mark.parametrize(+ "sigma, centre, size",+ [(2.5, (25.4, 18.6), (48, 72)), (6.0, (70.4, 52.6), (96, 128))],+ ids=["octave0", "octave1"],+ )+ def test_convention_scale_space_detector_laf_scale_is_mr_size_times_the_detection_sigma(+ self, device, dtype, sigma, centre, size+ ):+ # The LAF scale is mr_size times the scale the blob is detected at, in input pixels, also from octave 1. The+ # detection scale of a blob of sigma s lies within [0.95 s, 1.15 s] (1.035 s and 1.042 s here, CPU float32),+ # so the default mr_size = 6 gives a frame of about 6 s; OpenCV's KeyPoint.size is 2 s.+ _skip_without_half_padding(device, dtype)+ img = _conv_blob(*centre, sigma, *size, device, dtype)+ scales = {}+ for mr_size in (6.0, 1.0):+ lafs, _ = ScaleSpaceDetector(16, mr_size=mr_size).to(device, dtype)(img)+ assert int(kornia.feature.laf_is_filled(lafs)[0].sum()) == 1+ frame = lafs[0, 0, :, :2]+ assert frame[0, 1] == 0+ assert frame[1, 0] == 0+ scales[mr_size] = kornia.feature.get_laf_scale(lafs)[0, 0, 0, 0]+ self.assert_close(scales[6.0], 6.0 * scales[1.0])+ assert 0.95 <= scales[1.0].item() / sigma <= 1.15++ @pytest.mark.parametrize(+ "response, polarity, minima_are_also_good, found",+ [+ ("hessian", "bright", False, True),+ ("hessian", "dark", False, True),+ ("dog", "dark", False, True),+ ("dog", "bright", False, False),+ ("dog", "bright", True, True),+ ],+ )+ def test_convention_scale_space_detector_polarity_follows_the_response(+ self, device, dtype, response, polarity, minima_are_also_good, found+ ):+ # The detector keeps response maxima, and minima only with minima_are_also_good. The Hessian determinant is a+ # maximum at bright and dark blobs alike; DoG (coarser minus finer blur) is a maximum at a dark blob and a+ # minimum at a bright one, which is detected only with minima_are_also_good, and a minimum's slot carries the+ # negated response, so it is positive.+ _skip_without_half_padding(device, dtype)+ if response == "dog" and polarity == "bright" and dtype == torch.bfloat16:+ # The same tie would hide the maximum that a reversed DoG makes of the bright blob, so the maxima-only case+ # could not fail either.+ pytest.skip("bfloat16 rounds the DoG minimum into a tie with a neighbour, and the 3x3x3 NMS is strict")+ blob = _conv_blob(25.4, 18.6, 2.5, 48, 72, device, dtype)+ img = blob if polarity == "bright" else 1.0 - blob+ if response == "hessian":+ det = ScaleSpaceDetector(8, minima_are_also_good=minima_are_also_good)+ else:+ det = ScaleSpaceDetector(+ 8,+ resp_module=kornia.feature.BlobDoG(),+ scale_space_response=True,+ minima_are_also_good=minima_are_also_good,+ )+ lafs, resps = det.to(device, dtype)(img)+ target = torch.tensor([25.4, 18.6], device=device, dtype=dtype)+ near = kornia.feature.laf_is_filled(lafs)[0] & ((lafs[0, :, :, 2] - target).norm(dim=-1) < 1.0)+ assert bool(near.any()) == found+ if found: # the strongest detection, with a positive response+ assert bool(near[0])+ assert resps[0, 0] > 0++ @pytest.mark.parametrize("rejection", ["border", "mask"])+ def test_wart_scale_space_detector_tests_border_and_mask_after_the_octave_top_k_5741(+ self, device, dtype, rejection+ ):+ # An octave hands only its `num_features` strongest candidates to the border and mask test, so a rejected+ # candidate's slot stays empty while a weaker valid one exists (#5741). A is rejected -- its half frame of+ # radius 10.3 overhangs the border y = 63 - 5, or its refined centre x = 40.17 touches the masked pixel+ # (41, 50) -- and B at (30, 20) is valid: num_features=1 returns an empty slot, num_features=2 returns B.+ _skip_without_half_padding(device, dtype)+ sigma = 1.6 * 2 ** (2 / 3) # the scale of level 2 of the first octave+ img = torch.zeros(1, 1, 64, 96, device=device, dtype=dtype)+ mask = None+ if rejection == "border":+ response, radius = _TwoMaxima(), 10.3+ else:+ response, radius = _TwoMaxima(pull=-0.5), 5.0+ mask = torch.ones(1, 1, 64, 96, device=device, dtype=torch.bool)+ mask[..., 50, 41] = False+ filled = {}+ for n in (1, 2):+ det = ScaleSpaceDetector(n, resp_module=response, scale_space_response=True, mr_size=2 * radius / sigma)+ lafs, resps = det.to(device, dtype)(img, mask)+ filled[n] = kornia.feature.laf_is_filled(lafs)[0].tolist()+ assert filled[1] == [False]+ assert filled[2] == [True, False]+ self.assert_close(lafs[0, 0, :, 2], torch.tensor([30.0, 20.0], device=device, dtype=dtype))+ self.assert_close(resps[0, 0], torch.tensor(-0.5, device=device, dtype=dtype))++ @pytest.mark.parametrize(+ "sign, minima_are_also_good, centres, values",+ [+ (1.0, False, [[40.0, 30.0], [70.0, 45.0]], [0.8, -0.2]),+ (1.0, True, [[40.0, 30.0], [25.0, 40.0], [70.0, 45.0]], [0.8, 0.7, -0.2]),+ (-1.0, True, [[40.0, 30.0], [25.0, 40.0], [60.0, 25.0]], [0.8, 0.7, -0.3]),+ ],+ ids=["maxima", "minima", "minima-negated-response"],+ )+ def test_convention_scale_space_detector_takes_single_voxel_minima_below_zero_only(+ self, device, dtype, sign, minima_are_also_good, centres, values+ ):+ # On a background of 0.5: maxima of 0.8 at (40, 30) and of -0.2 inside a -0.4 box at (70, 45), minima of -0.7+ # at (25, 40) and of 0.3 at (60, 25). A strict maximum is a candidate whatever its sign; with+ # minima_are_also_good a strict minimum is one when its refined negated response exceeds the response sampled+ # there. Refinement leaves a single-voxel extremum at its sampled value, so such a minimum is one only below+ # zero, and returns its negated response. So the minimum of 0.3 is not detected, and negating the response+ # detects it (as a maximum of -0.3) instead of the maximum of -0.2 (now a minimum of 0.2).+ _skip_without_half_padding(device, dtype)+ items = [((40, 30), 0.8, None), ((70, 45), -0.2, -0.4), ((25, 40), -0.7, None), ((60, 25), 0.3, None)]+ items = [(site, sign * value, None if box is None else sign * box) for site, value, box in items]+ det = ScaleSpaceDetector(+ 8,+ resp_module=_Extrema(items, background=sign * 0.5),+ scale_space_response=True,+ mr_size=1.0,+ minima_are_also_good=minima_are_also_good,+ )+ lafs, resps = det.to(device, dtype)(torch.zeros(1, 1, 64, 96, device=device, dtype=dtype))+ n = len(values)+ assert kornia.feature.laf_is_filled(lafs)[0].tolist() == [True] * n + [False] * (8 - n)+ self.assert_close(lafs[0, :n, :, 2], torch.tensor(centres, device=device, dtype=dtype))+ self.assert_close(resps[0, :n], torch.tensor(values, device=device, dtype=dtype))++ @pytest.mark.parametrize("minima_are_also_good", [False, True])+ def test_convention_scale_space_detector_compares_a_refined_minimum_with_the_sampled_response(+ self, device, dtype, minima_are_also_good+ ):+ # The selection compares a minimum after refinement: its refined negated response, 0.3, exceeds the 0.121875+ # sampled at its voxel, so the minimum is a candidate although no sampled response is below zero. It is+ # reported at its refined centre (20.375, 30.375) with response 0.3. The response has no strict maximum, so+ # without minima_are_also_good there is no detection.+ _skip_without_half_padding(device, dtype)+ det = ScaleSpaceDetector(+ 2,+ resp_module=_QuadraticMinimum(),+ scale_space_response=True,+ mr_size=1.0,+ minima_are_also_good=minima_are_also_good,+ )+ lafs, resps = det.to(device, dtype)(torch.zeros(1, 1, 64, 96, device=device, dtype=dtype))+ if not minima_are_also_good:+ assert kornia.feature.laf_is_filled(lafs)[0].tolist() == [False, False]+ return+ assert kornia.feature.laf_is_filled(lafs)[0].tolist() == [True, False]+ self.assert_close(lafs[0, 0, :, 2], torch.tensor([20.375, 30.375], device=device, dtype=dtype))+ self.assert_close(resps[0, 0], torch.tensor(0.3, device=device, dtype=dtype))++ def test_convention_scale_space_detector_masks_candidates_before_the_top_k(self, device, dtype):+ # A mask drops a candidate at its integer site before the octave's top-k; only the check of the refined centre+ # comes after it (#5741). A, the strongest maximum, at (40, 50) lies in a masked 5 x 5 region, so the only slot+ # of num_features=1 goes to the weaker B at (30, 20); without the mask it goes to A.+ _skip_without_half_padding(device, dtype)+ img = torch.zeros(1, 1, 64, 96, device=device, dtype=dtype)+ mask = torch.ones(1, 1, 64, 96, device=device, dtype=torch.bool)+ mask[..., 48:53, 38:43] = False+ det = ScaleSpaceDetector(1, resp_module=_TwoMaxima(), scale_space_response=True, mr_size=2.0).to(device, dtype)+ lafs, resps = det(img, mask)+ assert kornia.feature.laf_is_filled(lafs)[0].tolist() == [True]+ self.assert_close(lafs[0, 0, :, 2], torch.tensor([30.0, 20.0], device=device, dtype=dtype))+ self.assert_close(resps[0, 0], torch.tensor(-0.5, device=device, dtype=dtype))+ lafs, _ = det(img)+ self.assert_close(lafs[0, 0, :, 2], torch.tensor([40.0, 50.0], device=device, dtype=dtype))+++class TestConventionsMultiResolutionDetector(BaseTester):+ @pytest.mark.parametrize("detector", ["MultiResolutionDetector", "KeyNetDetector"])+ def test_convention_multi_resolution_detector_reports_the_level_pixel_times_the_level_factor(+ self, device, dtype, detector+ ):+ # A detection is an integer level pixel (u, v), reported at (u * W / W_l, v * H / H_l) with scale+ # s_mult * mean(W / W_l, H / H_l), s_mult = 22 by default; there is no sub-pixel step, and (u, v) is not mapped+ # to its pixel centre (u + 0.5) * W / W_l - 0.5 (the Key.Net reference maps it the same way). Level 1 of+ # 69 x 128 at factor 2 is 34 x 64: pixel (20, 17) -> (40.0, 17 * 69 / 34 = 34.5), scale 22 * (2 + 69 / 34) / 2.+ # Each peak's lower neighbour on its +x side (+y when transposed) would pull a sub-pixel step off the pixel.+ _skip_without_half_padding(device, dtype)+ cfg = get_default_detector_config()+ cfg.update(pyramid_levels=1, up_levels=0, scale_factor_levels=2.0)+ tol = 0.15 if dtype == torch.bfloat16 else 1e-3 # bfloat16 spaces values in [32, 64) by 0.25+ for transposed in (False, True):+ if transposed: # relabelling: the transposed image reports swapped coordinates+ size, peaks = (128, 69), {(128, 69): ((31, 45), 1.0), (64, 34): ((17, 20), 0.5)}+ centres, neighbour = [[31.0, 45.0], [34.5, 40.0]], (0, 1)+ else:+ size, peaks = (69, 128), {(69, 128): ((45, 31), 1.0), (34, 64): ((20, 17), 0.5)}+ centres, neighbour = [[45.0, 31.0], [40.0, 34.5]], (1, 0)+ response = _LevelPeaks(peaks, neighbour)+ if detector == "MultiResolutionDetector":+ det = MultiResolutionDetector(response, num_features=4, config=cfg)+ else: # the KeyNet response is replaced by the same peaks through a forward hook+ conf = {**kornia.feature.keynet.keynet_default_config, "Detector_conf": cfg}+ det = kornia.feature.KeyNetDetector(False, num_features=4, keynet_conf=conf)+ det.model.register_forward_hook(lambda module, args, output, response=response: response(args[0]))+ lafs, resps = det.to(device, dtype)(torch.zeros(1, 1, *size, device=device, dtype=dtype))+ self.assert_close(resps, torch.tensor([[1.0, 0.5, 0.0, 0.0]], device=device, dtype=dtype))+ expected = kornia.feature.laf_from_center_scale_ori(+ torch.tensor([centres], device=device, dtype=dtype),+ torch.tensor([22.0, 44.3235294], device=device, dtype=dtype).view(1, 2, 1, 1),+ )+ self.assert_close(lafs[:, :2], expected, rtol=0.0, atol=tol)+ assert bool((lafs[0, 2:] == 0).all())