π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(feature): DISK and ALIKED keep at most the budget of real maxima, ALIKED's fallback per image (#5875)
Dmytro Mishkin0ec46c7c9a62
diff --git a/changelog.d/5875.breaking.md b/changelog.d/5875.breaking.mdnew file mode 100644index 000000000..e5f3002fc--- /dev/null+++ b/changelog.d/5875.breaking.md@@ -0,0 +1,14 @@+`ALIKED` and `DISK` no longer pad their keypoints with non-maxima, nor drop a real maximum, when an image has no more+local maxima than the keypoint budget. In top-k mode (`ALIKED(max_num_keypoints=k, detection_threshold<=0)`), ALIKED+used to return exactly `k` keypoints per image, filling the slots beyond the score map's maxima with other positions+in `torch.topk`'s tie order, including the removed border, the region a `forward_laf` `mask` excludes and the+`image_size` padding, and it raised when `k` exceeded the number of pixels. It now returns at most `k`, all of them+maxima, and `forward_laf` pads each image to the largest count of the batch with zero frames (#5862).+`DISK(...)(images, n=n)` used to drop the weakest maximum of an image with `n` maxima above `score_threshold` or fewer,+and raised on an image with none; it now returns all of them, the keypoints `n=None` returns. With more than `n`, it+used to leave out every maximum tied across the `n`-th place, returning fewer than `n`; it now keeps the `n` strongest,+taking maxima tied at the `n`-th score in raster order (#5864). In threshold mode, ALIKED fell back to+the maxima above the mean score only when no image of the batch had a maximum above `detection_threshold`; the+fallback is now decided for each image, so a batch returns the keypoints that one-by-one calls return (#5865). The+default `ALIKED` configuration on one image at a time, and `DISK` on an image with more than `n` maxima and no tie across+the `n`-th place, return the same keypoints as before.diff --git a/kornia/feature/aliked/aliked.py b/kornia/feature/aliked/aliked.pyindex fed0287d9..07a6a557e 100644--- a/kornia/feature/aliked/aliked.py+++ b/kornia/feature/aliked/aliked.py@@ -210,11 +210,11 @@ class DKD(nn.Module):Args:radius: soft detection radius; NMS kernel size is ``2 * radius + 1``. The NMS keeps strict local maximaonly, unlike the reference's ``simple_nms``; the note of :class:`ALIKED` explains the difference.- top_k: if ``> 0`` return exactly the ``top_k`` highest-scoring- keypoints; otherwise threshold mode is used.+ top_k: if ``> 0`` return at most ``top_k`` keypoints per image: its ``top_k`` highest-scoring local maxima,+ or all of them when it has fewer; otherwise threshold mode is used.scores_th: score threshold when ``top_k <= 0``.- If ``> 0`` keep keypoints with ``score > scores_th``;- otherwise keep keypoints above the per-image mean score.+ If ``> 0`` keep keypoints with ``score > scores_th``, and in an image with none above it, the keypoints+ above that image's mean score; otherwise keep keypoints above the per-image mean score.n_limit: maximum number of keypoints returned in threshold mode."""@@ -263,32 +263,34 @@ class DKD(nn.Module):"""b, _c, h, w = scores_map.shapescores_nograd = scores_map.detach()- nms_scores = nms2d(scores_nograd, (self.kernel_size, self.kernel_size))+ # the candidates: the strict local maxima outside the border (and outside each image's padding)+ is_max = nms2d(scores_nograd, (self.kernel_size, self.kernel_size), mask_only=True)# remove border- nms_scores[:, :, : self.radius, :] = 0- nms_scores[:, :, :, : self.radius] = 0+ is_max[:, :, : self.radius, :] = False+ is_max[:, :, :, : self.radius] = Falseif image_size is not None:for i in range(b):iw, ih = image_size[i].long()- nms_scores[i, :, ih.item() - self.radius :, :] = 0- nms_scores[i, :, :, iw.item() - self.radius :] = 0+ is_max[i, :, ih.item() - self.radius :, :] = False+ is_max[i, :, :, iw.item() - self.radius :] = Falseelse:- nms_scores[:, :, -self.radius :, :] = 0- nms_scores[:, :, :, -self.radius :] = 0+ is_max[:, :, -self.radius :, :] = False+ is_max[:, :, :, -self.radius :] = Falseif self.top_k > 0:- topk = torch.topk(nms_scores.view(b, -1), self.top_k)- indices_keypoints = [topk.indices[i] for i in range(b)]+ # at most top_k of the maxima: a non-maximum scores -inf here and is dropped, not used to fill up to top_k+ candidate_scores = scores_nograd.masked_fill(~is_max, float("-inf")).reshape(b, -1)+ topk = torch.topk(candidate_scores, min(self.top_k, h * w))+ indices_keypoints = [topk.indices[i][topk.values[i] > float("-inf")] for i in range(b)]else:+ # the per-image mean score: the threshold when scores_th <= 0, and the fallback of an image whose maxima+ # are all at or below scores_th, decided for each image alone+ mean = scores_nograd.reshape(b, -1).mean(dim=1).reshape(b, 1, 1, 1)+ masks = is_max & (scores_nograd > mean)if self.scores_th > 0:- masks = nms_scores > self.scores_th- if masks.sum() == 0:- th = scores_nograd.reshape(b, -1).mean(dim=1)- masks = nms_scores > th.reshape(b, 1, 1, 1)- else:- th = scores_nograd.reshape(b, -1).mean(dim=1)- masks = nms_scores > th.reshape(b, 1, 1, 1)+ above = is_max & (scores_nograd > self.scores_th)+ masks = torch.where(above.reshape(b, -1).any(dim=1).reshape(b, 1, 1, 1), above, masks)masks = masks.reshape(b, -1)indices_keypoints = []@@ -953,8 +955,9 @@ class ALIKED(nn.Module):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 so- that the outputs are proper batched tensors.+ All per-image tensors are zero-padded along the keypoint dimension to+ the largest keypoint count in the batch, so that the outputs are proper+ batched tensors.Args:img: image to extract features with shape :math:`(B,C,H,W)`.diff --git a/kornia/feature/disk/detector.py b/kornia/feature/disk/detector.pyindex 206bb14d3..7b12379ec 100644--- a/kornia/feature/disk/detector.py+++ b/kornia/feature/disk/detector.py@@ -27,7 +27,21 @@ from .structs import Keypointsdef heatmap_to_keypoints(heatmap: torch.Tensor, n: int | None = None, window_size: int = 5, score_threshold: float = 0.0) -> list[Keypoints]:- """Inference-time nms-based detection protocol."""+ """Detect keypoints as the strict local maxima of a heatmap, in raster order.++ Args:+ heatmap: detection logits of shape :math:`(B, 1, H, W)`.+ n: the maximum number of keypoints per image, counted among the maxima above ``score_threshold``. An image+ with ``n`` such maxima or fewer keeps all of them; with more, its ``n`` strongest, where maxima tied at the+ ``n``-th score are taken in raster order (row by row, then column by column) until ``n`` are kept.+ ``None`` keeps every maximum.+ window_size: the size of the non-maxima suppression window.+ score_threshold: a maximum is kept only if its score is strictly above it.++ Returns:+ A list of length :math:`B` with the keypoints of each image.++ """heatmap = heatmap.squeeze(1)nms_mask = nms2d(heatmap.unsqueeze(1), (window_size, window_size), mask_only=True).squeeze(1)nmsed = nms_mask & (heatmap > score_threshold)@@ -38,22 +52,21 @@ def heatmap_to_keypoints(detection_logp = heatmap[b][nmsed[b]]xy = yx.flip((1,))- if n is not None:- n_ = min(n + 1, detection_logp.numel())- # torch.kthvalue picks in ascending order and we want to pick in- # descending order, so we pick n-th smallest among -logp to get- # -threshold- minus_threshold, _indices = torch.kthvalue(-detection_logp, n_)- mask = detection_logp > -minus_threshold+ if n is not None and detection_logp.numel() > n:+ # The n strongest: every score above the n-th largest (torch.kthvalue gives it as the n-th smallest of+ # -logp), then the maxima equal to it in raster order until n are kept. The keypoints stay in raster order.+ if n > 0:+ minus_threshold, _indices = torch.kthvalue(-detection_logp, n)+ threshold = -minus_threshold+ above = detection_logp > threshold+ tied = detection_logp == threshold+ mask = above | (tied & (torch.cumsum(tied, 0) <= n - above.sum()))+ else:+ mask = torch.zeros_like(detection_logp, dtype=torch.bool)xy = xy[mask]detection_logp = detection_logp[mask]- # it may be that due to numerical saturation on the threshold we have- # more than n keypoints, so we need to clip them- xy = xy[:n]- detection_logp = detection_logp[:n]-keypoints.append(Keypoints(xy, detection_logp))return keypointsdiff --git a/kornia/feature/disk/disk.py b/kornia/feature/disk/disk.pyindex 2a0eaf6d3..b595013c1 100644--- a/kornia/feature/disk/disk.py+++ b/kornia/feature/disk/disk.py@@ -120,7 +120,9 @@ class DISK(nn.Module):Args:images: The image to detect features in. Shape :math:`(B, 3, H, W)`.- n: The maximum number of keypoints to detect. If None, all keypoints are returned.+ n: The maximum number of keypoints per image, counted among the maxima above ``score_threshold``. An+ image with ``n`` such maxima or fewer keeps all of them; with more, its ``n`` strongest, where maxima+ tied at the ``n``-th score are taken in raster order. If None, all keypoints are returned.window_size: The size of the non-maxima suppression window used to filter detections.score_threshold: The minimum score a detection must have to be returned.See :py:class:`DISKFeatures` for details.diff --git a/tests/feature/test_aliked.py b/tests/feature/test_aliked.pyindex b8649f409..249a28a9a 100644--- a/tests/feature/test_aliked.py+++ b/tests/feature/test_aliked.py@@ -18,6 +18,7 @@import pytestimport torch+from kornia.feature import laf_is_filledfrom kornia.feature.aliked import ALIKED, ALIKEDFeaturesfrom kornia.feature.aliked.aliked import _affine_from_covfrom kornia.feature.aliked.deform_conv2d import deform_conv2d@@ -490,3 +491,143 @@ class TestALIKEDForwardLAF(BaseTester):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 less+++# ---------------------------------------------------------------------------+# keypoint selection: top-k and threshold modes+# ---------------------------------------------------------------------------+++class TestALIKEDKeypointSelection(BaseTester):+ """Top-k mode keeps at most ``k`` strict maxima (#5862); the threshold fallback is decided per image (#5865)."""++ @staticmethod+ def _score_map(peaks, device, dtype, batch=1, h=64, w=96):+ # a score map (after the sigmoid) of 0.01 with the given peaks (image, x, y, score)+ s = torch.full((batch, 1, h, w), 0.01, dtype=torch.float64)+ for b, x, y, score in peaks:+ s[b, 0, y, x] = score+ return s.to(device, dtype)++ @staticmethod+ def _run(aliked, score_map, method="forward", **kwargs):+ # the score head returns the logit of score_map, so the sigmoid after it gives score_map back+ hook = aliked.score_head.register_forward_hook(lambda m, i, o: torch.logit(score_map))+ b, _, h, w = score_map.shape+ try:+ with torch.no_grad():+ image = torch.rand(b, 3, h, w, device=score_map.device, dtype=score_map.dtype)+ return getattr(aliked, method)(image, **kwargs)+ finally:+ hook.remove()++ @staticmethod+ def _tol(dtype):+ # an isolated peak lands on its pixel; in half precision DKD computes in the map's dtype, so 0.25 px+ return 0.25 if dtype in (torch.float16, torch.bfloat16) else 1e-4++ @staticmethod+ def _top_k(k, device, dtype):+ return ALIKED(model_name="aliked-t16", max_num_keypoints=k, detection_threshold=0.0).to(device, dtype).eval()++ def test_top_k_returns_only_the_maxima_when_the_map_has_fewer_than_k_5862(self, device, dtype):+ # Three maxima, returned by score: k = 3 returns them; k = 5 and k = 10000 (more than the 64 * 96 pixels)+ # return the same three, never a non-maximum.+ peaks = [(0, 60, 40, 0.8), (0, 21, 13, 0.9), (0, 35, 50, 0.7)]+ maxima = torch.tensor([[21.0, 13.0], [60.0, 40.0], [35.0, 50.0]], device=device, dtype=dtype)+ # relabelling: the transposed map gives the transposed maxima+ peaks_t = [(b, y, x, s) for b, x, y, s in peaks]+ for h, w, peaks_i, maxima_i in ((64, 96, peaks, maxima), (96, 64, peaks_t, maxima.flip(-1))):+ score_map = self._score_map(peaks_i, device, dtype, h=h, w=w)+ for k in (3, 5, 10000):+ (feats,) = self._run(self._top_k(k, device, dtype), score_map)+ assert feats.n == 3, (h, w, k, feats.n)+ self.assert_close(feats.keypoints, maxima_i, rtol=0.0, atol=self._tol(dtype))++ def test_top_k_above_the_pixel_count_returns_the_maxima_5862(self, device, dtype):+ # k larger than the number of pixels does not raise. A 3 x 5 image has no position 2 px inside its border, so+ # no keypoint; a 5 x 7 image with one maximum at (3, 2) and k = 40 gets that maximum. extract_dense_map pads+ # the image around its centre to 32 x 32 and crops the score map back, so the hook places the small map at+ # that offset of the 32 x 32 score-head output.+ for h, w, peaks, expected in ((3, 5, [], []), (5, 7, [(0, 3, 2, 0.9)], [[3.0, 2.0]])):+ small = self._score_map(peaks, device, dtype, h=h, w=w)+ padded = torch.full((1, 1, 32, 32), 0.01, device=device, dtype=dtype)+ top, left = (32 - h) // 2, (32 - w) // 2+ padded[..., top : top + h, left : left + w] = small+ aliked = self._top_k(w * h + 5, device, dtype)+ hook = aliked.score_head.register_forward_hook(lambda m, i, o, p=padded: torch.logit(p))+ try:+ with torch.no_grad():+ (feats,) = aliked(torch.rand(1, 3, h, w, device=device, dtype=dtype))+ lafs, _, _ = aliked.forward_laf(torch.rand(1, 3, h, w, device=device, dtype=dtype))+ finally:+ hook.remove()+ assert feats.n == len(expected)+ assert lafs.shape == (1, len(expected), 2, 3)+ if expected:+ expected_t = torch.tensor(expected, device=device, dtype=dtype)+ self.assert_close(feats.keypoints, expected_t, rtol=0.0, atol=self._tol(dtype))++ def test_top_k_keeps_no_keypoint_in_the_border_or_the_padding_5862(self, device, dtype):+ # A batch padded to 64 x 96: image 0 is valid on (W, H) = (80, 50), image 1 on the whole slot. The peaks at+ # (88, 30) and (30, 58) lie in image 0's padding, so with k = 6 image 0 keeps its two maxima and image 1 its+ # one, and every keypoint lies at least nms_radius = 2 px inside its image.+ peaks = [(0, 21, 13, 0.9), (0, 60, 40, 0.8), (0, 88, 30, 0.95), (0, 30, 58, 0.95), (1, 47, 10, 0.9)]+ image_size = torch.tensor([[80, 50], [96, 64]], device=device)+ expected = [[[21.0, 13.0], [60.0, 40.0]], [[47.0, 10.0]]]+ feats = self._run(+ self._top_k(6, device, dtype), self._score_map(peaks, device, dtype, batch=2), image_size=image_size+ )+ assert [f.n for f in feats] == [2, 1]+ for f, (w, h), expected_i in zip(feats, image_size.tolist(), expected):+ self.assert_close(+ f.keypoints, torch.tensor(expected_i, device=device, dtype=dtype), rtol=0.0, atol=self._tol(dtype)+ )+ assert (f.keypoints >= 2).all()+ assert (f.keypoints[:, 0] <= w - 3).all()+ assert (f.keypoints[:, 1] <= h - 3).all()++ def test_forward_laf_top_k_pads_per_image_and_keeps_the_mask_5862(self, device, dtype):+ # forward_laf pads every image to the largest count of the batch with zero frames, zero responses and zero+ # descriptors. Image 0 has three maxima and image 1 one, with k = 5: three slots, two of them padding in+ # image 1. A mask that keeps x < 48 leaves two maxima in image 0 and the one in image 1.+ peaks = [(0, 21, 13, 0.9), (0, 60, 40, 0.8), (0, 35, 50, 0.7), (1, 40, 10, 0.9)]+ score_map = self._score_map(peaks, device, dtype, batch=2)+ aliked = self._top_k(5, device, dtype)+ mask = torch.zeros(2, 1, 64, 96, device=device, dtype=dtype)+ mask[..., :48] = 1.0+ for kwargs, expected in (+ ({}, [[[21.0, 13.0], [60.0, 40.0], [35.0, 50.0]], [[40.0, 10.0]]]),+ ({"mask": mask}, [[[21.0, 13.0], [35.0, 50.0]], [[40.0, 10.0]]]),+ ):+ lafs, responses, descs = self._run(aliked, score_map, "forward_laf", compute_affine=False, **kwargs)+ n = len(expected[0])+ assert lafs.shape == (2, n, 2, 3)+ assert responses.shape == (2, n, 1)+ assert descs.shape[:2] == (2, n)+ filled = laf_is_filled(lafs)+ assert filled.tolist() == [[True] * n, [True] + [False] * (n - 1)]+ for i, expected_i in enumerate(expected):+ centres = lafs[i, filled[i], :, 2]+ self.assert_close(+ centres, torch.tensor(expected_i, device=device, dtype=dtype), rtol=0.0, atol=self._tol(dtype)+ )+ assert lafs[1, 1:].abs().max() == 0+ assert responses[1, 1:].abs().max() == 0+ assert descs[1, 1:].abs().max() == 0++ def test_threshold_fallback_is_decided_per_image_5865(self, device, dtype):+ # The weak image's maxima, 0.15 and 0.12, are below detection_threshold = 0.2, so it keeps the maxima above+ # its mean score; the strong image keeps its maxima above 0.2. Each image gets the same keypoints alone and in+ # a batch, in either order.+ strong = [(0, 21, 13, 0.9), (0, 60, 40, 0.5), (0, 35, 50, 0.1)]+ weak = [(0, 30, 20, 0.15), (0, 70, 45, 0.12)]+ aliked = ALIKED(model_name="aliked-t16").to(device, dtype).eval()+ alone = [self._run(aliked, self._score_map(p, device, dtype))[0] for p in (strong, weak)]+ assert [f.n for f in alone] == [2, 2]+ for order in ((0, 1), (1, 0)):+ peaks = [(i, x, y, s) for i, j in enumerate(order) for _, x, y, s in (strong, weak)[j]]+ batched = self._run(aliked, self._score_map(peaks, device, dtype, batch=2))+ for i, j in enumerate(order):+ self.assert_close(batched[i].keypoints, alone[j].keypoints, rtol=0.0, atol=0.0)+ self.assert_close(batched[i].keypoint_scores, alone[j].keypoint_scores, rtol=0.0, atol=0.0)diff --git a/tests/feature/test_disk.py b/tests/feature/test_disk.pyindex 06341ca0e..93d67072b 100644--- a/tests/feature/test_disk.py+++ b/tests/feature/test_disk.py@@ -104,3 +104,108 @@ class TestDisk(BaseTester):inp = torch.ones(1, 1, 64, 64, device=device)with pytest.raises(ValueError):_ = disk(inp)+++class TestDiskKeypointSelection(BaseTester):+ """``n`` is an upper bound: with ``n`` maxima or fewer, every maximum is a keypoint (#5864)."""++ class _FixedUNet(torch.nn.Module):+ # The public ``unet`` argument of DISK, returning a fixed output.+ def __init__(self, out: torch.Tensor) -> None:+ super().__init__()+ self.out = out++ def forward(self, images: torch.Tensor) -> torch.Tensor:+ return self.out++ @staticmethod+ def _heatmaps(peaks, batch=1, h=48, w=80):+ # (batch, h, w) heatmaps of -1 with the given peaks (image, x, y, logit)+ heatmaps = torch.full((batch, h, w), -1.0, dtype=torch.float64)+ for b, x, y, logit in peaks:+ heatmaps[b, y, x] = logit+ return heatmaps++ def _features(self, heatmaps, device, dtype, **kwargs):+ # DISK whose U-Net returns the heatmaps and descriptor channels (column, row, 1), so a descriptor names its+ # pixel; returns per image the sorted (x, y, score) of its keypoints and the features themselves+ b, h, w = heatmaps.shape+ yy, xx = torch.meshgrid(+ torch.arange(h, dtype=torch.float64), torch.arange(w, dtype=torch.float64), indexing="ij"+ )+ out = torch.stack([xx.expand(b, h, w), yy.expand(b, h, w), torch.ones(b, h, w, dtype=torch.float64), heatmaps])+ disk = DISK(desc_dim=3, unet=self._FixedUNet(out.transpose(0, 1).to(device, dtype))).eval()+ feats = disk(torch.rand(b, 3, h, w, device=device, dtype=dtype), **kwargs)+ kept = [+ sorted((x, y, s) for (x, y), s in zip(f.keypoints.tolist(), f.detection_scores.tolist())) for f in feats+ ]+ return kept, feats++ def test_n_at_or_above_the_number_of_maxima_returns_every_maximum_5864(self, device, dtype):+ # Five maxima of a 48 x 80 heatmap. n = 4 keeps the four strongest; n = 5 and n = 55 return the same keypoints,+ # descriptors and scores as n = None, in the same (raster) order.+ peaks = [(0, 13, 21, 2.0), (0, 50, 9, 1.5), (0, 60, 33, 1.0), (0, 27, 40, 0.5), (0, 70, 14, 3.0)]+ expected = sorted((float(x), float(y), s) for _, x, y, s in peaks)+ # relabelling: the transposed heatmap gives the transposed keypoints+ peaks_t = [(b, y, x, s) for b, x, y, s in peaks]+ for heatmaps, expected_i in (+ (self._heatmaps(peaks), expected),+ (self._heatmaps(peaks_t, h=80, w=48), sorted((y, x, s) for x, y, s in expected)),+ ):+ (kept_all,), (feats_all,) = self._features(heatmaps, device, dtype)+ assert kept_all == expected_i+ (kept_4,), _ = self._features(heatmaps, device, dtype, n=4)+ assert kept_4 == [k for k in expected_i if k[2] != 0.5]+ for n in (5, 55):+ (kept_n,), (feats_n,) = self._features(heatmaps, device, dtype, n=n)+ assert kept_n == expected_i+ self.assert_close(feats_n.keypoints, feats_all.keypoints, rtol=0.0, atol=0.0)+ self.assert_close(feats_n.descriptors, feats_all.descriptors, rtol=0.0, atol=0.0)+ self.assert_close(feats_n.detection_scores, feats_all.detection_scores, rtol=0.0, atol=0.0)++ def test_n_is_applied_per_image_and_an_image_without_maxima_returns_none_5864(self, device, dtype):+ # n = 3 on a batch of three: five maxima give the three strongest, two give both, and a heatmap without a+ # maximum gives no keypoint.+ peaks = [(0, 13, 21, 2.0), (0, 50, 9, 1.5), (0, 60, 33, 1.0), (0, 27, 40, 0.5), (0, 70, 14, 3.0)]+ peaks += [(1, 33, 30, 1.25), (1, 8, 12, 0.75)]+ kept, _ = self._features(self._heatmaps(peaks, batch=3), device, dtype, n=3)+ assert kept == [+ [(13.0, 21.0, 2.0), (50.0, 9.0, 1.5), (70.0, 14.0, 3.0)],+ [(8.0, 12.0, 0.75), (33.0, 30.0, 1.25)],+ [],+ ]++ def test_n_counts_the_maxima_above_score_threshold_5864(self, device, dtype):+ # n counts the maxima above score_threshold: of five maxima, three are strictly above 1.0, so n = 3, 4 and 10+ # keep those three, and n = 2 the two strongest of them.+ peaks = [(0, 13, 21, 2.0), (0, 50, 9, 1.5), (0, 60, 33, 1.0), (0, 27, 40, 0.5), (0, 70, 14, 3.0)]+ heatmaps = self._heatmaps(peaks)+ scores = {}+ for n in (None, 2, 3, 4, 10):+ (kept,), _ = self._features(heatmaps, device, dtype, n=n, score_threshold=1.0)+ scores[n] = sorted(s for _, _, s in kept)+ three = [1.5, 2.0, 3.0]+ assert scores == {None: three, 2: [2.0, 3.0], 3: three, 4: three, 10: three}++ def test_n_takes_maxima_tied_at_the_cut_in_raster_order_5864(self, device, dtype):+ # With more maxima than n, the n strongest are kept, and maxima tied at the n-th score are taken in raster+ # order (row by row) until there are n. The maxima (50, 9) and (20, 33) tie at 2.0 across the cut at n = 2:+ # (50, 9) comes first in raster order and is kept. Transposing the heatmap swaps their raster order, so the+ # transposed (20, 33) is kept instead. n = 0 keeps nothing.+ peaks = [(0, 13, 21, 3.0), (0, 50, 9, 2.0), (0, 20, 33, 2.0), (0, 60, 40, 1.0)]+ peaks_t = [(b, y, x, s) for b, x, y, s in peaks]+ expected = {+ 0: [],+ 1: [(13.0, 21.0, 3.0)],+ 2: [(13.0, 21.0, 3.0), (50.0, 9.0, 2.0)],+ 3: [(13.0, 21.0, 3.0), (20.0, 33.0, 2.0), (50.0, 9.0, 2.0)],+ 4: [(13.0, 21.0, 3.0), (20.0, 33.0, 2.0), (50.0, 9.0, 2.0), (60.0, 40.0, 1.0)],+ }+ expected_t = {n: sorted((y, x, s) for x, y, s in kept) for n, kept in expected.items()}+ expected_t[2] = [(21.0, 13.0, 3.0), (33.0, 20.0, 2.0)]+ for heatmaps, expected_i in (+ (self._heatmaps(peaks), expected),+ (self._heatmaps(peaks_t, h=80, w=48), expected_t),+ ):+ kept = {n: self._features(heatmaps, device, dtype, n=n)[0][0] for n in expected_i}+ assert kept == expected_i