Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(feature): search each scale once in ScaleSpaceDetector (#5672)

Dmytro Mishkin3e9da1cfb147
diff --git a/changelog.d/5672.fixed.md b/changelog.d/5672.fixed.md
new file mode 100644
index 000000000..13b77ddaa
--- /dev/null
+++ b/changelog.d/5672.fixed.md
@@ -0,0 +1 @@
+`ScaleSpaceDetector` now searches exactly `n_levels` response levels per octave and uses the levels below and above them only as NMS neighbours. With a per-level response such as `BlobHessian` or `CornerGFTT` and a `ScalePyramid` with three extra levels, it used to search one more level. That level has the same scale as level 1 of the next octave, so every octave-boundary scale was detected twice, and the near-identical twins failed the ratio test in matching. `HesAffNetHardNet` and `GFTTAffNetHardNet` were affected. Their scale pyramid now also builds one level fewer per octave.
diff --git a/kornia/feature/integrated.py b/kornia/feature/integrated.py
index f8f7bf0d8..10f8fce68 100644
--- a/kornia/feature/integrated.py
+++ b/kornia/feature/integrated.py
@@ -425,7 +425,8 @@ class GFTTAffNetHardNet(LocalFeature):
detector = ScaleSpaceDetector(
num_features,
resp_module=CornerGFTT(),
- scale_pyr_module=ScalePyramid(3, 1.6, 32, double_image=True),
+ # A per-level response reads n_levels + 2 levels per octave; a third extra level is never read.
+ scale_pyr_module=ScalePyramid(3, 1.6, 32, double_image=True, extra_levels=2),
ori_module=PassLAF() if upright else LAFOrienter(19),
aff_module=LAFAffNetShapeEstimator(True, preserve_orientation=False).eval(),
scale_space_response=False,
@@ -452,7 +453,8 @@ class HesAffNetHardNet(LocalFeature):
detector = ScaleSpaceDetector(
num_features,
resp_module=BlobHessian(),
- scale_pyr_module=ScalePyramid(3, 1.6, 32, double_image=True),
+ # A per-level response reads n_levels + 2 levels per octave; a third extra level is never read.
+ scale_pyr_module=ScalePyramid(3, 1.6, 32, double_image=True, extra_levels=2),
ori_module=PassLAF() if upright else LAFOrienter(19),
aff_module=LAFAffNetShapeEstimator(True, preserve_orientation=False).eval(),
scale_space_response=False,
diff --git a/kornia/feature/scale_space_detector.py b/kornia/feature/scale_space_detector.py
index 40495ac5e..11fa9b2cd 100644
--- a/kornia/feature/scale_space_detector.py
+++ b/kornia/feature/scale_space_detector.py
@@ -223,7 +223,11 @@ class ScaleSpaceDetector(nn.Module):
mr_size: multiplier for local feature scale compared to the detection scale.
6.0 is matching OpenCV 12.0 convention for SIFT.
scale_pyr_module: generates scale pyramid. See :class:`~kornia.geometry.ScalePyramid` for details.
- Default: ScalePyramid(3, 1.6, 15).
+ Default: ``ScalePyramid(3, 1.6, 16, extra_levels=3)`` with a scale-space response,
+ ``extra_levels=2`` without. Each octave searches ``n_levels`` response levels, levels
+ ``1..n_levels``; the levels below and above them are NMS neighbours only, and any further
+ level 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.
@@ -368,6 +372,15 @@ class ScaleSpaceDetector(nn.Module):
since the response alone cannot.
"""
dev = octave.device
+ # An octave searches `num_levels` response levels, 1..num_levels; levels 0 and num_levels + 1 are only
+ # their NMS neighbours. A further level would make level num_levels + 1 searchable too, and that level has
+ # the scale of level 1 of the next octave, which the per-octave NMS never compares it with: that scale
+ # would be detected twice. A per-level response is computed on the levels it needs only; a scale-space
+ # response is cut once it has run.
+ n_resp_levels = num_levels + 2
+ if not self.scale_space_response:
+ octave = octave[:, :, :n_resp_levels]
+ sigmas_oct = sigmas_oct[:, :n_resp_levels]
B, CH, L, H, W = octave.size()
# Run response function
@@ -376,7 +389,7 @@ class ScaleSpaceDetector(nn.Module):
oct_resp = self.resp(octave, sigmas_oct.view(-1)) # (B, 1, Ldog, H, W)
else:
with self._dynamo_config_patch(("resp",)):
- level_resp = self.resp(octave.permute(0, 2, 1, 3, 4).reshape(B * L, CH, H, W), sigmas_oct.view(-1))
+ level_resp = self.resp(octave.permute(0, 2, 1, 3, 4).reshape(B * L, CH, H, W), sigmas_oct.reshape(-1))
KORNIA_CHECK(
level_resp.dim() == 4
and level_resp.shape[0] == B * L
@@ -396,8 +409,8 @@ class ScaleSpaceDetector(nn.Module):
)
# Iterative sub-pixel modules flatten the full response volume internally. The
# level/channel permutation above is contiguous when CH == 1 (the common path), but
- # not for a response that preserves multiple channels.
- oct_resp = oct_resp.contiguous()
+ # not for a response that preserves multiple channels, nor for a scale-space response cut to its levels.
+ oct_resp = oct_resp[:, :, :n_resp_levels].contiguous()
scale_sigmas = sigmas_oct[:, : oct_resp.shape[2]]
# Always precompute NMS masks in one fused pass.
diff --git a/tests/feature/test_scale_space_detector.py b/tests/feature/test_scale_space_detector.py
index 83d8a4f39..4eceeca50 100644
--- a/tests/feature/test_scale_space_detector.py
+++ b/tests/feature/test_scale_space_detector.py
@@ -617,6 +617,66 @@ class TestScaleSpaceDetector(BaseTester):
assert lafs.shape == torch.Size([1, n_feats, 2, 3])
assert resps.shape == torch.Size([1, n_feats])
+ @pytest.mark.parametrize("sigma", [2.016, 4.032])
+ def test_octave_boundary_scale_is_detected_once_5670(self, device, dtype, sigma):
+ # sigma = 1.6 * 2 ** (4 / 3) * 2 ** k is level 4 of one octave and level 1 of the next. With
+ # extra_levels=3 a per-level response has a level 4 in every octave, but it is only the NMS neighbour of
+ # level 3: searching it as well found this blob once in each octave.
+ if dtype == torch.bfloat16:
+ pytest.skip(
+ "in bfloat16 the octave-1 copy of this blob does not survive NMS, with or without a spare level"
+ )
+ yy, xx = torch.meshgrid(
+ torch.arange(160, dtype=torch.float64), torch.arange(200, dtype=torch.float64), indexing="ij"
+ )
+ blob = torch.exp(-((xx - 150.3) ** 2 + (yy - 110.6) ** 2) / (2 * sigma**2))
+ img = blob[None, None].to(device, dtype)
+ det = ScaleSpaceDetector(
+ 16,
+ resp_module=kornia.feature.BlobHessian(),
+ scale_pyr_module=ScalePyramid(3, 1.6, 32, double_image=True, extra_levels=3),
+ ).to(device, dtype)
+ lafs, resps = det(img)
+ found = kornia.feature.laf_is_filled(lafs)[0] & (resps[0] > 1e-3 * resps[0].max())
+ assert int(found.sum()) == 1
+
+ @pytest.mark.parametrize(
+ "resp_module, scale_space_response, minima_are_also_good, extra_levels",
+ [
+ (kornia.feature.BlobHessian, False, False, (2, 3)),
+ (kornia.feature.BlobDoG, True, True, (3, 4)),
+ ],
+ )
+ def test_spare_pyramid_levels_do_not_change_the_detections_5670(
+ self, device, dtype, resp_module, scale_space_response, minima_are_also_good, extra_levels
+ ):
+ # Each octave searches response levels 1..n_levels, and levels 0 and n_levels + 1 are their NMS
+ # neighbours. A pyramid that builds a level past those detects exactly what the minimal one does.
+ # Bright and dark blobs from below the first octave boundary to above the second.
+ yy, xx = torch.meshgrid(
+ torch.arange(96, device=device, dtype=dtype), torch.arange(128, device=device, dtype=dtype), indexing="ij"
+ )
+ img = torch.zeros_like(xx)
+ for i, sigma in enumerate((1.3, 1.6, 2.016, 2.6, 3.2, 4.032, 5.0)):
+ cx, cy = 18.0 + 15.0 * i, 30.0 + 36.0 * (i % 2)
+ img = img + (-1) ** i * torch.exp(-((xx - cx) ** 2 + (yy - cy) ** 2) / (2 * sigma**2))
+ img = img[None, None]
+ lafs, resps = [], []
+ for extra in extra_levels:
+ det = ScaleSpaceDetector(
+ 30,
+ mr_size=1.0,
+ resp_module=resp_module(),
+ scale_pyr_module=ScalePyramid(3, 1.6, 16, extra_levels=extra),
+ scale_space_response=scale_space_response,
+ minima_are_also_good=minima_are_also_good,
+ ).to(device, dtype)
+ out_lafs, out_resps = det(img)
+ lafs.append(out_lafs)
+ resps.append(out_resps)
+ self.assert_close(lafs[1], lafs[0])
+ self.assert_close(resps[1], resps[0])
+
def test_few_detections_padding(self, device, dtype):
# Constant image β†’ very few (possibly zero) NMS candidates; output must still
# have the requested shape because the detect() method pads with zeros.