π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(feature): detect bright blobs in SIFTFeature (#5744)
Dmytro Mishkin1c3aebf128be
diff --git a/changelog.d/5744.fixed.md b/changelog.d/5744.fixed.mdnew file mode 100644index 000000000..80bb15f2e--- /dev/null+++ b/changelog.d/5744.fixed.md@@ -0,0 +1,14 @@+`SIFTFeature` now detects bright blobs as well as dark ones. Its detector, `MultiResolutionDetector`, keeps the maxima+of its response only, and `SIFTFeature` gave it the single-scale DoG of `BlobDoGSingle`, whose maxima lie at dark+blobs: a bright blob was never detected, only weaker maxima on the ring around it. `SIFTFeature` now gives the+detector the magnitude of the DoG, so a keypoint is a maximum or a minimum of the DoG; the DoG detectors of Lowe,+OpenCV and VLFeat keep both signs too. The suppression rule is not theirs: a keypoint must be the strict maximum of+the magnitude in its `config["nms_size"]` window (15x15 by default) on its pyramid level, so a stronger response of+the other sign in that window suppresses a weaker extremum, be it the ring around a blob or a nearby blob of the other+polarity, where they test each sign against its 3x3x3 scale-space neighbours separately. An image can therefore yield+fewer extrema in all than it had maxima, and when `num_features` exceeds them, more slots than before are padded with+a zero response and a zero LAF: the first image of the Oxford graf sequence fills 4509 of the default+`num_features=8000` slots instead of 5285. `SIFTFeature` returns different keypoints, many of them at bright blobs,+and its responses are the magnitude of the DoG. An image and its negative give keypoints at the same positions and+scales, up to rounding and not in half precision; without `upright` their orientations differ by pi.+`MultiResolutionDetector` itself and the Key.Net features are unchanged.diff --git a/kornia/feature/integrated.py b/kornia/feature/integrated.pyindex c61a34139..4626e75b7 100644--- a/kornia/feature/integrated.py+++ b/kornia/feature/integrated.py@@ -285,6 +285,17 @@ class LocalFeature(nn.Module):return (lafs, responses, descs)+class _DoGSingleMagnitude(nn.Module):+ """Magnitude of a single-scale DoG response, whose maxima are maxima of the DoG above zero or minima below zero."""++ def __init__(self, sigma1: float = 1.0, sigma2: float = 1.6) -> None:+ super().__init__()+ self.dog = BlobDoGSingle(sigma1, sigma2)++ def forward(self, input: torch.Tensor) -> torch.Tensor:+ return self.dog(input).abs()++class _SIFTFeature(LocalFeature):"""Compose a sparse SIFT detector with a patch or pyramid extraction backend."""@@ -321,6 +332,15 @@ class SIFTFeature(_SIFTFeature)::class:`~kornia.feature.LightGlueMatcher` expects with ``"sift"``.:func:`~kornia.feature.convert_sift_descriptor_layout` converts between the two.+ The detector is :class:`~kornia.feature.MultiResolutionDetector` on the magnitude of a single-scale+ :class:`~kornia.feature.BlobDoGSingle` response. Like the DoG detectors of Lowe, OpenCV and VLFeat, it keeps+ both signs of DoG extremum: the maxima (dark blobs) and the minima (bright blobs). A keypoint is a strict+ maximum of the magnitude over its ``config["nms_size"]`` window (15 px by default) on its pyramid level, so a+ stronger response of the other sign in that window suppresses a weaker extremum, be it the ring of opposite+ sign around a blob or a nearby blob of the other polarity. Those detectors instead test a maximum against its+ 3x3x3 scale-space neighbours and a minimum likewise, so an extremum of one sign never suppresses one of the+ other. ``responses`` holds the magnitude.+Using `kornia.feature.MultiResolutionDetector` without blur pyramid Still not as good as OpenCV/VLFeat because ofhttps://github.com/kornia/kornia/pull/884,but we are working on it@@ -347,7 +367,7 @@ class SIFTFeature(_SIFTFeature):if config is None:config = get_default_detector_config()detector = MultiResolutionDetector(- BlobDoGSingle(1.0, 1.6),+ _DoGSingleMagnitude(1.0, 1.6),num_features,config,ori_module=PassLAF() if upright or descriptor_backend == "pyramid" else LAFOrienter(19),diff --git a/kornia/feature/scale_space_detector.py b/kornia/feature/scale_space_detector.pyindex ea052a47a..8c89214a7 100644--- a/kornia/feature/scale_space_detector.py+++ b/kornia/feature/scale_space_detector.py@@ -729,6 +729,9 @@ class MultiResolutionDetector(nn.Module):detector suppresses on the whole response and removes the strip from the suppression output instead;see :meth:`detect_features_on_single_level`.+ Detections are maxima of the response. For a signed response whose minima are features as well, such as a+ difference of Gaussians, pass its magnitude, as :class:`~kornia.feature.SIFTFeature` does.+Args:model: response function, such as KeyNet or BlobHessiannum_features: Number of features to detect. Every pyramid level is searched for this manydiff --git a/tests/feature/test_integrated.py b/tests/feature/test_integrated.pyindex a28a52c86..26aabab78 100644--- a/tests/feature/test_integrated.py+++ b/tests/feature/test_integrated.py@@ -44,6 +44,7 @@ from kornia.feature import (laf_is_filled,)from kornia.feature.integrated import LocalFeatureMatcher+from kornia.feature.scale_space_detector import get_default_detector_configfrom kornia.geometry import RANSAC, resize, transform_pointsfrom testing.base import DYNAMO_UNAVAILABLE_REASON, BaseTester, dynamo_is_available, supports_replicate_padding@@ -490,6 +491,72 @@ class TestSIFTFeature(BaseTester):assert responses.shape == (1, 2)assert descriptors.shape == (1, 2, 128)+ @staticmethod+ def _blobs(h, w, blobs, device, dtype, background=0.5):+ # Gaussian blobs (x, y, sigma, amplitude) on a constant background, built in float64 on the CPU.+ yy, xx = torch.meshgrid(+ torch.arange(h, dtype=torch.float64), torch.arange(w, dtype=torch.float64), indexing="ij"+ )+ img = torch.full_like(xx, background)+ for x0, y0, s, a in blobs:+ img = img + a * torch.exp(-((xx - x0) ** 2 + (yy - y0) ** 2) / (2 * s * s))+ return img[None, None].to(device=device, dtype=dtype)++ def test_detects_bright_and_dark_blobs_5743(self, device, dtype):+ # The single-scale DoG is negative at a bright blob and positive at a dark one. Like Lowe's, OpenCV's and+ # VLFeat's DoG detectors, SIFTFeature keeps the minima of the DoG as well as its maxima.+ img = self._blobs(120, 160, [(70.0, 52.0, 3.0, 0.4), (40.0, 85.0, 3.0, -0.4)], device, dtype)+ with torch.no_grad():+ lafs, _, _ = SIFTFeature(8, upright=True).to(device, dtype)(img)+ centres = get_laf_center(lafs)[0, kornia.feature.laf_is_filled(lafs)[0]].cpu().double()+ for name, x0, y0 in (("bright", 70.0, 52.0), ("dark", 40.0, 85.0)):+ dist = (centres - torch.tensor([x0, y0], dtype=torch.float64)).norm(dim=-1)+ assert bool((dist <= 3.0).any()), f"no detection at the {name} blob: {centres.tolist()}"++ def test_responses_are_the_dog_magnitude_5743(self, device, dtype):+ # On a single full-resolution level a keypoint sits on a pixel, and its response is the magnitude of the+ # DoG there, for a bright blob (DoG < 0) and a dark one (DoG > 0) alike.+ cfg = get_default_detector_config()+ cfg.update(pyramid_levels=0, up_levels=0)+ img = self._blobs(96, 128, [(40.0, 34.0, 2.5, 0.4), (86.0, 60.0, 3.0, -0.3)], device, dtype)+ with torch.no_grad():+ lafs, responses, _ = SIFTFeature(2, upright=True, config=cfg).to(device, dtype)(img)+ dog = kornia.feature.BlobDoGSingle(1.0, 1.6).to(device, dtype)(img)[0, 0]+ xy = get_laf_center(lafs)[0].round().long()+ assert xy.tolist() == [[40, 34], [86, 60]], xy.tolist()+ signed = dog[xy[:, 1], xy[:, 0]]+ assert signed[0] < 0 < signed[1]+ self.assert_close(responses[0], signed.abs())++ def test_blob_is_detected_without_its_ring_5743(self, device, dtype):+ # The DoG of a blob is surrounded by a weaker ring of the opposite sign. The ring lies within the blob's+ # suppression window and is weaker, so every detection of note is at the blob, whichever its polarity.+ for name, amplitude, background in (("bright", 1.0, 0.0), ("dark", -1.0, 1.0)):+ img = self._blobs(120, 160, [(70.0, 52.0, 3.0, amplitude)], device, dtype, background)+ with torch.no_grad():+ lafs, responses, _ = SIFTFeature(32, upright=True).to(device, dtype)(img)+ # A flat background still has extrema of rounding-error size; they are not features.+ strong = responses[0] > 0.01 * responses[0].max()+ centres = get_laf_center(lafs)[0, strong].cpu().double()+ dist = (centres - torch.tensor([70.0, 52.0], dtype=torch.float64)).norm(dim=-1)+ assert dist.numel() > 0, name+ assert bool((dist <= 3.0).all()), f"{name} blob: detections at distances {dist.tolist()}"++ def test_frames_do_not_depend_on_polarity_5743(self, device, dtype):+ # DoG(1 - x) = -DoG(x): an image and its negative have the same extrema with the same magnitudes, so+ # upright SIFTFeature finds the same frames in both. Every pixel lies in [0.5, 1], where 1 - x is exact.+ if dtype in (torch.float16, torch.bfloat16):+ pytest.skip("the DoG is computed in the input dtype, which rounds an image and its negative differently")+ blobs = [(34.0, 30.0, 3.0, 0.2), (88.0, 42.0, 4.0, -0.2), (58.0, 66.0, 2.5, -0.15), (100.0, 70.0, 3.5, 0.12)]+ img = self._blobs(96, 128, blobs, device, dtype, background=0.75)+ feature = SIFTFeature(8, upright=True).to(device, dtype)+ with torch.no_grad():+ lafs, responses, _ = feature(img)+ lafs_neg, responses_neg, _ = feature(1 - img)+ assert bool(kornia.feature.laf_is_filled(lafs).all())+ self.assert_close(lafs_neg, lafs)+ self.assert_close(responses_neg, responses)+@pytest.mark.skip("jacobian not well computed")def test_gradcheck(self, device):B, C, H, W = 1, 1, 32, 32