🐍 Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(feature): DeDoDe padding, SOLD2 junction NMS, ALIKED forward_laf mirroring; document kornia's strict NMS (#5731)
Dmytro Mishkin1adb5b93af1f
diff --git a/changelog.d/+migration-008.breaking.md b/changelog.d/+migration-008.breaking.mdindex 25b998451..f1f7515e4 100644--- a/changelog.d/+migration-008.breaking.md+++ b/changelog.d/+migration-008.breaking.md@@ -5,6 +5,8 @@ so a position whose window ran off an edge was judged against duplicated copieswhich both fabricated plateaus that suppressed genuine maxima and hid genuine neighbours that shouldhave suppressed spurious ones; the `(3, 3)`, `(5, 5)` and `(7, 7)` paths meanwhile rejected the stripoutright, so the two disagreed about the same pixel. The explicit paths' rule is now the rule-everywhere. Every kornia detector already rejects that strip -- ALIKED by hand after calling `nms2d`,-DISK and XFeat by using `k = 5`, `MultiResolutionDetector` by zeroing 15 px before the call -- so no-detector output changes. (#4239, #4242)+everywhere. The kornia detectors that call `nms2d` already reject that strip: ALIKED zeroes its+`nms_radius` border by hand after the call, DISK and XFeat call it with a `(5, 5)` window by default,+whose explicit path already had this rule, and `MultiResolutionDetector` zeroes a 15 px border in its+output, which is wider than the strip of its default `(15, 15)` window. No detector output changes with+its default configuration. (#4239, #4242)diff --git a/changelog.d/5731.fixed.md b/changelog.d/5731.fixed.mdnew file mode 100644index 000000000..16aefd225--- /dev/null+++ b/changelog.d/5731.fixed.md@@ -0,0 +1,31 @@+`DeDoDe.detect` now pads an image to a multiple of 14 the way `DeDoDe.forward` and `DeDoDe.describe` do: after the+ImageNet normalisation, so the pad is the mean colour. Previously `detect` called directly padded first and normalised+after, so the network saw a black strip on the bottom and right, and on a 370x504 crop of Oxford graf img1 it selected+94 of 2000 keypoints different from `forward` (`describe` and `forward` already normalised first). `DeDoDe.describe` now+also cuts the padding off its descriptor map: with `keypoints=None` it returns the `(B, DIM, H, W)` map its docstring+states instead of a map padded to a multiple of 14, and the descriptors it samples at the normalised keypoints of+`detect` come from the right pixels when `H` or `W` is not a multiple of 14. `detect` followed by `describe` now returns+the same keypoints (in normalised coordinates), scores and descriptors as `forward`, and images whose sides are multiples of 14 are bitwise unchanged. The mean-colour pad+is the closer one to the reference implementation (Parskatt/DeDoDe), which does not pad. `DeDoDe.forward` with+`pad_if_not_divisible=False` now runs on the unpadded image; its inner `detect` and `describe` calls used to pad it+anyway.++`SOLD2` and `SOLD2_detector` now pick junctions like the reference implementation (cvg/SOLD2). The junction suppression+keeps the stronger of two junctions that are at most 8 pixels apart along both axes (`grid_size` in general), where it+kept both when either distance was exactly 8 pixels; and the junctions are in raster order, so the first endpoint of+every line segment is the one with the smaller row or, on the same row, the smaller column. Before, the junctions came+in score order. With `use_junction_refinement=False` the endpoints followed the junction score, and+`[[70, 100], [30, 20]]` came out where the reference returns `[[30, 20], [70, 100]]`. With the default `True` the+refinement sorted the endpoints, but it breaks ties between candidate positions by endpoint order, so a refined endpoint+could differ from the reference's (by 0.5 px on a drawn line). With the pretrained weights on Oxford graf img1 the+junction set drops from 416 to the reference's 399, and in both modes the 246 segments become the reference's 229 with+identical coordinates.++`ALIKED.forward_laf` no longer returns mirrored frames. Its 2x2 block is `U · diag(√λ)` of the covariance of the+soft-argmax weights, and `torch.linalg.eigh` fixes each eigenvector only up to sign and lists them in ascending order of+eigenvalue, so `det U` was often -1: no keypoint of Oxford graf or boat img1 had a positive determinant with the+pretrained `aliked-n16`. The first eigenvector is now negated where needed, so every frame has `det > 0`. The ellipse+`A Aᵀ` and the scale are unchanged; a frame that was mirrored gets a different orientation. The docstring now states+that the frame's scale is the spread of the soft-argmax weights, about a pixel or less (0.14 to 1.25 px on graf img1),+not a keypoint size. `compute_affine=False` and `LightGlueMatcher("aliked")`, which reads only keypoint positions and+descriptors, are unaffected.diff --git a/kornia/feature/aliked/aliked.py b/kornia/feature/aliked/aliked.pyindex 1621c81fd..fed0287d9 100644--- a/kornia/feature/aliked/aliked.py+++ b/kornia/feature/aliked/aliked.py@@ -152,8 +152,11 @@ def _affine_from_cov(cov: torch.Tensor) -> torch.Tensor:"""Build a 2x2 affine matrix from a batch of 2x2 covariance matrices.The affine is ``U @ diag(sqrt(eigenvalues))``, where ``U`` contains the- orthonormal eigenvectors of ``cov`` as *columns*. This gives an ellipse- whose axes align with the principal directions of the covariance.+ orthonormal eigenvectors of ``cov`` as *columns*, in ascending order of+ eigenvalue. This gives an ellipse whose axes align with the principal+ directions of the covariance (``A @ A.T == cov``). The sign of the first+ eigenvector is chosen so that ``det(U) = +1``: the affine is a rotation+ times a scaling, never mirrored.Args:cov: symmetric positive-semi-definite matrices ``(N, 2, 2)``.@@ -168,6 +171,11 @@ def _affine_from_cov(cov: torch.Tensor) -> torch.Tensor:if cov.dtype in (torch.float16, torch.bfloat16):cov = cov.float()eigenvalues, eigenvectors = torch.linalg.eigh(cov)+ # eigh fixes each eigenvector only up to sign, and the ascending order alone swaps the axes of a covariance that+ # is wider along x, so det(U) is often -1, a mirrored frame. Negate the first eigenvector there.+ det_u = eigenvectors[:, 0, 0] * eigenvectors[:, 1, 1] - eigenvectors[:, 0, 1] * eigenvectors[:, 1, 0]+ sign = 1.0 - 2.0 * (det_u < 0).to(eigenvectors.dtype) # (N,)+ eigenvectors = eigenvectors * torch.stack([sign, torch.ones_like(sign)], dim=-1)[:, None, :]scales = eigenvalues.clamp(min=1e-8).sqrt() # (N, 2)# Each column of eigenvectors multiplied by the corresponding scale.return (eigenvectors * scales[:, None, :]).to(orig_dtype) # (N, 2, 2)@@ -200,7 +208,8 @@ class DKD(nn.Module):"""Differentiable keypoint detection from a score map.Args:- radius: soft detection radius; NMS kernel size is ``2 * radius + 1``.+ radius: soft detection radius; NMS kernel size is ``2 * radius + 1``. The NMS keeps strict local maxima+ only, unlike the reference's ``simple_nms``; the note of :class:`ALIKED` explains the difference.top_k: if ``> 0`` return exactly the ``top_k`` highest-scoringkeypoints; otherwise threshold mode is used.scores_th: score threshold when ``top_k <= 0``.@@ -757,7 +766,19 @@ class ALIKED(nn.Module):max_num_keypoints: maximum number of keypoints to detect.``-1`` means no limit (threshold-based mode).detection_threshold: minimum detection score in threshold mode.- nms_radius: NMS radius (kernel size ``= 2 * nms_radius + 1``).+ nms_radius: NMS radius (kernel size ``= 2 * nms_radius + 1``). The suppression keeps strict local maxima+ only; see the note below.++ Note:+ Keypoints are the strict local maxima of the score map: :func:`~kornia.geometry.subpix.nms2d` keeps a+ position only if its score is greater than every other score in its ``2 * nms_radius + 1`` window. This+ departs on purpose from the reference implementations (Shiaoming/ALIKED and LightGlue's port). Their+ ``simple_nms`` also keeps tied maxima, and in two further rounds it adds the positions that become the+ maximum of their window once the windows around the maxima already kept are zeroed. Those positions lie on+ the flank of a stronger peak and are not local maxima of the score map. kornia therefore returns a subset+ of the reference keypoints. With the pretrained ``aliked-n16`` it returns 1363 of the reference's 1514 on+ Oxford graf img1, and each of the 151 left out has a higher score in its window. The single pass is also+ faster on CPU than the reference's three rounds.Example:>>> aliked = ALIKED.from_pretrained('aliked-n16') # doctest: +SKIP@@ -919,10 +940,18 @@ class ALIKED(nn.Module):) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:"""Detect and describe local features, returning results in kornia LAF format.- Local Affine Frames are estimated from the soft-argmax weight covariance- computed inside :class:`DKD`: the 2x2 affine matrix captures the dominant- orientation and scale of each detected keypoint without any additional- network parameters.+ With ``compute_affine=True`` the 2x2 block ``A`` of each LAF comes from+ the covariance of the soft-argmax weights in the keypoint's+ ``2 * nms_radius + 1`` detection window, computed inside :class:`DKD`+ without any additional network parameters: ``A @ A.T`` is that+ covariance, so the axes of the frame are its principal axes, and+ ``det A > 0`` (the frame is never mirrored). The frame describes how+ sharply the score map peaks, not an image structure. Its scale+ (:func:`~kornia.feature.get_laf_scale`) is about a pixel or less: 0.14+ to 1.25 px, median 0.62 px, on Oxford graf img1 with the pretrained+ ``aliked-n16``. That is much smaller than the region the descriptor+ samples, so rescale the frames, for example with+ :func:`~kornia.feature.scale_laf`, before using them as a region size.All per-image tensors are zero-padded along the keypoint dimension sothat the outputs are proper batched tensors.diff --git a/kornia/feature/dedode/dedode.py b/kornia/feature/dedode/dedode.pyindex 19e3b6cdc..725b3c65e 100644--- a/kornia/feature/dedode/dedode.py+++ b/kornia/feature/dedode/dedode.py@@ -81,7 +81,9 @@ class DeDoDe(nn.Module):See :cite:`edstedt2024dedode` for details.- .. note:: DeDode takes ImageNet normalized images as input (not in range [0, 1]).+ .. note:: :meth:`forward`, :meth:`detect` and :meth:`describe` take RGB images in the range :math:`[0, 1]` and+ apply the ImageNet normalization themselves; pass ``apply_imagenet_normalization=False`` for images that are+ already normalized.Args:detector_model: The detector model kind. Available options are: `L`.@@ -90,7 +92,7 @@ class DeDoDe(nn.Module):Example:>>> dedode = DeDoDe.from_pretrained(detector_weights="L-C4-v2", descriptor_weights="B-upright")- >>> images = torch.randn(1, 3, 256, 256)+ >>> images = torch.rand(1, 3, 256, 256)>>> keypoints, scores = dedode.detect(images)>>> descriptions = dedode.describe(images, keypoints = keypoints)>>> keypoints, scores, features = dedode(images) # alternatively do both@@ -109,6 +111,23 @@ class DeDoDe(nn.Module):self.descriptor: DeDoDeDescriptor = get_descriptor(descriptor_model, amp_dtype)self.normalizer = Normalize(torch.tensor([0.485, 0.456, 0.406]), std=torch.tensor([0.229, 0.224, 0.225]))+ def _preprocess(+ self, images: torch.Tensor, apply_imagenet_normalization: bool, pad_if_not_divisible: bool+ ) -> torch.Tensor:+ """Normalise, then zero-pad to a multiple of 14.++ The pad is applied after the normalisation so that it is the ImageNet mean colour, the neutral value the+ networks see, in every entry point.+ """+ if apply_imagenet_normalization:+ images = self.normalizer(images)+ if pad_if_not_divisible:+ H, W = images.shape[-2:]+ pd_h = 14 - H % 14 if H % 14 > 0 else 0+ pd_w = 14 - W % 14 if W % 14 > 0 else 0+ images = F.pad(images, (0, pd_w, 0, pd_h), value=0.0)+ return images+def forward(self,images: torch.Tensor,@@ -119,10 +138,14 @@ class DeDoDe(nn.Module):"""Detect and describe keypoints in the input images.Args:- images: A torch.Tensor of shape :math:`(B, 3, H, W)` containing the ImageNet-Normalized input images.+ images: A torch.Tensor of shape :math:`(B, 3, H, W)` containing the RGB input images in the range+ :math:`[0, 1]`.n: The number of keypoints to detect.- apply_imagenet_normalization: Whether to apply ImageNet normalization to the input images.- pad_if_not_divisible: F.pad image shape if not evenly divisible.+ apply_imagenet_normalization: Whether to apply ImageNet normalization to the input images. Pass+ ``False`` if they are already ImageNet-normalized.+ pad_if_not_divisible: Zero-pad the (normalised) image on the bottom and right so that H and W are+ multiples of 14; the pad is the ImageNet mean colour. The padding is removed from the scoremap, so+ keypoints are never reported in it.Returns:keypoints: A torch.Tensor of shape :math:`(B, N, 2)` containing the detected keypoints in the image range,@@ -134,15 +157,15 @@ class DeDoDe(nn.Module):of the detected keypoints. DIM is 256 for B and 512 for G."""- if apply_imagenet_normalization:- images = self.normalizer(images)_B, _C, H, W = images.shape- if pad_if_not_divisible:- pd_h = 14 - H % 14 if H % 14 > 0 else 0- pd_w = 14 - W % 14 if W % 14 > 0 else 0- images = F.pad(images, (0, pd_w, 0, pd_h), value=0.0)- keypoints, scores = self.detect(images, n=n, apply_imagenet_normalization=False, crop_h=H, crop_w=W)- descriptions = self.describe(images, keypoints, apply_imagenet_normalization=False, crop_h=H, crop_w=W)+ images = self._preprocess(images, apply_imagenet_normalization, pad_if_not_divisible)+ # ``images`` is already normalised and, when asked, padded: the calls below must do neither again.+ keypoints, scores = self.detect(+ images, n=n, apply_imagenet_normalization=False, pad_if_not_divisible=False, crop_h=H, crop_w=W+ )+ descriptions = self.describe(+ images, keypoints, apply_imagenet_normalization=False, pad_if_not_divisible=False, crop_h=H, crop_w=W+ )return dedode_denormalize_pixel_coordinates(keypoints, H, W), scores, descriptions@torch.inference_mode()@@ -163,10 +186,14 @@ class DeDoDe(nn.Module):detector is only used at inference time and its statistics must be frozen.Args:- images: A torch.Tensor of shape :math:`(B, 3, H, W)` containing the input images.+ images: A torch.Tensor of shape :math:`(B, 3, H, W)` containing the RGB input images in the range+ :math:`[0, 1]`.n: The number of keypoints to detect.- apply_imagenet_normalization: Whether to apply ImageNet normalization to the input images.- pad_if_not_divisible: F.pad image shape if not evenly divisible.+ apply_imagenet_normalization: Whether to apply ImageNet normalization to the input images. Pass+ ``False`` if they are already ImageNet-normalized.+ pad_if_not_divisible: Zero-pad the (normalised) image on the bottom and right so that H and W are+ multiples of 14; the pad is the ImageNet mean colour, as in :meth:`forward` and :meth:`describe`. The+ padding is removed from the scoremap, so keypoints are never reported in it.crop_h: The height of the crop to be used for detection. If None, the full image is used.crop_w: The width of the crop to be used for detection. If None, the full image is used.@@ -179,13 +206,7 @@ class DeDoDe(nn.Module):KORNIA_CHECK_SHAPE(images, ["B", "3", "H", "W"])self.train(False)B, _C, H, W = images.shape- if pad_if_not_divisible:- h, w = images.shape[2:]- pd_h = 14 - h % 14 if h % 14 > 0 else 0- pd_w = 14 - w % 14 if w % 14 > 0 else 0- images = F.pad(images, (0, pd_w, 0, pd_h), value=0.0)- if apply_imagenet_normalization:- images = self.normalizer(images)+ images = self._preprocess(images, apply_imagenet_normalization, pad_if_not_divisible)logits = self.detector.forward(images)# Remove the padding, if anylogits = logits[..., :H, :W]@@ -214,11 +235,15 @@ class DeDoDe(nn.Module):descriptor is only used at inference time and its statistics must be frozen.Args:- images: A torch.Tensor of shape :math:`(B, 3, H, W)` containing the input images.+ images: A torch.Tensor of shape :math:`(B, 3, H, W)` containing the RGB input images in the range+ :math:`[0, 1]`.keypoints: An optional torch.Tensor of shape :math:`(B, N, 2)` containing the detected keypoints.- apply_imagenet_normalization: Whether to apply ImageNet normalization to the input images.- pad_if_not_divisible: Zero-pad the image so H and W are divisible by 14. Required when- using the ``G`` descriptor backed by DINOv2 (patch size 14). Ignored for ``B``.+ apply_imagenet_normalization: Whether to apply ImageNet normalization to the input images. Pass+ ``False`` if they are already ImageNet-normalized.+ pad_if_not_divisible: Zero-pad the (normalised) image on the bottom and right so that H and W are+ multiples of 14; the pad is the ImageNet mean colour, as in :meth:`forward` and :meth:`detect`.+ Required when using the ``G`` descriptor backed by DINOv2 (patch size 14). The padding is removed from+ the descriptor map, so the map has the size of the input image.crop_h: The height of the crop to be used for description. If None, the full image is used.crop_w: The width of the crop to be used for description. If None, the full image is used.@@ -232,17 +257,13 @@ class DeDoDe(nn.Module):_B, _C, H, W = images.shapeif keypoints is not None:KORNIA_CHECK_SHAPE(keypoints, ["B", "N", "2"])- if apply_imagenet_normalization:- images = self.normalizer(images)- if pad_if_not_divisible:- pd_h = 14 - H % 14 if H % 14 > 0 else 0- pd_w = 14 - W % 14 if W % 14 > 0 else 0- images = F.pad(images, (0, pd_w, 0, pd_h), value=0.0)+ images = self._preprocess(images, apply_imagenet_normalization, pad_if_not_divisible)self.train(False)descriptions = self.descriptor.forward(images)if crop_h is not None and crop_w is not None:- descriptions = descriptions[..., :crop_h, :crop_w]H, W = crop_h, crop_w+ # Remove the padding, so that the normalised keypoints of `detect` index the map of the input image.+ descriptions = descriptions[..., :H, :W]if keypoints is not None:return F.grid_sample(descriptions.float(), keypoints[:, None], mode="bilinear", align_corners=False)[diff --git a/kornia/feature/disk/disk.py b/kornia/feature/disk/disk.pyindex 8dbcba1a9..2a0eaf6d3 100644--- a/kornia/feature/disk/disk.py+++ b/kornia/feature/disk/disk.py@@ -56,6 +56,16 @@ class DISK(nn.Module):a torch.Tensor of shape:math:`(B, \mathrm{desc\_dim} + 1, H, W)`.+ Note:+ Keypoints are the strict local maxima of the heatmap: :func:`~kornia.geometry.subpix.nms2d` keeps a position+ only if its score is greater than every other score in its full ``window_size`` window. Tied maxima, and the+ positions near the border whose window runs off the image (see :func:`~kornia.geometry.subpix.nms2d`), are+ never keypoints. This departs on purpose from the reference implementation (cvlab-epfl/disk). Its max-pool NMS+ clips the window at the border, so it judges a border position against part of its window. Of several equal+ maxima it keeps the one the max-pool reports first, which depends on an order PyTorch does not specify. With+ the pretrained ``depth`` weights on Oxford graf and boat img1, every keypoint of the reference that kornia+ leaves out lies in that border strip.+Example:>>> disk = DISK.from_pretrained('depth')>>> images = torch.rand(1, 3, 256, 256)diff --git a/kornia/feature/sold2/sold2_detector.py b/kornia/feature/sold2/sold2_detector.pyindex 77d0fdda8..d3ffee186 100644--- a/kornia/feature/sold2/sold2_detector.py+++ b/kornia/feature/sold2/sold2_detector.py@@ -574,16 +574,33 @@ def line_map_to_segments(junctions: torch.Tensor, line_map: torch.Tensor) -> tordef prob_to_junctions(prob: torch.Tensor, dist: float, prob_thresh: float = 0.01, top_k: int = 0) -> torch.Tensor:- """Extract junctions from a probability map, apply NMS, and extract the top k candidates."""+ """Extract junctions from a probability map, apply NMS, and extract the top k candidates.++ The strongest junction is kept first and suppresses every other junction within ``dist`` pixels of it along both+ axes, ``dist`` itself included, like ``super_nms`` of the SOLD2 reference implementation. The ``top_k`` strongest+ survivors are returned in raster order (by row, then by column), so the first endpoint of a line segment built+ from the junction indices is the one with the smaller row or, on the same row, the smaller column.++ Args:+ prob: junction probability map with shape :math:`(H, W)`.+ dist: suppression distance in pixels.+ prob_thresh: minimum probability of a junction.+ top_k: number of junctions to keep; ``0`` keeps all.++ Returns:+ Junction locations in ``(row, col)`` order with shape :math:`(N, 2)`.+ """# Extract the junctionsjunctions = torch.stack(torch.where(prob >= prob_thresh), -1).float()if len(junctions) == 0:return junctions- # Perform NMS- boxes = torch.cat([junctions - dist / 2, junctions + dist / 2], 1)+ # Perform NMS. Boxes of side ``floor(dist) + 0.5`` around the integer locations overlap exactly when both+ # coordinates differ by at most ``dist``; ``nms`` then drops every overlapping box.+ side = math.floor(dist) + 0.5+ boxes = torch.cat([junctions - side / 2, junctions + side / 2], 1)scores = prob[prob >= prob_thresh]- remainings = nms(boxes, scores, 0.001)+ remainings = nms(boxes, scores, 0.0)junctions = junctions[remainings]# Keep only the topk values@@ -591,4 +608,5 @@ def prob_to_junctions(prob: torch.Tensor, dist: float, prob_thresh: float = 0.01k = min(len(junctions), top_k)junctions = junctions[:k]- return junctions+ # Raster order: the line map, and so the endpoints of each segment, follow the junction indices+ return junctions[torch.argsort(junctions[:, 0].long() * prob.shape[-1] + junctions[:, 1].long())]diff --git a/kornia/feature/xfeat.py b/kornia/feature/xfeat.pyindex f82802499..81337d36c 100644--- a/kornia/feature/xfeat.py+++ b/kornia/feature/xfeat.py@@ -282,6 +282,16 @@ class XFeat(nn.Module):top_k: maximum number of keypoints to keep per image. Default: ``4096``.detection_threshold: minimum keypoint score. Default: ``0.05``.+ Note:+ Keypoints are the strict local maxima of the keypoint heatmap: :func:`~kornia.geometry.subpix.nms2d` keeps a+ position only if its score is greater than every other score in its full 5x5 window. Tied maxima, and the+ positions within 2 pixels of the border whose window runs off the image, are never keypoints. This departs+ on purpose from the reference implementation (verlab/accelerated_features). Its NMS keeps every position+ equal to the maximum of its window: all positions of a plateau survive, and whether a near-tie survives+ depends on rounding-level differences of the scores. Its window is also clipped at the border, so it judges+ a border position against part of its window. With the pretrained weights on Oxford graf and boat img1,+ every candidate of the reference that kornia leaves out lies in that border strip.+Example:>>> model = XFeat()>>> img = torch.rand(1, 3, 256, 256)diff --git a/tests/feature/test_aliked.py b/tests/feature/test_aliked.pyindex 06fb256ae..b8649f409 100644--- a/tests/feature/test_aliked.py+++ b/tests/feature/test_aliked.py@@ -19,6 +19,7 @@ import pytestimport torchfrom kornia.feature.aliked import ALIKED, ALIKEDFeatures+from kornia.feature.aliked.aliked import _affine_from_covfrom kornia.feature.aliked.deform_conv2d import deform_conv2dfrom testing.base import BaseTester@@ -437,3 +438,55 @@ class TestALIKEDForwardLAF(BaseTester):# det(A) should be non-zero (non-degenerate)dets = torch.det(A)assert (dets.abs() > 1e-6).all()++ def test_affine_from_cov_is_not_mirrored_5730(self, device, dtype):+ """The frame keeps the covariance ellipse (``A @ A.T == cov``) and is not mirrored (``det A > 0``).++ ``torch.linalg.eigh`` returned an eigenvector matrix with determinant -1 for every one of these, on CPU and+ MPS: the ascending eigenvalue order alone swaps the axes of ``diag(0.3, 0.1)``.+ """+ cov = torch.tensor(+ [+ [[2.0, 1.0], [1.0, 2.0]],+ [[1.0, -0.5], [-0.5, 3.0]],+ [[0.3, 0.0], [0.0, 0.1]],+ [[0.5, 0.2], [0.2, 0.1]],+ ],+ device=device,+ dtype=dtype,+ )+ A = _affine_from_cov(cov)+ self.assert_close(A @ A.transpose(-1, -2), cov)+ det_a = A[:, 0, 0] * A[:, 1, 1] - A[:, 0, 1] * A[:, 1, 0]+ det_cov = cov[:, 0, 0] * cov[:, 1, 1] - cov[:, 0, 1] * cov[:, 1, 0]+ self.assert_close(det_a, det_cov.sqrt())++ def test_frames_are_not_mirrored_5730(self, device, dtype):+ """forward_laf frames are not mirrored and keep the sub-pixel ellipse of the soft-argmax weights.++ Three peaks, each with a weaker neighbour to its right, below it, or diagonally. The expected ellipse+ ``A @ A.T`` of the right-neighbour peak is ``main``'s before the fix, whose frame was+ ``[[0, 0.45736], [0.11605, 0]]`` with determinant -0.05308; the one with the neighbour below is its+ transpose.+ """+ s = torch.full((1, 1, 64, 96), 0.01, device=device, dtype=dtype)+ s[0, 0, 40, 60], s[0, 0, 40, 61] = 0.8, 0.7+ s[0, 0, 20, 30], s[0, 0, 21, 30] = 0.8, 0.7+ s[0, 0, 20, 80], s[0, 0, 21, 81] = 0.8, 0.7+ aliked = ALIKED(model_name="aliked-t16").to(device, dtype).eval()+ hook = aliked.score_head.register_forward_hook(lambda m, i, o: torch.logit(s))+ try:+ with torch.no_grad():+ lafs, _, _ = aliked.forward_laf(torch.rand(1, 3, 64, 96, device=device, dtype=dtype))+ finally:+ hook.remove()+ assert lafs.shape == (1, 3, 2, 3)+ order = torch.argsort(lafs[0, :, 0, 2] * 100 + lafs[0, :, 1, 2]) # by x, then y+ A = lafs[0, order, :, :2] # peaks at x = 30 (neighbour below), 60 (right), 80 (diagonal)+ det = A[:, 0, 0] * A[:, 1, 1] - A[:, 0, 1] * A[:, 1, 0]+ assert (det > 0).all(), det+ ellipse_right = torch.tensor([[0.45736**2, 0.0], [0.0, 0.11605**2]], device=device, dtype=dtype)+ self.assert_close(A[1] @ A[1].T, ellipse_right, low_tolerance=True)+ self.assert_close(A[0] @ A[0].T, ellipse_right.flip(0, 1), low_tolerance=True)+ self.assert_close(det[:2], torch.full_like(det[:2], 0.45736 * 0.11605), low_tolerance=True)+ assert (det.sqrt() < 1.0).all() # the documented scale: the spread of the weights, about a pixel or lessdiff --git a/tests/feature/test_dedode.py b/tests/feature/test_dedode.pyindex 330cfbaf4..8d5d8d55e 100644--- a/tests/feature/test_dedode.py+++ b/tests/feature/test_dedode.py@@ -20,10 +20,12 @@ import warningsimport pytestimport torch+from kornia.enhance.normalize import Normalizefrom kornia.feature.dedode import DeDoDefrom kornia.feature.dedode.decoder import ConvRefinerfrom kornia.feature.dedode.transformer.dinov2 import DinoVisionTransformerfrom kornia.feature.dedode.transformer.layers import MemEffAttention, NestedTensorBlock+from kornia.feature.dedode.utils import dedode_denormalize_pixel_coordinatesfrom testing.base import BaseTester@@ -104,6 +106,93 @@ class TestDinoVisionTransformer(BaseTester):assert features["masks"] is masks+class _BlurNet(torch.nn.Module):+ """Stand-in for a DeDoDe network: a 15x15 box blur, so the output near the border depends on the padded values."""++ def __init__(self, out_channels):+ super().__init__()+ self.out_channels = out_channels+ self.seen = []++ def forward(self, images):+ self.seen.append(images)+ blurred = torch.nn.functional.avg_pool2d(images, 15, stride=1, padding=7)+ return blurred[:, : self.out_channels]+++class TestDeDoDePadding(BaseTester):+ @staticmethod+ def _model(device, dtype):+ # Networks are replaced by blurs: the padding rule is under test, not the pretrained weights.+ model = DeDoDe.__new__(DeDoDe) # skips building the VGG networks+ torch.nn.Module.__init__(model)+ model.detector = _BlurNet(1)+ model.descriptor = _BlurNet(3)+ model.normalizer = Normalize(torch.tensor([0.485, 0.456, 0.406]), std=torch.tensor([0.229, 0.224, 0.225]))+ return model.to(device, dtype)++ @staticmethod+ def _image(device, dtype, h=50, w=80):+ gen = torch.Generator().manual_seed(7)+ return torch.rand(1, 3, h, w, generator=gen).to(device, dtype)++ @pytest.mark.parametrize("entry", ["forward", "detect", "describe"])+ def test_pad_is_the_mean_colour_in_every_entry_point_5730(self, device, dtype, entry):+ model = self._model(device, dtype)+ x = self._image(device, dtype) # 50x80 -> 56x84+ if entry == "forward":+ model(x, n=4)+ elif entry == "detect":+ model.detect(x, n=4)+ else:+ model.describe(x)+ net = model.descriptor if entry == "describe" else model.detector+ seen = net.seen[0]+ assert seen.shape == (1, 3, 56, 84)+ normalized = model.normalizer(x)+ self.assert_close(seen[..., :50, :80], normalized)+ # padded after the normalisation: the pad is the ImageNet mean colour, 0 in normalised units+ assert seen[..., 50:, :].abs().max() == 0+ assert seen[..., :, 80:].abs().max() == 0++ def test_detect_and_describe_agree_with_forward_5730(self, device, dtype):+ model = self._model(device, dtype)+ x = self._image(device, dtype)+ n = 40+ kpts, scores, descs = model(x, n=n)+ kpts_n, scores_d = model.detect(x, n=n)+ descs_d = model.describe(x, kpts_n)+ self.assert_close(dedode_denormalize_pixel_coordinates(kpts_n, 50, 80), kpts)+ self.assert_close(scores_d, scores)+ self.assert_close(descs_d, descs)++ def test_dense_descriptors_have_the_size_of_the_image_5730(self, device, dtype):+ model = self._model(device, dtype)+ x = self._image(device, dtype)+ assert model.describe(x).shape == (1, 3, 50, 80)++ def test_multiple_of_14_is_not_padded(self, device, dtype):+ model = self._model(device, dtype)+ x = self._image(device, dtype, h=28, w=42)+ model(x, n=4)+ model.detect(x, n=4)+ model.describe(x)+ for seen in model.detector.seen + model.descriptor.seen:+ self.assert_close(seen, model.normalizer(x))++ @pytest.mark.parametrize("entry", ["forward", "detect_describe"])+ def test_pad_can_be_disabled(self, device, dtype, entry):+ model = self._model(device, dtype)+ x = self._image(device, dtype)+ if entry == "forward":+ model(x, n=4, pad_if_not_divisible=False)+ else:+ model.detect(x, n=4, pad_if_not_divisible=False)+ model.describe(x, pad_if_not_divisible=False)+ assert model.detector.seen[0].shape == (1, 3, 50, 80)+ assert model.descriptor.seen[0].shape == (1, 3, 50, 80)++@pytest.mark.skip(reason="DeDoDe is ummaintained")class TestDeDoDe:@pytest.mark.slowdiff --git a/tests/feature/test_sold2.py b/tests/feature/test_sold2.pyindex 67f0e8c15..e6d1d6eac 100644--- a/tests/feature/test_sold2.py+++ b/tests/feature/test_sold2.py@@ -22,6 +22,8 @@ import torch.nn.functional as Ffrom kornia.core.check import ShapeErrorfrom kornia.feature.sold2 import SOLD2, SOLD2_detectorfrom kornia.feature.sold2.sold2 import keypoints_to_grid+from kornia.feature.sold2.sold2_detector import LineSegmentDetectionModule, line_map_to_segments, prob_to_junctions+from kornia.feature.sold2.structures import LineDetectorCfgfrom testing.base import BaseTester@@ -58,6 +60,97 @@ class TestSOLD2_detector(BaseTester):self.assert_close(model(img), model_jit(img))+class TestJunctionsAndSegments(BaseTester):+ @staticmethod+ def _junction_map(points, device, dtype, shape=(96, 128)):+ prob = torch.zeros(shape, device=device, dtype=dtype)+ for (row, col), score in points:+ prob[row, col] = score+ return prob++ @pytest.mark.parametrize(+ "offset, n_kept",+ [+ # (d_row, d_col) between the strong and the weak junction; the reference suppresses up to and at 8 px+ ((0, 7), 1),+ ((0, 8), 1),+ ((0, 9), 2),+ ((8, 0), 1),+ ((9, 0), 2),+ ((8, 8), 1),+ ((8, 9), 2),+ ((-8, 3), 1),+ ((-9, 3), 2),+ ],+ )+ def test_nms_radius_matches_reference_5730(self, device, dtype, offset, n_kept):+ # reference: cvg/SOLD2 sold2/model/metrics.py ``super_nms`` / ``nms_fast`` (pad = 8, inclusive window)+ r0, c0 = 40, 30+ prob = self._junction_map([((r0, c0), 1.0), ((r0 + offset[0], c0 + offset[1]), 0.9)], device, dtype)+ junctions = prob_to_junctions(prob, 8, 0.0153846, 500)+ assert len(junctions) == n_kept+ assert [float(r0), float(c0)] in junctions.tolist()++ @pytest.mark.parametrize(+ "dist, offset, n_kept",+ [(8.7, (0, 8), 1), (8.7, (0, 9), 2), (3.6, (0, 3), 1), (3.6, (0, 4), 2), (3.6, (4, 4), 2)],+ )+ def test_nms_fractional_distance_5730(self, device, dtype, dist, offset, n_kept):+ # junction locations are integers, so a junction at most ``dist`` away is at most ``floor(dist)`` away+ r0, c0 = 40, 30+ prob = self._junction_map([((r0, c0), 1.0), ((r0 + offset[0], c0 + offset[1]), 0.9)], device, dtype)+ junctions = prob_to_junctions(prob, dist, 0.0153846, 500)+ assert len(junctions) == n_kept+ assert [float(r0), float(c0)] in junctions.tolist()++ def test_nms_is_greedy_by_score_5730(self, device, dtype):+ # the strongest junction suppresses both of its 8 px neighbours, which cannot then suppress the one beyond+ prob = self._junction_map([((40, 20), 0.9), ((40, 28), 1.0), ((40, 37), 0.8)], device, dtype)+ junctions = prob_to_junctions(prob, 8, 0.0153846, 500)+ assert junctions.tolist() == [[40.0, 28.0], [40.0, 37.0]]++ def test_junctions_are_in_raster_order_5730(self, device, dtype):+ # scores run against the raster order, in an H != W map+ points = [((70, 100), 1.0), ((30, 20), 0.9), ((30, 60), 0.8), ((10, 110), 0.7), ((90, 5), 0.6)]+ # row 40 ends at a column above row 41's start with a width stride, but not with a height stride+ points += [((40, 120), 0.55), ((41, 2), 0.5)]+ prob = self._junction_map(points, device, dtype)+ junctions = prob_to_junctions(prob, 8, 0.0153846, 500)+ expected = [[10.0, 110.0], [30.0, 20.0], [30.0, 60.0], [40.0, 120.0], [41.0, 2.0], [70.0, 100.0], [90.0, 5.0]]+ assert junctions.tolist() == expected++ def test_top_k_selects_by_score_then_raster_order_5730(self, device, dtype):+ points = [((70, 100), 1.0), ((30, 20), 0.9), ((30, 60), 0.8), ((10, 110), 0.7)]+ prob = self._junction_map(points, device, dtype)+ junctions = prob_to_junctions(prob, 8, 0.0153846, 3)+ assert junctions.tolist() == [[30.0, 20.0], [30.0, 60.0], [70.0, 100.0]]++ @pytest.mark.parametrize("end", [(70, 100), (30, 100)], ids=["diagonal", "horizontal"])+ @pytest.mark.parametrize("use_junction_refinement", [False, True])+ def test_segment_endpoints_are_in_raster_order_5730(self, device, dtype, use_junction_refinement, end):+ # a line from (row, col) = (30, 20) to ``end``, with the junction at ``end`` the stronger one. Raster order puts+ # (30, 20) first: by row on the diagonal line, by column on the horizontal one. cvg/SOLD2 b2e49f2 returns these+ # endpoints in this order in both modes, moved by up to 0.75 px by the junction refinement.+ prob = self._junction_map([(end, 1.0), ((30, 20), 0.5)], device, dtype)+ heatmap = torch.zeros(96, 128, device=device, dtype=dtype)+ t = torch.linspace(0, 1, 400, device=device)+ rows = torch.round(30 + (end[0] - 30) * t).long()+ cols = torch.round(20 + (end[1] - 20) * t).long()+ heatmap[rows, cols] = 1.0+ cfg = LineDetectorCfg(+ use_heatmap_refinement=False,+ use_junction_refinement=use_junction_refinement,+ use_candidate_suppression=False,+ )+ junctions = prob_to_junctions(prob, 8, 0.0153846, 500)+ line_map, junctions, _ = LineSegmentDetectionModule(cfg).detect(junctions, heatmap)+ segments = line_map_to_segments(junctions, line_map)+ assert segments.shape == (1, 2, 2)+ assert segments[0, 0].tolist() < segments[0, 1].tolist() # lexicographic: row, then column+ expected = torch.tensor([[30.0, 20.0], [float(end[0]), float(end[1])]], device=device, dtype=segments.dtype)+ self.assert_close(segments[0], expected, atol=1.0, rtol=0)++class TestSOLD2(BaseTester):@pytest.mark.slow@pytest.mark.parametrize("batch_size", [1, 2])