π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(feature): return the true top-k from MultiResolutionDetector.detect (#4222)
Dmytro Mishkin25b2ca728703
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex f4f883c55..1a35f30f0 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -343,6 +343,23 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0the quotas always sum to exactly `num_features` and stay spread across scales. #4098's narrower `num_features=1`fallback, which handed the request's one slot to the largest-share level when every quota floored to zero, isthe special case where the shortfall equals `num_features` and is superseded by the general apportionment.+ The apportionment was then removed again by #4222 below, inside this same unreleased window, so no release+ ever carries it; the `num_features=1` behaviour it fixed still holds.++* `MultiResolutionDetector.detect` now returns the `num_features` highest responses in the image (#4222). Each+ pyramid level used to be asked only for its own share of the budget, so a level could contribute at most+ `quotas[0]` (the upscaled level) or `sum(quotas[: i + 1 + up_levels])` (pyramid level `i`) -- both well under+ `num_features` for the finer levels. When an image's strongest maxima concentrated on one level, which is the+ common case rather than a corner case, the excess was never requested and so could not be ranked in by the+ final global `topk`: the detector silently returned something other than the top-k, and the sorted responses of+ `detect(k)` were not a prefix of those of `detect(k')`. Every level is now searched for `num_features` candidates, which is exactly sufficient+ because the detections a level contributes to the global top-k are that level's own strongest. The per-level+ apportionment, including #4101's largest-remainder rounding, is removed with it. This changes which keypoints+ are returned for a given image: callers get strictly better-ranked detections, and any result that depended on+ the old per-level spread will differ. The prefix is on the sorted responses, not on which detection carries a+ given response: `topk` breaks a tie by position, so exactly equal maxima can come back in a different order for+ a different `num_features`. It carries about 1.2x the candidates through the concatenation, which is not+ measurable next to the response function and the non-maxima suppression.* Make YUV and XYZ transformations compute integer inputs in `float32` instead of truncating their kernels, andpreserve directly constructed `float64` coefficients. This makes `rgb_to_yuv(uint8)` return `float32` on thediff --git a/kornia/feature/scale_space_detector.py b/kornia/feature/scale_space_detector.pyindex 584176dca..2e3602008 100644--- a/kornia/feature/scale_space_detector.py+++ b/kornia/feature/scale_space_detector.py@@ -657,7 +657,12 @@ class MultiResolutionDetector(nn.Module):Args:model: response function, such as KeyNet or BlobHessian- num_features: Number of features to detect.+ num_features: Number of features to detect. Every pyramid level is searched for this many+ candidates and the whole set is ranked together, so the result is the ``num_features``+ highest responses in the image, and the sorted response vector for one value is a prefix+ of the vector for any larger one. Which detection carries a given response is not pinned+ when responses tie: ``topk`` breaks a tie by position, and the positions it ranks over+ depend on ``num_features``.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.@@ -833,7 +838,8 @@ class MultiResolutionDetector(nn.Module):Returns:Tuple containing detection scores and local affine frames, shaped `(1, num_features)` and- `(1, num_features, 2, 3)`. The shape holds even when the image yields fewer above-threshold maxima+ `(1, num_features, 2, 3)`, holding the `num_features` highest responses in the image and sorted by+ 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 atthat dtype's integer resolution: exact up to 256 in bfloat16 and up to 2048 in float16, and coarser@@ -842,30 +848,16 @@ class MultiResolutionDetector(nn.Module):KORNIA_CHECK_SHAPE(img, ["1", "C", "H", "W"])if mask is not None:_check_mask(mask, img)- # Compute points per level- num_features_per_level: List[float] = []- tmp = 0.0- factor_points = self.scale_factor_levels**2- levels = self.num_pyramid_levels + self.num_upscale_levels + 1- for idx_level in range(levels):- tmp += factor_points ** (-1 * (idx_level - self.num_upscale_levels))- nf = self.num_features * factor_points ** (-1 * (idx_level - self.num_upscale_levels))- num_features_per_level.append(nf)- shares: List[float] = [x / tmp for x in num_features_per_level]- # Largest-remainder (Hamilton) apportionment: `shares` sums to `self.num_features` (up to- # float error), but flooring each one independently discards every fractional part, so the- # floors can sum to well under `self.num_features` -- to zero at `num_features=1`, where the- # default six shares are 0.508 .. 0.016. The finest level's quota also dominates every other- # one's, so a small request degenerates to querying a single scale. Hand the shortfall --- # `self.num_features` minus the sum of floors -- to the levels with the largest fractional- # remainders, one slot each, so the quotas always sum to exactly `self.num_features` and stay- # spread across scales instead of collapsing onto the finest level.- num_features_per_level = [int(x) for x in shares]- shortfall = self.num_features - sum(num_features_per_level)- by_remainder = sorted(range(len(shares)), key=lambda i: shares[i] - num_features_per_level[i], reverse=True)- for idx_level in by_remainder[:shortfall]:- num_features_per_level[idx_level] += 1-+ # Every level is asked for the whole budget, not for a per-level share of it. A share is a+ # cap on what the level may contribute, and the final global `topk` cannot rank in a+ # detection that was never requested, so a per-level quota silently returns something other+ # than the top `num_features` whenever an image's strongest maxima concentrate on one level.+ # Asking each level for `num_features` is exactly sufficient rather than merely generous:+ # the m detections a level contributes to the global top-k are necessarily that level's own+ # top-m, so a request of `num_features` always reaches them. It costs ~1.2x the candidates+ # the old apportionment carried -- the coarse levels were already asked for a cumulative+ # prefix of the quotas, close to `num_features` -- which is not measurable next to the+ # response function and the non-maxima suppression._, _, h, w = img.shapeimg_up = imgcur_img = img@@ -873,16 +865,13 @@ class MultiResolutionDetector(nn.Module):all_lafs: List[torch.Tensor] = []# Extract features from the upper levelsfor idx_level in range(self.num_upscale_levels):- nf = num_features_per_level[len(num_features_per_level) - self.num_pyramid_levels - 1 - (idx_level + 1)]- num_points_level = int(nf)-# Resize input imageup_factor = self.scale_factor_levels ** (1 + idx_level)nh, nw = int(h * up_factor), int(w * up_factor)up_factor_kpts = (float(w) / float(nw), float(h) / float(nh))img_up = resize(img_up, (nh, nw), interpolation="bilinear", align_corners=False)- cur_scores, cur_lafs = self._detect_level(img_up, num_points_level, up_factor_kpts, mask)+ cur_scores, cur_lafs = self._detect_level(img_up, self.num_features, up_factor_kpts, mask)all_responses.append(cur_scores.view(1, -1))all_lafs.append(cur_lafs)@@ -896,11 +885,7 @@ class MultiResolutionDetector(nn.Module):else:factor = (1.0, 1.0)- num_points_level = int(num_features_per_level[idx_level])- if idx_level > 0 or (self.num_upscale_levels > 0):- num_points_level = sum(num_features_per_level[: idx_level + 1 + self.num_upscale_levels])-- cur_scores, cur_lafs = self._detect_level(cur_img, num_points_level, factor, mask)+ cur_scores, cur_lafs = self._detect_level(cur_img, self.num_features, factor, mask)all_responses.append(cur_scores.view(1, -1))all_lafs.append(cur_lafs)responses = torch.cat(all_responses, 1)diff --git a/tests/feature/test_scale_space_detector.py b/tests/feature/test_scale_space_detector.pyindex 286e5f4ca..40ede8d41 100644--- a/tests/feature/test_scale_space_detector.py+++ b/tests/feature/test_scale_space_detector.py@@ -931,9 +931,13 @@ class TestMultiResolutionDetector(BaseTester):assert torch.equal(resps[0], torch.sort(resps[0], descending=True).values)def test_single_feature_request_returns_a_real_detection(self, device, dtype):- # With the default configuration and `num_features=1` every proportional quota truncates- # to zero (the shares are 0.508 .. 0.016), so every level was queried for zero candidates- # and the result was a padded dummy on an image full of maxima.+ # Contract: asking for one feature returns a real detection, and the same one that asking+ # for two would rank first. The original defect was an apportionment that gave every level+ # a share of `num_features`: at `num_features=1` the default configuration's six shares are+ # 0.508 .. 0.016, all of which truncate to zero, so every level was queried for zero+ # candidates and the result was a padded dummy on an image full of maxima. The+ # apportionment is gone -- every level is now asked for `num_features` -- so this pins the+ # contract rather than that mechanism, and it holds under both.torch.manual_seed(11)inp = torch.rand(1, 1, 64, 64, device=device, dtype=dtype)lafs_one, resps_one = self._make_detector(num_features=1).to(device, dtype)(inp)@@ -946,14 +950,16 @@ class TestMultiResolutionDetector(BaseTester):self.assert_close(lafs_one[0, 0], lafs_two[0, int(resps_two[0].argmax())])def test_small_request_spreads_across_scales(self, device, dtype):- # `detect` used to apportion `num_features` across pyramid levels by flooring each level's- # fractional share independently (`int(x) for x in shares`). The shares favor the finest- # level so heavily (0.508 .. 0.016 with the default config) that a small `num_features`- # truncated every other level's quota to zero: five well-separated, equally strong blobs and- # `num_features=3` returned three near-duplicate detections of the single strongest blob- # instead of covering several of them. Largest-remainder (Hamilton) apportionment hands the- # shortfall to the levels with the largest fractional remainder instead, so a small request- # still reaches more than one scale and covers more than one blob.+ # Contract: a small request still covers more than one of several equally strong features+ # rather than returning near-duplicates of the single strongest one. `detect` used to+ # apportion `num_features` across pyramid levels by flooring each level's fractional share+ # independently (`int(x) for x in shares`); the shares favor the finest level so heavily+ # (0.508 .. 0.016 with the default config) that a small `num_features` truncated every other+ # level's quota to zero, and `num_features=3` on five well-separated equal blobs returned+ # three near-duplicate detections of one blob. Largest-remainder apportionment fixed that,+ # and asking every level for `num_features` supersedes it: with no cap the three slots go to+ # the three strongest maxima anywhere, which are on different blobs. The pin is on the+ # coverage, so it holds under all three.img = torch.zeros(1, 1, 96, 96, device=device, dtype=dtype)centers = [(20, 20), (20, 70), (48, 48), (76, 20), (76, 70)]for y, x in centers:@@ -967,6 +973,56 @@ class TestMultiResolutionDetector(BaseTester):)assert covered >= 2, f"expected the 3-feature request to reach at least 2 of the 5 blobs, got {covered}"+ def test_result_for_k_is_a_prefix_of_the_result_for_a_larger_k(self, device, dtype):+ # `detect` used to ask each pyramid level only for its own share of the budget, so a level+ # could contribute at most `quotas[0]` (the upscaled level) or `sum(quotas[: i + 1 + up])`+ # (pyramid level i) -- both well under `num_features` for the finer levels. When an image's+ # strongest maxima concentrate on one level, which is the normal case rather than a corner+ # case, the excess was never requested and so could not be ranked in by the final global+ # `topk`: the result was silently not the top-k, with no signal to the caller. Asking every+ # level for `num_features` makes the union a superset of the true top-k, since the m+ # detections a level contributes to the global top-k are necessarily that level's own top-m.+ #+ # The pin is on the sorted response vector rather than on keypoint identities: `detect`+ # already returns responses in descending order, and comparing values sidesteps both the+ # `topk` tie-break and the fact that one blob can be detected at several scales with the+ # same rounded centre.+ img = torch.zeros(1, 1, 240, 240, device=device, dtype=dtype)+ strength = 0+ for y in range(20, 220, 40): # 25 well-separated blobs, all resolved at the same scale+ for x in range(20, 220, 40):+ img[:, :, y - 1 : y + 2, x - 1 : x + 2] = 1.0 + 0.05 * strength+ strength += 1++ reference, _ = self._make_detector(num_features=32).to(device, dtype).detect(img)+ for k in (4, 8, 16):+ responses, _ = self._make_detector(num_features=k).to(device, dtype).detect(img)+ self.assert_close(responses[0], reference[0, :k])++ def test_the_response_prefix_survives_tied_responses(self, device, dtype):+ # The prefix the docstring promises is on the sorted responses, not on which detection carries+ # a given response. `topk` breaks a tie by position and the positions it ranks over depend on+ # `num_features`, so exactly equal maxima can come back in a different order for a different+ # request: with this input `detect(1)` returns the centre that `detect(2)` ranks *second*.+ # That permutation is `topk`'s to choose and is deliberately not pinned here -- pinning it+ # would codify undefined behaviour that already differs across devices. The response vector+ # staying a prefix is the part that is promised, and it holds under ties too.+ class Identity(torch.nn.Module):+ def forward(self, x: torch.Tensor) -> torch.Tensor:+ return x++ cfg = get_default_detector_config()+ cfg.update({"nms_size": 5, "pyramid_levels": 1, "up_levels": 0})+ img = torch.zeros(1, 1, 64, 64, device=device, dtype=dtype)+ for y, x in ((20, 20), (20, 30), (40, 40)):+ img[:, :, y, x] = 1.0 # three isolated maxima with byte-identical responses++ reference, _ = MultiResolutionDetector(Identity(), num_features=3, config=cfg).to(device, dtype).detect(img)+ assert int((reference[0] != 0).sum()) == 3, "expected all three tied maxima to be detected"+ for k in (1, 2):+ responses, _ = MultiResolutionDetector(Identity(), num_features=k, config=cfg).to(device, dtype).detect(img)+ self.assert_close(responses[0], reference[0, :k])+def test_negative_score_threshold_is_rejected(self, device, dtype):# NMS writes an exact zero at every suppressed position, so a negative threshold would# admit all of them -- and collide with the zero response that marks an unfilled slot.