π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(feature): make integrated.py's empty results match its non-empty ones (#4080)
Dmytro Mishkinb5453ad3d686
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 7a82cb3d6..8e30dd2bd 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -154,6 +154,20 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0`ScaleSpaceDetector` output on its own: a detection whose x-extent falls between the two constants used to bediscarded and is now kept. It is rare -- the detection has to land in a band of width `0.039 * half_s` against thex bound -- but when it fires it can promote the strongest response in the image, so it is not output-neutral.+* Fix the empty-result paths in `kornia.feature.integrated` disagreeing with the corresponding non-empty ones+ (#4065). `get_laf_descriptors` returned a hardcoded width of 128 with the *LAF's* dtype and device when it was+ handed no keypoints, so an empty batch through, say, a 256-d descriptor produced a `(B, 0, 128)` result that could+ not be concatenated with a real one; it now runs the descriptor once on a zero patch and returns its actual width+ (the flattened per-patch output, matching the non-empty path's `.view(B, N, -1)`), dtype and device. That is a+ widening of the empty path's failure surface: a third-party descriptor that raises on a zero input now raises here+ where it previously returned quietly. `LocalFeatureMatcher.no_match_output` returned `lafs0`/`lafs1` of shape+ `(0, 0, 2, 3)` where the success path returns `(1, NC, 2, 3)`, so `lafs0[0]` raised `IndexError` exactly when+ nothing matched; the empty tensors now keep the leading batch of 1. That is a shape change on a public return+ value -- code using `out["lafs0"].shape[0] == 0` as its no-match signal now sees `1` and should test+ `out["keypoints0"].shape[0] == 0`, which was already the consistent signal. `LocalFeatureMatcher.forward`'s+ docstring also stops claiming `confidence` is in `[0, 1]`: it is `1 - distance`, which for the raw-distance+ matchers `nn` and `mnn` goes at least down to -1 on unit-norm descriptors, and is unbounded below for arbitrary+ ones.## :rocket: [0.6.11] - 2022-03-28diff --git a/kornia/feature/integrated.py b/kornia/feature/integrated.pyindex 3ca1717e9..4d10e8536 100644--- a/kornia/feature/integrated.py+++ b/kornia/feature/integrated.py@@ -70,12 +70,22 @@ def get_laf_descriptors(patch_descriptor.eval()timg: torch.Tensor = img- if lafs.shape[1] == 0:- warnings.warn(f"LAF contains no keypoints {lafs.shape}, returning empty torch.Tensor", stacklevel=1)- return torch.empty(lafs.shape[0], lafs.shape[1], 128, dtype=lafs.dtype, device=lafs.device)if grayscale_descriptor and img.size(1) == 3:timg = rgb_to_grayscale(img)+ if lafs.shape[1] == 0:+ warnings.warn(f"LAF contains no keypoints {lafs.shape}, returning empty torch.Tensor", stacklevel=1)+ # Probe the descriptor for its output width instead of assuming 128, so the empty result+ # has the same trailing dimension and dtype as a non-empty one. The non-empty path ends in+ # `.view(B, N, -1)`, which flattens everything the descriptor produced per patch, so the+ # matching width is the whole probe -- `probe.shape[-1]` would only agree for descriptors+ # whose output is 2-D. The probe has a batch of one, so its numel is that width.+ with torch.no_grad():+ probe = patch_descriptor(+ torch.zeros(1, timg.size(1), patch_size, patch_size, dtype=timg.dtype, device=timg.device)+ )+ return torch.empty(lafs.shape[0], 0, probe.numel(), dtype=probe.dtype, device=probe.device)+patches: torch.Tensor = extract_patches_from_pyramid(timg, lafs, patch_size)# Descriptor accepts standard torch.Tensor [B, CH, H, W], while patches are [B, N, CH, H, W] shape# So we need to reshape a bit :)@@ -404,8 +414,10 @@ class LocalFeatureMatcher(nn.Module):return {"keypoints0": torch.empty(0, 2, device=device, dtype=dtype),"keypoints1": torch.empty(0, 2, device=device, dtype=dtype),- "lafs0": torch.empty(0, 0, 2, 3, device=device, dtype=dtype),- "lafs1": torch.empty(0, 0, 2, 3, device=device, dtype=dtype),+ # batch dim 1, matching the success path's `.view(1, -1, 2, 3)`, so that callers+ # can index `lafs0[0]` regardless of whether anything matched.+ "lafs0": torch.empty(1, 0, 2, 3, device=device, dtype=dtype),+ "lafs1": torch.empty(1, 0, 2, 3, device=device, dtype=dtype),"confidence": torch.empty(0, device=device, dtype=dtype),"batch_indexes": torch.empty(0, device=device, dtype=torch.long),}@@ -425,7 +437,11 @@ class LocalFeatureMatcher(nn.Module):Returns:- ``keypoints0``, matching keypoints from image0 :math:`(NC, 2)`.- ``keypoints1``, matching keypoints from image1 :math:`(NC, 2)`.- - ``confidence``, confidence score [0, 1] :math:`(NC)`.+ - ``confidence``, ``1 - descriptor distance`` :math:`(NC)`. This lies in :math:`[0, 1]`+ only for the ratio-based ``DescriptorMatcher`` modes (``snn``, ``smnn``); ``nn`` and+ ``mnn`` return raw distances, which are unbounded for an arbitrary descriptor, so the+ confidence has no lower bound in general -- it goes at least down to -1, the value+ reached by unit-norm descriptors, whose distance tops out at 2.0.- ``lafs0``, matching LAFs from image0 :math:`(1, NC, 2, 3)`.- ``lafs1``, matching LAFs from image1 :math:`(1, NC, 2, 3)`.- ``batch_indexes``, batch indexes for the keypoints and lafs :math:`(NC)`.diff --git a/tests/feature/test_integrated.py b/tests/feature/test_integrated.pyindex 351fa7d10..b99c1a1a4 100644--- a/tests/feature/test_integrated.py+++ b/tests/feature/test_integrated.py@@ -91,6 +91,81 @@ class TestGetLAFDescriptors(BaseTester):)+class TestGetLAFDescriptorsEmptyPath(BaseTester):+ """The empty-LAF result must agree with the non-empty one (see #4065)."""++ @pytest.mark.parametrize("output_dims", [64, 128, 238])+ def test_empty_matches_the_descriptor_width(self, device, dtype, output_dims):+ """The width came from a hardcoded 128 rather than from the descriptor module."""+ img = torch.rand(1, 1, 64, 64, device=device, dtype=dtype)+ desc = kornia.feature.MKDDescriptor(patch_size=32, output_dims=output_dims).to(device, dtype)+ laf = kornia.feature.laf_from_center_scale_ori(+ torch.tensor([[[32.0, 32.0]]], device=device, dtype=dtype),+ torch.full((1, 1, 1, 1), 8.0, device=device, dtype=dtype),+ )+ non_empty = kornia.feature.get_laf_descriptors(img, laf, desc, 32)+ with pytest.warns(UserWarning):+ empty = kornia.feature.get_laf_descriptors(+ img, torch.zeros(1, 0, 2, 3, device=device, dtype=dtype), desc, 32+ )+ assert empty.shape == (1, 0, non_empty.shape[-1])+ assert empty.dtype == non_empty.dtype+ assert empty.device.type == non_empty.device.type++ @pytest.mark.parametrize("descriptor", ["four_dim", "dense_sift"])+ def test_empty_matches_a_non_2d_descriptor(self, device, dtype, descriptor):+ """The width must be what `.view(B, N, -1)` produces, not the probe's last dimension.++ The non-empty path flattens *everything* the descriptor produced per patch, so taking+ `probe.shape[-1]` agreed only for descriptors whose output is 2-D. `patch_descriptor` is+ typed as a bare `nn.Module`; `DenseSIFTDescriptor` returns `(N, C, H, W)` and so does any+ user module of that shape, and those got a narrower empty result that could not be+ concatenated with a non-empty one -- the very defect this path exists to remove (#4065).+ """++ class FourDimDescriptor(nn.Module):+ """Minimal descriptor whose output is not 2-D."""++ def forward(self, patches: torch.Tensor) -> torch.Tensor:+ return patches.new_zeros(patches.shape[0], 3, 2, 5)++ desc = (+ FourDimDescriptor()+ if descriptor == "four_dim"+ else kornia.feature.DenseSIFTDescriptor(num_ang_bins=8, num_spatial_bins=4)+ )+ desc = desc.to(device, dtype)+ img = torch.rand(1, 1, 32, 32, device=device, dtype=dtype)+ laf = kornia.feature.laf_from_center_scale_ori(+ torch.tensor([[[16.0, 16.0]]], device=device, dtype=dtype),+ torch.full((1, 1, 1, 1), 8.0, device=device, dtype=dtype),+ )+ non_empty = kornia.feature.get_laf_descriptors(img, laf, desc, 32)+ with pytest.warns(UserWarning):+ empty = kornia.feature.get_laf_descriptors(+ img, torch.zeros(1, 0, 2, 3, device=device, dtype=dtype), desc, 32+ )+ assert empty.shape == (1, 0, non_empty.shape[-1])+ # which is the point: an empty batch has to be concatenable with a non-empty one+ assert torch.cat([non_empty, empty], dim=1).shape == non_empty.shape+++class TestLocalFeatureMatcherEmptyPath(BaseTester):+ """`no_match_output` must keep the rank the success path uses (see #4065)."""++ def test_empty_lafs_keep_the_batch_dimension(self, device, dtype):+ matcher = kornia.feature.LocalFeatureMatcher(+ kornia.feature.SIFTFeature(50), kornia.feature.DescriptorMatcher("snn", 0.9)+ )+ out = matcher.no_match_output(device, dtype)+ # the success path returns `.view(1, -1, 2, 3)`+ assert out["lafs0"].shape == (1, 0, 2, 3)+ assert out["lafs1"].shape == (1, 0, 2, 3)+ # so indexing the batch works either way+ assert out["lafs0"][0].shape == (0, 2, 3)+ assert out["keypoints0"].shape == (0, 2)++class TestLAFDescriptor(BaseTester):def test_same(self, device, dtype):B, C, H, W = 1, 3, 64, 64