π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(feature): treat the image extent as w-1/h-1 in laf_is_inside_image (#4078)
Dmytro Mishkine37ddb17b1a0
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 399a31651..ddc211745 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -130,6 +130,20 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0existing FGINN tests pass unchanged on both sides, which is how this survived; two tests that discriminate it wereadded. `match_fginn`'s docstring now also records the saturation corner, where every candidate falls within`spatial_th` of the 1st nearest neighbor, the ratio collapses towards zero and the match is accepted.+* Fix `laf_is_inside_image` treating the image extent as `(w, h)` rather than `(w - 1, h - 1)`, which made its+ bounds asymmetric: the lower bound rejected anything left of `x = 0`, but the upper bound accepted `x = w`, a+ full pixel past the last valid column `w - 1` (#4064). Valid pixel coordinates run `0 .. w-1` and `0 .. h-1` --+ the convention `get_laf_center` documents and the one `normalize_laf`/`denormalize_laf` already use -- so the+ upper bound is now `w - 1 - border` and `h - 1 - border`. A LAF whose boundary points reach past the last valid+ pixel coordinate is now reported as outside; anything strictly inside is unchanged. The equivalent inlined check+ in `ScaleSpaceDetector._process_octave` moved with it, so detections within one pixel of the right or bottom edge+ that used to survive its `border=5` filter are now discarded. That inlined check also computed its `max |sin|`+ constant with the wrong angular spacing (`2*pi/11` instead of the `2*pi/10` that `laf_to_boundary_points(n_pts=12)`+ actually samples), inflating the tested x-extent by 4% and making the inline check stricter than the reference it+ claims to reproduce; the two now agree exactly. That correction is a loosening in x, so it can change+ `ScaleSpaceDetector` output on its own: a detection whose x-extent falls between the two constants used to be+ discarded and is now kept. It is rare -- the detection has to land in a band of width `0.039 * half_s` against the+ x bound -- but when it fires it can promote the strongest response in the image, so it is not output-neutral.## :rocket: [0.6.11] - 2022-03-28diff --git a/kornia/feature/laf.py b/kornia/feature/laf.pyindex 04c3236b4..ee3f40af6 100644--- a/kornia/feature/laf.py+++ b/kornia/feature/laf.py@@ -549,9 +549,11 @@ def laf_is_inside_image(laf: torch.Tensor, images: torch.Tensor, border: int = 0KORNIA_CHECK_LAF(laf)_, _, h, w = images.size()pts = laf_to_boundary_points(laf, 12)- good_lafs_mask = (- (pts[..., 0] >= border) * (pts[..., 0] <= w - border) * (pts[..., 1] >= border) * (pts[..., 1] <= h - border)- )+ # Valid pixel coordinates run 0 .. w-1 and 0 .. h-1, matching the convention documented on+ # `get_laf_center` and the `w - 1` / `h - 1` extent used by `normalize_laf` / `denormalize_laf`.+ x_max = float(w - 1) - border+ y_max = float(h - 1) - border+ good_lafs_mask = (pts[..., 0] >= border) * (pts[..., 0] <= x_max) * (pts[..., 1] >= border) * (pts[..., 1] <= y_max)good_lafs_mask = good_lafs_mask.min(dim=2)[0]return good_lafs_maskdiff --git a/kornia/feature/scale_space_detector.py b/kornia/feature/scale_space_detector.pyindex 7288caf5d..f57c08e0c 100644--- a/kornia/feature/scale_space_detector.py+++ b/kornia/feature/scale_space_detector.py@@ -38,11 +38,11 @@ from .orientation import PassLAFfrom .responses import BlobHessian# Max |sin| among the 11 boundary points sampled by laf_to_boundary_points(n_pts=12):-# angles = linspace(0, 2Ο, 11) β k * 2Ο/11 for k=0..10-# max|sin| at k=3: sin(6Ο/11) β 0.9898; max|cos| at k=0: cos(0) = 1.0+# angles = linspace(0, 2Ο, n_pts - 1) = linspace(0, 2Ο, 11) β k * 2Ο/10 for k=0..10+# max|sin| at k=2 and k=3: sin(2Ο/5) β 0.9511; max|cos| at k=0: cos(0) = 1.0# Used to inline the boundary check in _process_octave for isotropic LAFs (rotmat=eye(2)),# avoiding CPUβGPU allocation + bmm every octave.-_MAX_ABS_SIN_12: float = math.sin(3 * 2 * math.pi / 11) # β 0.9898+_MAX_ABS_SIN_12: float = math.sin(2 * 2 * math.pi / 10) # β 0.9511def _scale_index_to_scale(max_coords: torch.Tensor, sigmas: torch.Tensor, num_levels: int) -> torch.Tensor:@@ -299,11 +299,14 @@ class ScaleSpaceDetector(nn.Module):cx = current_lafs[:, :, 0, 2]cy = current_lafs[:, :, 1, 2]h, w = octave.shape[3], octave.shape[4]+ # Valid pixel coordinates run 0 .. w-1 / 0 .. h-1, so the upper bound is (size - 1) - border.+ x_max = float(w - 1) - 5+ y_max = float(h - 1) - 5good_mask = ((cx - half_s * _MAX_ABS_SIN_12 >= 5)- & (cx + half_s * _MAX_ABS_SIN_12 <= w - 5)+ & (cx + half_s * _MAX_ABS_SIN_12 <= x_max)& (cy - half_s >= 5)- & (cy + half_s <= h - 5)+ & (cy + half_s <= y_max))resp_flat_best = resp_flat_best * good_mask.to(dev, dtype)current_lafs.mul_(px_size)diff --git a/tests/feature/test_laf.py b/tests/feature/test_laf.pyindex 23af7fd11..c0cb152ae 100644--- a/tests/feature/test_laf.py+++ b/tests/feature/test_laf.py@@ -594,6 +594,60 @@ class TestLAFIsTouchingBoundary(BaseTester):expected = torch.tensor([[False, True]], device=device)assert torch.all(kornia.feature.laf_is_inside_image(laf, img) == expected).item()+ @staticmethod+ def _radius_laf(cx, cy, radius, device, dtype):+ return kornia.feature.laf_from_center_scale_ori(+ torch.tensor([[[cx, cy]]], device=device, dtype=dtype),+ torch.full((1, 1, 1, 1), radius, device=device, dtype=dtype),+ )++ def test_boundary_is_the_last_valid_pixel(self, device, dtype):+ """Valid coordinates run 0 .. size-1, matching `get_laf_center`'s documented convention.++ A LAF reaching exactly `w - 1` is inside; anything past it is not (see #4064).+ """+ if dtype not in (torch.float32, torch.float64):+ pytest.skip("boundary comparison needs full precision")+ w = h = 32 # valid coordinates 0 .. 31+ img = torch.zeros(1, 1, h, w, device=device, dtype=dtype)+ r = 2.0++ # rightmost boundary lands exactly on 31.0 -> inside+ assert bool(kornia.feature.laf_is_inside_image(self._radius_laf(29.0, 16.0, r, device, dtype), img)[0, 0])+ # ... and half a pixel past it -> outside+ assert not bool(kornia.feature.laf_is_inside_image(self._radius_laf(29.5, 16.0, r, device, dtype), img)[0, 0])+ # same for the bottom edge+ assert bool(kornia.feature.laf_is_inside_image(self._radius_laf(16.0, 29.0, r, device, dtype), img)[0, 0])+ assert not bool(kornia.feature.laf_is_inside_image(self._radius_laf(16.0, 29.5, r, device, dtype), img)[0, 0])++ def test_boundary_is_symmetric(self, device, dtype):+ """The low and high edges must be equally strict."""+ if dtype not in (torch.float32, torch.float64):+ pytest.skip("boundary comparison needs full precision")+ w = h = 32+ img = torch.zeros(1, 1, h, w, device=device, dtype=dtype)+ r = 2.0+ # negative offsets push the LAF past the edge, which is where an asymmetric+ # upper bound shows up: on the low side it is rejected, on the high side it was not.+ for offset in (-1.0, -0.5, 0.0, 0.5, 1.0):+ low = kornia.feature.laf_is_inside_image(self._radius_laf(r + offset, 16.0, r, device, dtype), img)+ high = kornia.feature.laf_is_inside_image(+ self._radius_laf(float(w - 1) - r - offset, 16.0, r, device, dtype), img+ )+ assert bool(low[0, 0]) == bool(high[0, 0]), f"asymmetric at offset {offset}"++ def test_border_argument_shrinks_both_edges(self, device, dtype):+ if dtype not in (torch.float32, torch.float64):+ pytest.skip("boundary comparison needs full precision")+ w = h = 32+ img = torch.zeros(1, 1, h, w, device=device, dtype=dtype)+ r = 2.0+ # with border=3 the usable range is 3 .. 28, so a radius-2 LAF centred at 26 just fits+ assert bool(kornia.feature.laf_is_inside_image(self._radius_laf(26.0, 16.0, r, device, dtype), img, 3)[0, 0])+ assert not bool(+ kornia.feature.laf_is_inside_image(self._radius_laf(26.5, 16.0, r, device, dtype), img, 3)[0, 0]+ )+@pytest.mark.jit()def test_jit(self, device, dtype):w, h = 10, 5diff --git a/tests/feature/test_scale_space_detector.py b/tests/feature/test_scale_space_detector.pyindex 62a0232c8..01c4cfca1 100644--- a/tests/feature/test_scale_space_detector.py+++ b/tests/feature/test_scale_space_detector.py@@ -18,7 +18,12 @@import torchimport kornia-from kornia.feature.scale_space_detector import MultiResolutionDetector, ScaleSpaceDetector, get_default_detector_config+from kornia.feature.scale_space_detector import (+ _MAX_ABS_SIN_12,+ MultiResolutionDetector,+ ScaleSpaceDetector,+ get_default_detector_config,+)from kornia.geometry.subpix import ConvQuadInterp3dfrom testing.base import BaseTester@@ -109,6 +114,27 @@ class TestScaleSpaceDetector(BaseTester):assert lafs.shape == torch.Size([1, n_feats, 2, 3])assert resps.shape == torch.Size([1, n_feats])+ def test_inline_boundary_constant_matches_reference(self):+ """`_MAX_ABS_SIN_12` must be the x-extent `laf_to_boundary_points(laf, 12)` actually produces.++ `_process_octave` inlines `laf_is_inside_image(scale_laf(lafs, 0.5), octave, 5)` for the+ isotropic LAFs it builds. That inline form is only equivalent to the reference if the+ constant is the maximum ``|sin|`` over the angles the reference samples, which are+ ``linspace(0, 2 * pi, n_pts - 1)`` -- spacing ``2 * pi / 10``, not ``2 * pi / 11`` (#4064).+ Device- and dtype-independent: this pins a Python float against a sampling convention.+ """+ cx, cy, half_s = 10.0, 20.0, 3.0+ laf = kornia.feature.laf_from_center_scale_ori(+ torch.tensor([[[cx, cy]]], dtype=torch.float64),+ torch.full((1, 1, 1, 1), half_s, dtype=torch.float64),+ )+ pts = kornia.feature.laf_to_boundary_points(laf, 12)+ # `laf_to_boundary_points` builds its angles in float32 before casting, so compare at+ # float32 resolution -- the wrong spacing is off by 4e-2, four orders of magnitude more.+ assert abs(((pts[..., 0].max() - cx) / half_s).item() - _MAX_ABS_SIN_12) < 1e-6+ # ... and the y-extent the same block hardcodes as `half_s` (max|cos| = 1).+ assert abs(((pts[..., 1].max() - cy) / half_s).item() - 1.0) < 1e-6+def test_gradcheck(self, device):batch_size, channels, height, width = 1, 1, 7, 7patches = torch.rand(batch_size, channels, height, width, device=device, dtype=torch.float64)