Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(feature): map ScaleSpaceDetector octaves to the image exactly (#5677)

Dmytro Mishkin58262b9f1442
diff --git a/changelog.d/5677.fixed.md b/changelog.d/5677.fixed.md
new file mode 100644
index 000000000..ab7b194ca
--- /dev/null
+++ b/changelog.d/5677.fixed.md
@@ -0,0 +1 @@
+`ScaleSpaceDetector` now places each detection where its octave pixel lies in the input image. It used to scale octave coordinates by the nominal spacing `2**o`, but `ScalePyramid` resizes with `align_corners=True`, which maps octave pixel `u` to input pixel `u * (W - 1) / (W_o - 1)` and the same along `y`. Detections from a doubled first octave were up to half a pixel too far from the origin. Detections from every coarser octave were pulled towards the origin, by several pixels on large images. `HesAffNetHardNet`, `GFTTAffNetHardNet` and `SIFTFeatureScaleSpace` (with its default `"patch"` backend) are affected. The `ScalePyramid` documentation now states the map and that `pixel_dists` is nominal.
diff --git a/kornia/feature/scale_space_detector.py b/kornia/feature/scale_space_detector.py
index 11fa9b2cd..eab2fbd79 100644
--- a/kornia/feature/scale_space_detector.py
+++ b/kornia/feature/scale_space_detector.py
@@ -224,7 +224,10 @@ class ScaleSpaceDetector(nn.Module):
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, 16, extra_levels=3)`` with a scale-space response,
- ``extra_levels=2`` without. Each octave searches ``n_levels`` response levels, levels
+ ``extra_levels=2`` without. A detection at octave pixel :math:`(u, v)` is reported at
+ :math:`(u (W - 1) / (W_o - 1), v (H - 1) / (H_o - 1))` in the input, the map of
+ :class:`~kornia.geometry.ScalePyramid`'s ``align_corners=True`` resizes; a custom pyramid has to
+ resize the same way. 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``.
@@ -361,7 +364,7 @@ class ScaleSpaceDetector(nn.Module):
num_levels: int,
is_iterative_subpix: bool,
batchable_subpix: bool,
- px_size: float,
+ octave_to_image: Tuple[float, float],
) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
"""Process one scale-space octave: response β†’ NMS/subpix β†’ top-K β†’ LAF.
@@ -568,7 +571,9 @@ class ScaleSpaceDetector(nn.Module):
# real detection, however negative; `_detect` zeroes its response and LAF once ranked.
filled = is_cand & good_mask
resp_flat_best = resp_flat_best.masked_fill(~filled, float("-inf"))
- current_lafs.mul_(px_size)
+ # Octave pixels to input pixels, per axis: x scales the first LAF row, y the second.
+ current_lafs[:, :, 0, :].mul_(octave_to_image[0])
+ current_lafs[:, :, 1, :].mul_(octave_to_image[1])
return resp_flat_best, current_lafs, filled
def _detect(
@@ -601,8 +606,13 @@ class ScaleSpaceDetector(nn.Module):
# compiled one passed by the caller, is dispatched consistently on both the single-sign and
# the minima-and-maxima path.
is_iterative_subpix, batchable_subpix = _subpix_dispatch(self.subpix)
- px_size0 = 0.5 if self.scale_pyr.double_image else 1.0
- px_sizes = [px_size0 * (2.0**i) for i in range(len(sp))]
+ # ScalePyramid resizes with align_corners=True, which keeps the first and last pixel centres: octave pixel u
+ # is input pixel u * (W - 1) / (W_o - 1) along x, and likewise along y. The nominal spacing 2 ** o is off by
+ # up to half a pixel on a doubled octave and by more on every coarser one.
+ H, W = img.shape[-2:]
+ octave_to_image = [
+ ((W - 1) / max(octave.shape[-1] - 1, 1), (H - 1) / max(octave.shape[-2] - 1, 1)) for octave in sp
+ ]
# ── Process octaves sequentially ────────────────────────────────────
# All octaves are independent once the scale pyramid is built, but CUDA
@@ -620,7 +630,7 @@ class ScaleSpaceDetector(nn.Module):
num_levels,
is_iterative_subpix,
batchable_subpix,
- px_sizes[i],
+ octave_to_image[i],
)
for i in range(n_oct)
]
diff --git a/kornia/geometry/transform/pyramid.py b/kornia/geometry/transform/pyramid.py
index c55060bc8..547ed9b6c 100644
--- a/kornia/geometry/transform/pyramid.py
+++ b/kornia/geometry/transform/pyramid.py
@@ -163,7 +163,10 @@ class ScalePyramid(nn.Module):
- an ``init_sigma`` below the assumed input blur (``0.5``, or ``1.0`` with
``double_image=True``) leaves the first level at that blur, and the octave is built and
labelled from it, as if ``init_sigma`` were the assumed input blur
- - the internal resizes use ``align_corners=True``; there is no ``align_corners`` parameter
+ - the internal resizes use ``align_corners=True``; there is no ``align_corners`` parameter. They keep the
+ first and last pixel centres, so pixel :math:`(u, v)` of octave ``o`` is input pixel
+ :math:`(u (W - 1) / (W_o - 1), v (H - 1) / (H_o - 1))`; ``pixel_dists`` is the nominal spacing
+ :math:`2^o` (:math:`2^{o - 1}` with ``double_image=True``), not this map
Args:
n_levels: number of the levels in octave.
@@ -174,7 +177,7 @@ class ScalePyramid(nn.Module):
Returns:
1st output: images
2nd output: sigmas (coefficients for scale conversion)
- 3rd output: pixelDists (coefficients for coordinate conversion)
+ 3rd output: pixelDists (nominal pixel spacing of each level relative to the input)
Shape:
- Input: :math:`(B, C, H, W)`
@@ -300,8 +303,9 @@ class ScalePyramid(nn.Module):
Returns:
Tuple ``(cur_level, cur_sigma, pixel_distance)``. ``cur_level`` is
the first image level, ``cur_sigma`` is its effective blur sigma,
- and ``pixel_distance`` tells how one pixel in this level maps back
- to the original input image.
+ and ``pixel_distance`` is the level's nominal pixel spacing in input
+ pixels (``0.5`` when doubled). It is not the coordinate map: see the
+ class Convention for where a level pixel lies in the input.
"""
pixel_distance = 1.0
cur_sigma = 0.5
@@ -344,8 +348,9 @@ class ScalePyramid(nn.Module):
image levels, ``sigmas`` contains the octave-relative nominal blur
sigma for each level (multiply by the matching ``pixel_dists``
entry for the nominal absolute blur in original-image pixels), and
- ``pixel_dists`` contains the pixel spacing of each level relative
- to the original image.
+ ``pixel_dists`` contains the nominal pixel spacing of each level
+ relative to the original image. It is not the coordinate map: see
+ the class Convention for where an octave pixel lies in the input.
"""
bs, _, _, _ = x.size()
cur_level, cur_sigma, pixel_distance = self.get_first_level(x)
diff --git a/tests/feature/test_scale_space_detector.py b/tests/feature/test_scale_space_detector.py
index 4eceeca50..b7eae5322 100644
--- a/tests/feature/test_scale_space_detector.py
+++ b/tests/feature/test_scale_space_detector.py
@@ -504,8 +504,12 @@ class TestScaleSpaceDetector(BaseTester):
lafs, resps = det(torch.zeros(1, 1, 96, 96, device=device, dtype=dtype))
assert (resps == 0).all()
centers = lafs[0, :, :, 2]
- found = (centers == 48).all(dim=-1)
- assert int(found.sum()) == 3, f"expected the three centre maxima, got {centers.tolist()}"
+ # The maximum sits at octave pixel W_o // 2 of the 96, 48 and 24 px octaves, which ScalePyramid's
+ # align_corners=True resizes put at 48, 24 * 95 / 47 and 12 * 95 / 23 in the input.
+ expected = torch.tensor([48.0, 24 * 95 / 47, 12 * 95 / 23], device=device, dtype=dtype)
+ atol = {torch.float16: 0.02, torch.bfloat16: 0.13, torch.float32: 1e-4}.get(dtype, 1e-9)
+ found = torch.isclose(centers[:, None, :], expected[None, :, None], rtol=0.0, atol=atol).all(-1).any(0)
+ assert bool(found.all()), f"expected the three maxima at {expected.tolist()}, got {centers.tolist()}"
def test_batched_underfill_does_not_leak_the_topk_sentinel(self, device, dtype):
# For B > 1 the octave top-K ranks over the whole volume with non-candidates masked to
@@ -677,6 +681,50 @@ class TestScaleSpaceDetector(BaseTester):
self.assert_close(lafs[1], lafs[0])
self.assert_close(resps[1], resps[0])
+ @pytest.mark.parametrize(
+ "double_image, sigma, octave_div",
+ [
+ (True, 1.5, 0.5),
+ (True, 3.0, 1),
+ (True, 6.0, 2),
+ (True, 12.0, 4),
+ (False, 3.0, 1),
+ (False, 6.0, 2),
+ (False, 12.0, 4),
+ ],
+ )
+ def test_detection_lands_on_the_blob_centre_in_every_octave_5675(
+ self, device, dtype, double_image, sigma, octave_div
+ ):
+ # One blob per octave, far from the origin. ScalePyramid resizes with align_corners=True, so octave pixel u
+ # is input pixel u * (W - 1) / (W_o - 1); mapping it by 2 ** o instead put the doubled octave ~0.4 px past
+ # the blob and pulled every coarser octave towards the origin, by ~0.8 px at 1/2 and ~2.3 px at 1/4.
+ if dtype in (torch.float16, torch.bfloat16):
+ pytest.skip("the sub-pixel refinement alone moves a half-precision centre by more than the tolerance")
+ h, w = 241, 320
+ yy, xx = torch.meshgrid(
+ torch.arange(h, dtype=torch.float64), torch.arange(w, dtype=torch.float64), indexing="ij"
+ )
+ blob = torch.exp(-((xx - 251.3) ** 2 + (yy - 180.6) ** 2) / (2 * sigma**2))
+ det = ScaleSpaceDetector(
+ 4,
+ resp_module=kornia.feature.BlobHessian(),
+ scale_pyr_module=ScalePyramid(3, 1.6, 15, double_image=double_image, extra_levels=2),
+ ).to(device, dtype)
+ lafs, _ = det(blob[None, None].to(device, dtype))
+ expected = torch.tensor([[251.3, 180.6]], device=device, dtype=dtype)
+ self.assert_close(kornia.feature.get_laf_center(lafs)[0, :1], expected, rtol=0.0, atol=0.1)
+ # The frame follows the same per-axis map. With an odd height the two factors differ (by 0.05 % on the
+ # doubled octave, 0.5 % at 1/2, 0.7 % at 1/4), so an isotropic frame in octave units fails the ratio.
+ h_o, w_o = (2 * h, 2 * w) if octave_div == 0.5 else (h // octave_div, w // octave_div)
+ sx, sy = (w - 1) / (w_o - 1), (h - 1) / (h_o - 1)
+ frame = lafs[0, 0, :, :2]
+ assert frame[0, 1] == 0
+ assert frame[1, 0] == 0
+ self.assert_close(
+ frame[1, 1] / frame[0, 0], torch.tensor(sy / sx, device=device, dtype=dtype), rtol=1e-5, atol=0.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.