Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

feat(feature): add laf_is_filled, the detector padding predicate (#4223)

Dmytro Mishkinc5ae61cd64da
diff --git a/CHANGELOG.md b/CHANGELOG.md
index b0f8554ca..f4f883c55 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -10,6 +10,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Added
+* `kornia.feature.laf_is_filled(laf)` returns the `(B, N)` mask of the slots a detection filled, the complement
+ of a detector's zero-LAF padding. Fixed-shape detectors pad the slots no detection filled with an all-zero LAF,
+ and those slots must be dropped before matching -- their descriptors are identical to one another, so they match
+ each other at zero distance and a mutual nearest-neighbour test does not reject them. `LocalFeature.forward`'s
+ docstring already required callers of a hand-rolled pipeline to do this and gave them the expression to copy;
+ they can now call the function instead. It replaces the same expression at four internal sites in
+ `kornia/feature`. (#4223)
+
* `benchmarks/feature/laf_ops.py` microbenchmarks seven public LAF operations
(`laf_from_center_scale_ori`, `make_upright`, `ellipse_to_laf`, `laf_to_boundary_points`,
`laf_is_inside_image`, `extract_patches_simple`, `extract_patches_from_pyramid`) as kornia eager vs
diff --git a/docs/source/feature.laf.rst b/docs/source/feature.laf.rst
index ae35d3e5f..8b385f190 100644
--- a/docs/source/feature.laf.rst
+++ b/docs/source/feature.laf.rst
@@ -23,6 +23,7 @@ Functions
.. autofunction:: get_laf_orientation
.. autofunction:: set_laf_orientation
.. autofunction:: laf_from_center_scale_ori
+.. autofunction:: laf_is_filled
.. autofunction:: laf_is_inside_image
.. autofunction:: laf_is_valid
.. autofunction:: laf_to_three_points
diff --git a/kornia/feature/__init__.py b/kornia/feature/__init__.py
index 6a3e28ed1..00f65c589 100644
--- a/kornia/feature/__init__.py
+++ b/kornia/feature/__init__.py
@@ -52,6 +52,7 @@ from .laf import (
get_laf_scale,
laf_from_center_scale_ori,
laf_from_three_points,
+ laf_is_filled,
laf_is_inside_image,
laf_is_valid,
laf_to_boundary_points,
@@ -166,6 +167,7 @@ __all__ = [
"hessian_response",
"laf_from_center_scale_ori",
"laf_from_three_points",
+ "laf_is_filled",
"laf_is_inside_image",
"laf_is_valid",
"laf_to_boundary_points",
diff --git a/kornia/feature/integrated.py b/kornia/feature/integrated.py
index 256318896..41621ed48 100644
--- a/kornia/feature/integrated.py
+++ b/kornia/feature/integrated.py
@@ -31,7 +31,14 @@ from kornia.geometry.transform import ScalePyramid
from .affine_shape import LAFAffNetShapeEstimator
from .hardnet import HardNet
from .keynet import KeyNetDetector
-from .laf import extract_patches_from_pyramid, get_laf_center, get_laf_orientation, get_laf_scale, scale_laf
+from .laf import (
+ extract_patches_from_pyramid,
+ get_laf_center,
+ get_laf_orientation,
+ get_laf_scale,
+ laf_is_filled,
+ scale_laf,
+)
from .lightglue import LightGlue
from .matching import GeometryAwareDescriptorMatcher, _no_match
from .orientation import LAFOrienter, OriNet, PassLAF
@@ -186,9 +193,12 @@ class LocalFeature(nn.Module):
before matching; a hand-rolled pipeline must do the same before any other matcher, including
:func:`~kornia.feature.match_nn`, :func:`~kornia.feature.match_mnn`, :func:`~kornia.feature.match_fginn`,
:func:`~kornia.feature.match_adalam` and :class:`~kornia.feature.LightGlueMatcher`, since identical
- descriptors match each other at zero distance and a mutual test does not reject a pair of them::
+ descriptors match each other at zero distance and a mutual test does not reject a pair of them, with
+ :func:`~kornia.feature.laf_is_filled`::
+
+ from kornia.feature import laf_is_filled
- valid = lafs.ne(0).any(-1).any(-1) # (B, N); the zero LAF marks a padded slot
+ valid = laf_is_filled(lafs) # (B, N); the zero LAF marks a padded slot
descs, lafs = descs[0][valid[0]], lafs[:, valid[0]]
Test the LAF, not the response: a signed response can legitimately peak at exactly zero. Only the ratio
@@ -512,13 +522,17 @@ class LocalFeatureMatcher(nn.Module):
out_lafs0: List[torch.Tensor] = []
out_lafs1: List[torch.Tensor] = []
+ # Fixed-shape detectors represent an unfilled slot with a zero LAF. Do not let the
+ # descriptor sampled at that dummy frame become a correspondence (NN/MNN would match
+ # identical padding at the origin). Occupancy cannot be inferred from the response:
+ # a pluggable signed scale-space response may have a genuine maximum at exactly zero.
+ # Computed for the whole batch once, rather than per pair inside the loop.
+ filled0 = laf_is_filled(lafs0)
+ filled1 = laf_is_filled(lafs1)
+
for batch_idx in range(num_image_pairs):
- # Fixed-shape detectors represent an unfilled slot with a zero LAF. Do not let the
- # descriptor sampled at that dummy frame become a correspondence (NN/MNN would match
- # identical padding at the origin). Occupancy cannot be inferred from the response:
- # a pluggable signed scale-space response may have a genuine maximum at exactly zero.
- valid0 = lafs0[batch_idx].ne(0).any(dim=-1).any(dim=-1)
- valid1 = lafs1[batch_idx].ne(0).any(dim=-1).any(dim=-1)
+ valid0 = filled0[batch_idx]
+ valid1 = filled1[batch_idx]
current_descs0 = descs0[batch_idx][valid0]
current_descs1 = descs1[batch_idx][valid1]
current_keypoints0 = keypoints0[batch_idx][valid0]
diff --git a/kornia/feature/laf.py b/kornia/feature/laf.py
index 0bf4df562..6bda0b6bc 100644
--- a/kornia/feature/laf.py
+++ b/kornia/feature/laf.py
@@ -67,6 +67,34 @@ def laf_is_valid(laf: torch.Tensor) -> torch.Tensor:
return laf.isfinite().all(dim=-1).all(dim=-1) & det.isfinite() & (det != 0)
+def laf_is_filled(laf: torch.Tensor) -> torch.Tensor:
+ """Check which slots hold a detection rather than the zero-LAF padding.
+
+ Detectors return a fixed number of slots and pad the ones no detection filled with an all-zero
+ LAF and a zero response, so that the output shape does not depend on the image. Drop those
+ slots before matching: the padding frames are identical to one another, so a mutual
+ nearest-neighbour test does not reject them and they match each other at zero distance.
+
+ Occupancy cannot be read off the response instead, because a pluggable signed response may have
+ a genuine maximum at exactly zero. Only an all-zero frame is padding: a detection at the image
+ origin has a zero centre but a nonzero shape, so it is filled.
+
+ Args:
+ laf: :math:`(B, N, 2, 3)`.
+
+ Returns:
+ mask of the slots a detection filled :math:`(B, N)`.
+
+ Example:
+ >>> laf = torch.tensor([[[[2., 0., 5.], [0., 3., 7.]], [[0., 0., 0.], [0., 0., 0.]]]])
+ >>> laf_is_filled(laf)
+ tensor([[ True, False]])
+
+ """
+ KORNIA_CHECK_LAF(laf)
+ return laf.ne(0).any(dim=-1).any(dim=-1)
+
+
def get_laf_center(LAF: torch.Tensor) -> torch.Tensor:
"""Return a center (keypoint) of the LAFs.
diff --git a/kornia/feature/scale_space_detector.py b/kornia/feature/scale_space_detector.py
index 792265ca1..584176dca 100644
--- a/kornia/feature/scale_space_detector.py
+++ b/kornia/feature/scale_space_detector.py
@@ -34,7 +34,7 @@ from kornia.geometry.subpix import (
)
from kornia.geometry.transform import ScalePyramid, pyrdown, resize
-from .laf import laf_from_center_scale_ori
+from .laf import laf_from_center_scale_ori, laf_is_filled
from .orientation import PassLAF
from .responses import BlobHessian
@@ -619,7 +619,7 @@ class ScaleSpaceDetector(nn.Module):
# `detect` is the public extension point used by subclasses. Infer occupancy from its
# zero-LAF padding contract rather than bypassing an override through `_detect`.
responses, lafs = self.detect(img, self.num_features, mask)
- filled = lafs.ne(0).any(dim=-1).any(dim=-1)
+ filled = laf_is_filled(lafs)
with self._dynamo_config_patch(("aff",)):
lafs = self.aff(lafs, img)
with self._dynamo_config_patch(("ori",)):
@@ -946,7 +946,7 @@ class MultiResolutionDetector(nn.Module):
responses, lafs = self.detect(img, mask)
# Occupancy comes from `detect`'s zero-LAF padding contract, the same way as in
# `ScaleSpaceDetector.forward`, so an override of `detect` is honoured as well.
- filled = lafs.ne(0).any(dim=-1).any(dim=-1)
+ filled = laf_is_filled(lafs)
lafs = self.aff(lafs, img)
lafs = self.ori(lafs, img)
return _zero_unfilled(lafs, filled), responses
diff --git a/tests/feature/test_laf.py b/tests/feature/test_laf.py
index d3345409f..c92aff904 100644
--- a/tests/feature/test_laf.py
+++ b/tests/feature/test_laf.py
@@ -25,6 +25,7 @@ import torch
import kornia
import kornia.geometry.transform.imgwarp
+from kornia.core.check import ShapeError
from testing.base import DYNAMO_UNAVAILABLE_REASON, BaseTester, dynamo_is_available
from testing.geometry.create import create_random_homography
@@ -397,6 +398,66 @@ class TestLAFIsValid(BaseTester):
assert torch.equal(compiled(laf), expected)
+class TestLAFIsFilled(BaseTester):
+ def _mixed(self, device, dtype):
+ # Slot 0 is a real detection, slot 1 is the all-zero padding a detector writes for a slot
+ # no detection filled, slot 2 is a real detection at the image origin.
+ laf = torch.tensor(
+ [
+ [
+ [[2.0, 0.0, 5.0], [0.0, 3.0, 7.0]],
+ [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0]],
+ [[2.0, 0.0, 0.0], [0.0, 3.0, 0.0]],
+ ]
+ ],
+ device=device,
+ dtype=dtype,
+ )
+ return laf, torch.tensor([[True, False, True]], device=device)
+
+ def test_zero_laf_is_the_only_padding(self, device, dtype):
+ laf, expected = self._mixed(device, dtype)
+ assert torch.equal(kornia.feature.laf_is_filled(laf), expected)
+
+ def test_detection_at_the_origin_is_filled(self, device, dtype):
+ # The discriminating case: a keypoint at (0, 0) has a zero centre but a nonzero shape, so
+ # testing the centre alone -- or the response, which a signed response may peak at zero --
+ # would call a real detection padding.
+ laf = torch.tensor([[[[2.0, 0.0, 0.0], [0.0, 3.0, 0.0]]]], device=device, dtype=dtype)
+ assert bool(kornia.feature.laf_is_filled(laf).all())
+
+ def test_matches_the_documented_idiom(self, device, dtype):
+ # The expression this replaces, written out in `LocalFeature`'s docstring and previously
+ # at four sites in `kornia.feature`.
+ laf, _ = self._mixed(device, dtype)
+ assert torch.equal(kornia.feature.laf_is_filled(laf), laf.ne(0).any(dim=-1).any(dim=-1))
+
+ def test_shape_and_dtype(self, device, dtype):
+ laf = torch.rand(3, 7, 2, 3, device=device, dtype=dtype)
+ filled = kornia.feature.laf_is_filled(laf)
+ assert filled.shape == torch.Size([3, 7])
+ assert filled.dtype == torch.bool
+ assert filled.device == laf.device
+
+ def test_rejects_a_non_laf_shape(self, device, dtype):
+ # `ShapeError` specifically, not `Exception`: a bare `Exception` here would also swallow an
+ # `AttributeError` and pass without the function existing at all.
+ with pytest.raises(ShapeError):
+ kornia.feature.laf_is_filled(torch.rand(7, 2, 3, device=device, dtype=dtype))
+
+ @pytest.mark.skipif(not dynamo_is_available(), reason=DYNAMO_UNAVAILABLE_REASON)
+ def test_dynamo_fullgraph(self, device, dtype):
+ laf, expected = self._mixed(device, dtype)
+ torch._dynamo.reset()
+ compiled = torch.compile(kornia.feature.laf_is_filled, fullgraph=True)
+ assert torch.equal(compiled(laf), expected)
+
+ def test_jit(self, device, dtype):
+ laf, _ = self._mixed(device, dtype)
+ model_jit = torch.jit.script(kornia.feature.laf_is_filled)
+ assert torch.equal(kornia.feature.laf_is_filled(laf), model_jit(laf))
+
+
class TestNormalizeLAF(BaseTester):
def test_shape(self, device):
inp = torch.rand(5, 3, 2, 3)