Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

feat(feature): SIFT descriptor layouts and keypoint conventions for LightGlue (#5145)

Dmytro Mishkin9aa7541e69fc
diff --git a/changelog.d/5145.added.md b/changelog.d/5145.added.md
new file mode 100644
index 000000000..92c7ad10c
--- /dev/null
+++ b/changelog.d/5145.added.md
@@ -0,0 +1 @@
+`convert_sift_descriptor_layout` reorders SIFT descriptors between kornia's layout and OpenCV's, and `SIFTFeature` and `SIFTFeatureScaleSpace` take `descriptor_layout="opencv"` to return OpenCV's layout directly. `LightGlueMatcher("sift")` expects OpenCV's layout, which kornia's SIFT descriptors do not use by default, so request it or convert before matching: on Oxford Graf 1β†’4, `SIFTFeature` descriptors matched in kornia's layout gave 2 correct matches, and 497 in OpenCV's.
diff --git a/changelog.d/5145.fixed.md b/changelog.d/5145.fixed.md
new file mode 100644
index 000000000..07a472b95
--- /dev/null
+++ b/changelog.d/5145.fixed.md
@@ -0,0 +1 @@
+`LightGlueMatcher("sift")` now gives LightGlue each keypoint's scale and orientation in the convention of the COLMAP keypoints its weights were trained on: the orientation is the negated LAF orientation in (-pi, pi], and the scale is a sixth of the LAF scale, which is sigma for 6-sigma DoG frames such as `SIFTFeatureScaleSpace`'s. It used to pass the LAF scale and kornia's orientation in [0, 2pi). With OpenCV-layout descriptors, correct matches over the eight Oxford affine sequences rise by 1–2.4% for the kornia SIFT pipelines, and by up to 28% on bark, whose pairs rotate.
diff --git a/docs/source/feature.descriptors.rst b/docs/source/feature.descriptors.rst
index 2a484bad0..cb9486585 100644
--- a/docs/source/feature.descriptors.rst
+++ b/docs/source/feature.descriptors.rst
@@ -10,6 +10,7 @@ Descriptors
:members: forward, orient_and_describe
.. autoclass:: SIFTDescriptor
+.. autofunction:: convert_sift_descriptor_layout
.. autoclass:: MKDDescriptor
.. autoclass:: HardNet
.. autoclass:: HardNet8
diff --git a/kornia/feature/__init__.py b/kornia/feature/__init__.py
index c7d426e85..d3dfd2936 100644
--- a/kornia/feature/__init__.py
+++ b/kornia/feature/__init__.py
@@ -93,7 +93,7 @@ from .responses import (
)
from .scale_space_detector import MultiResolutionDetector, PassLAF, ScaleSpaceDetector
from .sift import SIFTDescriptorFromPyramid
-from .siftdesc import DenseSIFTDescriptor, SIFTDescriptor
+from .siftdesc import DenseSIFTDescriptor, SIFTDescriptor, convert_sift_descriptor_layout
from .sold2 import SOLD2, SOLD2_detector
from .sosnet import SOSNet
from .tfeat import TFeat
@@ -154,6 +154,7 @@ __all__ = [
"TFeat",
"XFeat",
"XFeatModel",
+ "convert_sift_descriptor_layout",
"denormalize_laf",
"dog_response",
"dog_response_single",
diff --git a/kornia/feature/integrated.py b/kornia/feature/integrated.py
index c045fec68..76a248db1 100644
--- a/kornia/feature/integrated.py
+++ b/kornia/feature/integrated.py
@@ -51,7 +51,32 @@ from .scale_space_detector import (
)
from .sift import SIFTDescriptorFromPyramid
from .sift.scale_space import _SIFTScalePyramid, _SIFTScaleSpaceDescriptor, _SIFTScaleSpaceDetector
-from .siftdesc import SIFTDescriptor
+from .siftdesc import SIFTDescriptor, _check_sift_descriptor_layout, convert_sift_descriptor_layout
+
+
+def _in_sift_layout(descriptors: torch.Tensor, layout: str) -> torch.Tensor:
+ """Return kornia-layout SIFT descriptors in ``layout``; the default ``"kornia"`` returns them unchanged."""
+ return descriptors if layout == "kornia" else convert_sift_descriptor_layout(descriptors, "kornia", layout)
+
+
+def _lightglue_keypoint_scale_ori(lafs: torch.Tensor, feature_name: str) -> Tuple[torch.Tensor, torch.Tensor]:
+ r"""Return the keypoint scales and orientations, shape :math:`(1, N)`, that LightGlue takes for ``lafs``.
+
+ LightGlue's ``"sift"`` weights were trained on COLMAP keypoints, whose scale is the detection sigma and whose
+ orientation is the image angle of the frame's x-axis in :math:`(-\pi, \pi]`: the negative of the LAF
+ orientation. The scale is taken as a sixth of the LAF scale, which is sigma for 6-sigma DoG frames such as
+ :class:`SIFTFeatureScaleSpace`'s. Every other feature keeps the LAF scale and the LAF orientation in
+ :math:`[0, 2\pi)`. The ``"sift"`` scale is converted here rather than through :class:`LightGlue`'s
+ ``scale_coef``, which the ``"doghardnet"`` configurations use, so that ``LightGlue("sift")`` itself keeps taking
+ keypoints in the training convention.
+ """
+ scales = get_laf_scale(lafs).reshape(1, -1)
+ oris = torch.deg2rad(get_laf_orientation(lafs).reshape(1, -1))
+ if feature_name == "sift":
+ oris = -oris
+ return scales / 6.0, torch.where(oris <= -math.pi, oris + 2.0 * math.pi, oris)
+ oris[oris < 0] += 2.0 * math.pi
+ return scales, oris
def get_laf_descriptors(
@@ -217,21 +242,26 @@ class LocalFeature(nn.Module):
class _SIFTFeature(LocalFeature):
"""Compose a sparse SIFT detector with a patch or pyramid extraction backend."""
- def __init__(self, detector: nn.Module, descriptor: nn.Module, upright: bool) -> None:
+ def __init__(
+ self, detector: nn.Module, descriptor: nn.Module, upright: bool, descriptor_layout: str = "kornia"
+ ) -> None:
+ _check_sift_descriptor_layout(descriptor_layout)
super().__init__(detector, descriptor)
self.upright = upright
+ self.descriptor_layout = descriptor_layout
def forward(
self, img: torch.Tensor, mask: Optional[torch.Tensor] = None
) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
"""Return sparse LAFs, detector responses, and one descriptor per LAF."""
if not isinstance(self.descriptor, SIFTDescriptorFromPyramid):
- return super().forward(img, mask)
- lafs, responses = self.detector(img, mask)
- lafs = scale_laf(lafs, self.scaling_coef)
- gray_image = rgb_to_grayscale(img) if img.shape[1] == 3 else img
- lafs, descriptors = self.descriptor.orient_and_describe(gray_image, lafs, upright=self.upright)
- return lafs, responses, descriptors
+ lafs, responses, descriptors = super().forward(img, mask)
+ else:
+ lafs, responses = self.detector(img, mask)
+ lafs = scale_laf(lafs, self.scaling_coef)
+ gray_image = rgb_to_grayscale(img) if img.shape[1] == 3 else img
+ lafs, descriptors = self.descriptor.orient_and_describe(gray_image, lafs, upright=self.upright)
+ return lafs, responses, _in_sift_layout(descriptors, self.descriptor_layout)
class SIFTFeature(_SIFTFeature):
@@ -240,7 +270,10 @@ class SIFTFeature(_SIFTFeature):
``descriptor_backend="pyramid"`` uses :class:`SIFTDescriptorFromPyramid` for
orientation and description at the detector's sparse LAFs. Detection and the
feature budget are unchanged. The default ``"patch"`` backend retains the
- existing patch-wise pipeline.
+ existing patch-wise pipeline. Both return descriptors in kornia's SIFT layout by
+ default; ``descriptor_layout="opencv"`` returns them in OpenCV's, which
+ :class:`~kornia.feature.LightGlueMatcher` expects with ``"sift"``.
+ :func:`~kornia.feature.convert_sift_descriptor_layout` converts between the two.
Using `kornia.feature.MultiResolutionDetector` without blur pyramid Still not as good as OpenCV/VLFeat because of
https://github.com/kornia/kornia/pull/884,
@@ -257,9 +290,11 @@ class SIFTFeature(_SIFTFeature):
compile_model: bool = False,
score_threshold: float = 0.0,
descriptor_backend: Literal["patch", "pyramid"] = "patch",
+ descriptor_layout: Literal["kornia", "opencv"] = "kornia",
) -> None:
if descriptor_backend not in ("patch", "pyramid"):
raise ValueError(f"Unknown SIFT descriptor backend: {descriptor_backend!r}")
+ _check_sift_descriptor_layout(descriptor_layout)
patch_size: int = 41
if device is None:
device = torch.device("cpu")
@@ -283,7 +318,7 @@ class SIFTFeature(_SIFTFeature):
patch_size=patch_size,
grayscale_descriptor=True,
).to(device)
- super().__init__(detector, descriptor, upright)
+ super().__init__(detector, descriptor, upright, descriptor_layout)
class SIFTFeatureScaleSpace(LocalFeature):
@@ -297,6 +332,9 @@ class SIFTFeatureScaleSpace(LocalFeature):
extrema and ranks all valid candidates by response, without contrast or edge
rejection. The feature budget is unchanged; detections may differ.
The default ``"patch"`` backend retains patch-wise orientation and description.
+ Both return descriptors in kornia's SIFT layout by default; ``descriptor_layout="opencv"``
+ returns them in OpenCV's, which :class:`~kornia.feature.LightGlueMatcher` expects with
+ ``"sift"``. :func:`~kornia.feature.convert_sift_descriptor_layout` converts between the two.
Still not as good as OpenCV/VLFeat because of https://github.com/kornia/kornia/pull/884, but we are working on it
"""
@@ -309,9 +347,11 @@ class SIFTFeatureScaleSpace(LocalFeature):
device: Union[str, torch.device, None] = None,
compile_modules: Union[bool, List[str]] = False,
descriptor_backend: Literal["patch", "pyramid"] = "patch",
+ descriptor_layout: Literal["kornia", "opencv"] = "kornia",
) -> None:
if descriptor_backend not in ("patch", "pyramid"):
raise ValueError(f"Unknown SIFT descriptor backend: {descriptor_backend!r}")
+ _check_sift_descriptor_layout(descriptor_layout)
if device is None:
device = torch.device("cpu")
patch_size: int = 41
@@ -352,20 +392,22 @@ class SIFTFeatureScaleSpace(LocalFeature):
super().__init__(detector, descriptor)
self.upright = upright
self.descriptor_backend = descriptor_backend
+ self.descriptor_layout = descriptor_layout
def forward(
self, img: torch.Tensor, mask: Optional[torch.Tensor] = None
) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
"""Detect and describe sparse SIFT features, sharing scale space when selected."""
if self.descriptor_backend == "patch":
- return super().forward(img, mask)
+ lafs, responses, descriptors = super().forward(img, mask)
+ return lafs, responses, _in_sift_layout(descriptors, self.descriptor_layout)
gray = rgb_to_grayscale(img) if img.shape[1] == 3 else img
responses, lafs, _, pyramid, octaves, levels = self.detector._detect_with_pyramid(
gray, self.detector.num_features, mask
)
lafs = scale_laf(lafs, self.scaling_coef)
lafs, descriptors = self.descriptor(pyramid, lafs, octaves, levels, upright=self.upright)
- return lafs, responses, descriptors.to(img.dtype)
+ return lafs, responses, _in_sift_layout(descriptors.to(img.dtype), self.descriptor_layout)
class GFTTAffNetHardNet(LocalFeature):
@@ -658,15 +700,26 @@ class LocalFeatureMatcher(nn.Module):
class LightGlueMatcher(GeometryAwareDescriptorMatcher):
- """LightGlue-based matcher in kornia API.
+ r"""LightGlue-based matcher in kornia API.
This is based on the original code from paper "LightGlue: Local Feature Matching at Light Speed".
See :cite:`LightGlue2023` for more details.
Args:
- feature_name: type of feature for matching, can be `disk` or `superpoint`.
+ feature_name: type of feature for matching, one of ``known_modes``.
params: LightGlue params.
+ With ``"sift"``, the descriptors must be in OpenCV's SIFT layout, which LightGlue's SIFT weights expect. kornia's
+ SIFT descriptors use another order of the same values: create the feature with ``descriptor_layout="opencv"``,
+ or convert them first with :func:`~kornia.feature.convert_sift_descriptor_layout`::
+
+ descs = convert_sift_descriptor_layout(descs, "kornia", "opencv")
+
+ The keypoint scale and orientation taken from the LAFs are converted to the convention of the COLMAP keypoints
+ the ``"sift"`` weights were trained on: the orientation is the negated LAF orientation in :math:`(-\pi, \pi]`,
+ and the scale is a sixth of the LAF scale, which is the detection sigma for 6-sigma DoG frames such as
+ :class:`~kornia.feature.SIFTFeatureScaleSpace`'s.
+
"""
known_modes: ClassVar[List[str]] = [
@@ -732,14 +785,12 @@ class LightGlueMatcher(GeometryAwareDescriptorMatcher):
hw2_ = keypoints2.max(dim=1)[0].squeeze().flip(0)
else:
hw2_ = torch.tensor(hw2, device=dev)
- ori0 = torch.deg2rad(get_laf_orientation(lafs1).reshape(1, -1))
- ori0[ori0 < 0] += 2.0 * math.pi
- ori1 = torch.deg2rad(get_laf_orientation(lafs2).reshape(1, -1))
- ori1[ori1 < 0] += 2.0 * math.pi
+ scale0, ori0 = _lightglue_keypoint_scale_ori(lafs1, self.feature_name)
+ scale1, ori1 = _lightglue_keypoint_scale_ori(lafs2, self.feature_name)
input_dict = {
"image0": {
"keypoints": keypoints1,
- "scales": get_laf_scale(lafs1).reshape(1, -1),
+ "scales": scale0,
"oris": ori0,
"lafs": lafs1,
"descriptors": desc1,
@@ -748,7 +799,7 @@ class LightGlueMatcher(GeometryAwareDescriptorMatcher):
"image1": {
"keypoints": keypoints2,
"lafs": lafs2,
- "scales": get_laf_scale(lafs2).reshape(1, -1),
+ "scales": scale1,
"oris": ori1,
"descriptors": desc2,
"image_size": hw2_.flip(0).reshape(-1, 2).to(dev),
diff --git a/kornia/feature/sift/pyramid.py b/kornia/feature/sift/pyramid.py
index e7684fcae..0290d8682 100644
--- a/kornia/feature/sift/pyramid.py
+++ b/kornia/feature/sift/pyramid.py
@@ -77,6 +77,9 @@ class SIFTDescriptorFromPyramid(nn.Module):
- image: :math:`(B, 1, H, W)`
- lafs: :math:`(B, N, 2, 3)` in image pixel coordinates
- descriptors: :math:`(B, N, num_ang_bins * num_spatial_bins^2)`
+
+ The descriptors are in kornia's angle-major SIFT layout, as :class:`~kornia.feature.SIFTDescriptor`'s are;
+ :func:`~kornia.feature.convert_sift_descriptor_layout` reorders them to OpenCV's.
"""
def __init__(
diff --git a/kornia/feature/sift/scale_space.py b/kornia/feature/sift/scale_space.py
index f9e020441..8e92ecce5 100644
--- a/kornia/feature/sift/scale_space.py
+++ b/kornia/feature/sift/scale_space.py
@@ -694,7 +694,11 @@ class _SIFTScaleSpaceDescriptor(nn.Module):
yy: torch.Tensor,
spatial_weights: torch.Tensor | None = None,
) -> torch.Tensor:
- """Accumulate the two angular votes per sample into the 4 x 4 spatial cells."""
+ """Accumulate the two angular votes per sample into the 4 x 4 spatial cells.
+
+ The result is in the (angle, row, column) order of every kornia SIFT descriptor; see
+ :func:`~kornia.feature.convert_sift_descriptor_layout` for OpenCV's order.
+ """
b, n, _ = mag.shape
weight = torch.exp(-0.78125 * (xx.square() + yy.square())).to(mag.dtype)
angular = (angle % (2 * math.pi)) * 8 / (2 * math.pi)
@@ -715,7 +719,8 @@ class _SIFTScaleSpaceDescriptor(nn.Module):
# (B,N,4,size,8), instead of multiplying each sample into 16 cells.
size = spatial_weights.shape[0]
rows = spatial_weights.T @ angular_weights.reshape(b, n, size, size * 8)
- return (spatial_weights.T @ rows.reshape(b, n, 4, size, 8)).reshape(b, n, 128)
+ # (B, N, row, column, angle) -> (B, N, angle, row, column).
+ return (spatial_weights.T @ rows.reshape(b, n, 4, size, 8)).permute(0, 1, 4, 2, 3).reshape(b, n, 128)
spatial_x = 2.5 * xx + 1.5
spatial_y = 2.5 * yy + 1.5
bins = torch.arange(4, device=mag.device, dtype=mag.dtype)
@@ -723,8 +728,8 @@ class _SIFTScaleSpaceDescriptor(nn.Module):
spatial_weights = (1.0 - (spatial_x.unsqueeze(-1) - cell_x.reshape(-1)).abs()).clamp_min(0.0) * (
1.0 - (spatial_y.unsqueeze(-1) - cell_y.reshape(-1)).abs()
).clamp_min(0.0)
- # (B, N, 8, samples) @ (samples, 16) -> one 8-bin histogram per spatial cell.
- return torch.matmul(angular_weights.transpose(-1, -2), spatial_weights).transpose(-1, -2).reshape(b, n, 128)
+ # (B, N, 8, samples) @ (samples, 16) -> (B, N, angle, cell): one 8-bin histogram per spatial cell.
+ return torch.matmul(angular_weights.transpose(-1, -2), spatial_weights).reshape(b, n, 128)
def forward(
self,
diff --git a/kornia/feature/siftdesc.py b/kornia/feature/siftdesc.py
index f426b08be..514cc40df 100644
--- a/kornia/feature/siftdesc.py
+++ b/kornia/feature/siftdesc.py
@@ -22,7 +22,7 @@ import torch
import torch.nn.functional as F
from torch import nn
-from kornia.core.check import KORNIA_CHECK_SHAPE
+from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_SHAPE
from kornia.core.utils import _l2_normalize
from kornia.filters import get_gaussian_kernel2d, spatial_gradient
@@ -152,6 +152,9 @@ class SIFTDescriptor(nn.Module):
- Input: :math:`(B, 1, \text{patch_size}, \text{patch_size})`
- Output: :math:`(B, \text{num_ang_bins * num_spatial_bins ** 2})`
+ The output is in kornia's angle-major SIFT layout; :func:`~kornia.feature.convert_sift_descriptor_layout` reorders
+ it to OpenCV's.
+
Example:
>>> input = torch.rand(23, 1, 32, 32)
>>> SIFT = SIFTDescriptor(32, 8, 4)
@@ -294,6 +297,88 @@ def _rootsift(desc: torch.Tensor, eps: float) -> torch.Tensor:
return torch.sqrt(F.normalize(desc, p=1, eps=1e-12) + eps)
+_SIFT_DESCRIPTOR_LAYOUTS = ("kornia", "opencv")
+
+
+def _check_sift_descriptor_layout(layout: str) -> None:
+ if layout not in _SIFT_DESCRIPTOR_LAYOUTS:
+ raise ValueError(f"Unknown SIFT descriptor layout {layout!r}; expected one of {_SIFT_DESCRIPTOR_LAYOUTS}")
+
+
+def _opencv_order(num_ang_bins: int, num_spatial_bins: int) -> list[int]:
+ """For each OpenCV descriptor position, the kornia position holding the same histogram value."""
+ cells = num_spatial_bins * num_spatial_bins
+ # Negating the angle maps bin a to bin -a (mod num_ang_bins); the map is its own inverse.
+ return [((-angle) % num_ang_bins) * cells + cell for cell in range(cells) for angle in range(num_ang_bins)]
+
+
+def convert_sift_descriptor_layout(
+ descriptors: torch.Tensor,
+ source: str,
+ target: str,
+ num_ang_bins: int = 8,
+ num_spatial_bins: int = 4,
+) -> torch.Tensor:
+ r"""Reorder SIFT descriptors between kornia's layout and OpenCV's.
+
+ Both layouts hold the same histogram values, one per angle bin :math:`a` and spatial cell :math:`(y, x)`
+ of the frame, with :math:`A` = ``num_ang_bins`` and :math:`S` = ``num_spatial_bins``:
+
+ - ``"kornia"``, the layout of every kornia SIFT descriptor (:class:`~kornia.feature.SIFTDescriptor`,
+ :class:`~kornia.feature.SIFTDescriptorFromPyramid`, and :class:`~kornia.feature.SIFTFeature` and
+ :class:`~kornia.feature.SIFTFeatureScaleSpace` with either ``descriptor_backend``): angle-major, value
+ :math:`(a, y, x)` at index :math:`a S^2 + y S + x`. Bin :math:`a` is centred on the direction
+ :math:`2 \pi a / A`, measured from :math:`+x` towards :math:`+y`, with :math:`y` growing downwards as image
+ rows do.
+ - ``"opencv"``, the layout of OpenCV's ``cv2.SIFT``: spatial-major, index :math:`(y S + x) A + a'`, with angles
+ measured from :math:`+x` towards :math:`-y`. A gradient in kornia's bin :math:`a` falls in OpenCV's bin
+ :math:`a' = -a \bmod A`.
+
+ LightGlue's ``"sift"`` weights expect the ``"opencv"`` layout: convert kornia descriptors before passing them to
+ :class:`~kornia.feature.LightGlueMatcher` with ``"sift"``. The conversion only reorders values, so it applies
+ equally to SIFT and RootSIFT descriptors and keeps their scale; converting back restores the input exactly.
+
+ Args:
+ descriptors: SIFT descriptors of shape :math:`(*, A S^2)`.
+ source: layout of ``descriptors``, ``"kornia"`` or ``"opencv"``.
+ target: layout to return, ``"kornia"`` or ``"opencv"``.
+ num_ang_bins: number of angle bins :math:`A`.
+ num_spatial_bins: number of spatial bins :math:`S` per side.
+
+ Returns:
+ The descriptors in the ``target`` layout, with the input's shape, dtype and device.
+
+ Example:
+ >>> descs = SIFTDescriptor(32)(torch.rand(4, 1, 32, 32))
+ >>> opencv_descs = convert_sift_descriptor_layout(descs, "kornia", "opencv")
+ >>> torch.equal(convert_sift_descriptor_layout(opencv_descs, "opencv", "kornia"), descs)
+ True
+
+ """
+ _check_sift_descriptor_layout(source)
+ _check_sift_descriptor_layout(target)
+ if num_ang_bins < 1 or num_spatial_bins < 1:
+ raise ValueError(
+ f"SIFT bin counts must be positive. Got num_ang_bins={num_ang_bins}, num_spatial_bins={num_spatial_bins}"
+ )
+ size = num_ang_bins * num_spatial_bins * num_spatial_bins
+ KORNIA_CHECK(
+ descriptors.shape[-1] == size,
+ f"Expected descriptors of size num_ang_bins * num_spatial_bins**2 = {size}, got {descriptors.shape[-1]}",
+ )
+ if source == target:
+ order = list(range(size))
+ elif target == "opencv":
+ order = _opencv_order(num_ang_bins, num_spatial_bins)
+ else:
+ # Invert the permutation: kornia position k takes the OpenCV value that `_opencv_order` sends to k.
+ inverse = [0] * size
+ for opencv_index, kornia_index in enumerate(_opencv_order(num_ang_bins, num_spatial_bins)):
+ inverse[kornia_index] = opencv_index
+ order = inverse
+ return descriptors.index_select(-1, torch.tensor(order, device=descriptors.device, dtype=torch.long))
+
+
def sift_describe(
input: torch.Tensor,
patch_size: int = 41,
diff --git a/tests/feature/test_integrated.py b/tests/feature/test_integrated.py
index fb2c4f74f..1411a6395 100644
--- a/tests/feature/test_integrated.py
+++ b/tests/feature/test_integrated.py
@@ -564,3 +564,53 @@ class TestSIFTPyramidBackend(BaseTester):
self.assert_close(returned, lafs)
self.assert_close(responses, image.new_ones(1, 1))
self.assert_close(descriptors, descriptor(image, lafs))
+
+
+class TestLightGlueKeypointConventions(BaseTester):
+ def _lafs(self, device, dtype, orientations):
+ centers = torch.zeros(1, len(orientations), 2, device=device, dtype=dtype)
+ scales = torch.full((1, len(orientations), 1, 1), 12.0, device=device, dtype=dtype)
+ angles = torch.tensor(orientations, device=device, dtype=dtype).view(1, -1, 1)
+ return kornia.feature.laf_from_center_scale_ori(centers, scales, angles)
+
+ def test_sift_uses_the_colmap_convention_of_its_training_keypoints(self, device, dtype):
+ from kornia.feature.integrated import _lightglue_keypoint_scale_ori
+
+ # kornia orientation +30 deg is COLMAP's -30 deg, -90 is +90, and 180 stays at pi in (-pi, pi]; the
+ # 12-pixel LAF is a 6-sigma DoG frame, so sigma is 2.
+ lafs = self._lafs(device, dtype, [30.0, -90.0, 180.0])
+ scales, oris = _lightglue_keypoint_scale_ori(lafs, "sift")
+ self.assert_close(scales, torch.full((1, 3), 2.0, device=device, dtype=dtype))
+ expected = torch.tensor([[-torch.pi / 6, torch.pi / 2, torch.pi]], device=device, dtype=dtype)
+ self.assert_close(oris, expected)
+
+ def test_other_features_keep_the_laf_scale_and_orientation(self, device, dtype):
+ from kornia.feature.integrated import _lightglue_keypoint_scale_ori
+
+ lafs = self._lafs(device, dtype, [30.0, -90.0])
+ scales, oris = _lightglue_keypoint_scale_ori(lafs, "doghardnet")
+ self.assert_close(scales, torch.full((1, 2), 12.0, device=device, dtype=dtype))
+ expected = torch.tensor([[torch.pi / 6, 3 * torch.pi / 2]], device=device, dtype=dtype)
+ self.assert_close(oris, expected)
+
+
+class TestSIFTDescriptorLayoutArgument(BaseTester):
+ @pytest.mark.parametrize("preset", [kornia.feature.SIFTFeature, kornia.feature.SIFTFeatureScaleSpace])
+ @pytest.mark.parametrize("backend", ["patch", "pyramid"])
+ def test_opencv_layout_reorders_only_the_descriptors(self, device, dtype, preset, backend):
+ image = torch.rand(1, 1, 64, 64, device=device, dtype=dtype)
+ default = preset(num_features=8, descriptor_backend=backend).to(device, dtype).eval()
+ opencv = preset(num_features=8, descriptor_backend=backend, descriptor_layout="opencv").to(device, dtype).eval()
+ assert default.descriptor_layout == "kornia" and opencv.descriptor_layout == "opencv"
+ lafs, responses, descriptors = default(image)
+ opencv_lafs, opencv_responses, opencv_descriptors = opencv(image)
+ self.assert_close(opencv_lafs, lafs)
+ self.assert_close(opencv_responses, responses)
+ self.assert_close(
+ opencv_descriptors, kornia.feature.convert_sift_descriptor_layout(descriptors, "kornia", "opencv")
+ )
+
+ @pytest.mark.parametrize("preset", [kornia.feature.SIFTFeature, kornia.feature.SIFTFeatureScaleSpace])
+ def test_invalid_layout(self, preset):
+ with pytest.raises(ValueError, match="layout"):
+ preset(descriptor_layout="vlfeat")
diff --git a/tests/feature/test_matching.py b/tests/feature/test_matching.py
index 2fc8554fb..dbdbb5836 100644
--- a/tests/feature/test_matching.py
+++ b/tests/feature/test_matching.py
@@ -584,9 +584,8 @@ class TestLightGlueHardNet(BaseTester):
class TestLightGlueMatcherOrientations(BaseTester):
- def test_float64_orientations_wrap_by_full_precision_two_pi_5127(self, device, monkeypatch):
- if device.type == "mps":
- pytest.skip("float64 is unavailable on MPS")
+ @staticmethod
+ def _record_lightglue_inputs(monkeypatch, device):
seen = {}
class _RecordingLightGlue(torch.nn.Module):
@@ -598,9 +597,15 @@ class TestLightGlueMatcherOrientations(BaseTester):
def forward(self, data):
seen.update(data)
matches = torch.full((1, data["image0"]["keypoints"].shape[1]), -1, device=device)
- return {"matches0": matches, "matching_scores0": torch.zeros_like(matches, dtype=torch.float64)}
+ return {"matches0": matches, "matching_scores0": torch.zeros_like(matches, dtype=torch.float32)}
monkeypatch.setattr("kornia.feature.integrated.LightGlue", _RecordingLightGlue)
+ return seen
+
+ def test_float64_orientations_wrap_by_full_precision_two_pi_5127(self, device, monkeypatch):
+ if device.type == "mps":
+ pytest.skip("float64 is unavailable on MPS")
+ seen = self._record_lightglue_inputs(monkeypatch, device)
degrees = torch.tensor([[-90.0, -45.0, 30.0], [-135.0, 60.0, -30.0]], device=device, dtype=torch.float64)
xy = torch.rand(2, 3, 2, device=device, dtype=torch.float64) * 50
scale = torch.full((2, 3, 1, 1), 4.0, device=device, dtype=torch.float64)
@@ -612,6 +617,20 @@ class TestLightGlueMatcherOrientations(BaseTester):
self.assert_close(seen["image0"]["oris"], expected[:1], rtol=0.0, atol=1e-12)
self.assert_close(seen["image1"]["oris"], expected[1:], rtol=0.0, atol=1e-12)
+ def test_sift_passes_the_training_keypoint_convention(self, device, dtype, monkeypatch):
+ seen = self._record_lightglue_inputs(monkeypatch, device)
+ degrees = torch.tensor([[30.0, -90.0, 180.0]], device=device, dtype=dtype)
+ xy = torch.tensor([[[10.0, 20.0], [30.0, 40.0], [50.0, 60.0]]], device=device, dtype=dtype)
+ scale = torch.full((1, 3, 1, 1), 12.0, device=device, dtype=dtype)
+ lafs = laf_from_center_scale_ori(xy, scale, degrees.unsqueeze(-1))
+ descriptors = torch.rand(3, 128, device=device, dtype=dtype)
+ LightGlueMatcher("sift")(descriptors, descriptors, lafs, lafs)
+ # The negated orientation in (-pi, pi], and sigma of the 12-pixel 6-sigma frame.
+ expected = torch.tensor([[-torch.pi / 6, torch.pi / 2, torch.pi]], device=device, dtype=dtype)
+ for image in ("image0", "image1"):
+ self.assert_close(seen[image]["oris"], expected)
+ self.assert_close(seen[image]["scales"], torch.full((1, 3), 2.0, device=device, dtype=dtype))
+
class TestMatchSteererGlobal(BaseTester):
@pytest.mark.parametrize("num_desc1, num_desc2, dim", [(1, 4, 4), (2, 5, 128), (6, 2, 32), (32, 32, 8)])
diff --git a/tests/feature/test_sift_scale_space.py b/tests/feature/test_sift_scale_space.py
index 23d3b899b..3f6e0dcca 100644
--- a/tests/feature/test_sift_scale_space.py
+++ b/tests/feature/test_sift_scale_space.py
@@ -21,10 +21,20 @@ import io
import pytest
import torch
+import torch.nn.functional as F
from torch import nn
-from kornia.feature import SIFTFeatureScaleSpace, get_laf_center, get_laf_orientation, laf_is_filled
-from kornia.feature.sift.scale_space import _SIFTScaleSpaceDescriptor, _SIFTScaleSpaceDetector
+from kornia.feature import (
+ LAFDescriptor,
+ SIFTDescriptor,
+ SIFTDescriptorFromPyramid,
+ SIFTFeatureScaleSpace,
+ convert_sift_descriptor_layout,
+ get_laf_center,
+ get_laf_orientation,
+ laf_is_filled,
+)
+from kornia.feature.sift.scale_space import _SIFTScalePyramid, _SIFTScaleSpaceDescriptor, _SIFTScaleSpaceDetector
from kornia.filters import spatial_gradient
from testing.base import (
@@ -36,17 +46,75 @@ from testing.base import (
)
+def _opencv_reference_image(device: torch.device, dtype: torch.dtype) -> torch.Tensor:
+ """Three asymmetric blobs on a ramp, quantized to the uint8 image OpenCV described."""
+ # Built in float64 on the CPU, which every device can receive: MPS has no float64.
+ yy, xx = torch.meshgrid(torch.arange(48, dtype=torch.float64), torch.arange(48, dtype=torch.float64), indexing="ij")
+
+ def blob(cx: float, cy: float, sigma: float) -> torch.Tensor:
+ return torch.exp(-((xx - cx) ** 2 + (yy - cy) ** 2) / (2 * sigma * sigma))
+
+ image = 0.5 + 0.3 * blob(26, 21, 2.5) - 0.25 * blob(19, 27, 2.0) + 0.15 * blob(30, 30, 1.5) + 0.004 * xx
+ return (torch.round(255 * image) / 255).to(device=device, dtype=dtype)[None, None]
+
+
+# OpenCV's SIFT descriptor of `_opencv_reference_image` at (24, 24): upright, sigma 1.6, taken from Gaussian layer 3 of
+# the doubled octave. Generated with OpenCV 5.0.0 from the same image built in numpy:
+# image = np.round(255 * image).astype(np.uint8)
+# keypoint = cv2.KeyPoint(24.0, 24.0, 3.2, 0.0, 0.0, (-1 & 255) | (3 << 8)) # size 2 * sigma; octave -1, layer 3
+# _, descriptor = cv2.SIFT_create().compute(image, [keypoint])
+_OPENCV_SIFT_DESCRIPTOR = [
+ 37, 3, 0, 0, 0, 0, 0, 7, 67, 2, 0, 0, 0, 0, 16, 123, 11, 0, 0, 0, 6, 47, 125, 92, 2, 0, 0, 0, 18, 66, 32, 3,
+ 25, 45, 48, 23, 1, 0, 0, 2, 125, 125, 26, 2, 0, 0, 3, 54, 68, 100, 71, 56, 46, 40, 43, 51, 0, 0, 8, 63, 109, 45,
+ 4, 0, 7, 29, 46, 64, 57, 32, 14, 7, 125, 125, 38, 7, 3, 4, 12, 39, 64, 125, 108, 36, 3, 0, 2, 8, 7, 3, 17, 49,
+ 20, 20, 13, 7, 3, 0, 0, 1, 14, 49, 61, 19, 60, 6, 0, 0, 1, 5, 44, 105, 96, 43, 4, 0, 0, 0, 1, 17, 17, 22,
+ 21, 15, 12, 11, 7, 6,
+] # fmt: skip
+
+
+def _describe_reference_frame(device: torch.device, dtype: torch.dtype) -> tuple[torch.Tensor, torch.Tensor]:
+ """Return the pyramid backend's upright descriptor at the OpenCV reference frame, and the frame's image."""
+ # Build the pyramid in float32 for half inputs, as the detector does.
+ work_dtype = torch.float32 if dtype in (torch.float16, torch.bfloat16) else dtype
+ image = _opencv_reference_image(device, work_dtype)
+ pyramid = [level.to(dtype) for level in _SIFTScalePyramid().to(device, work_dtype)(image)]
+ # LAF scale 6 sigma; the descriptor itself integrates over 1.25 times the frame, as OpenCV does.
+ lafs = torch.tensor([[[[9.6, 0.0, 24.0], [0.0, 9.6, 24.0]]]], device=device, dtype=dtype)
+ octaves = torch.zeros(1, 1, device=device, dtype=torch.long)
+ levels = torch.full((1, 1), 3, device=device, dtype=torch.long)
+ _, descriptor = _SIFTScaleSpaceDescriptor(rootsift=False)(pyramid, lafs, octaves, levels, upright=True)
+ return descriptor[0], image
+
+
class TestSharedSIFTScaleSpace(BaseTester):
+ def test_descriptor_matches_opencv_after_layout_conversion(self, device, dtype):
+ descriptor, _ = _describe_reference_frame(device, dtype)
+ expected = torch.tensor(_OPENCV_SIFT_DESCRIPTOR, device=device, dtype=torch.float32)[None]
+ opencv = convert_sift_descriptor_layout(descriptor, "kornia", "opencv").float()
+ # 0.997 in float32 and float64; a descriptor stored in another order stays below 0.6.
+ assert F.cosine_similarity(opencv, expected).item() > 0.99
+
+ def test_descriptor_layout_matches_the_other_sift_descriptors(self, device, dtype):
+ work_dtype = torch.float32 if dtype in (torch.float16, torch.bfloat16) else dtype
+ descriptor, image = _describe_reference_frame(device, dtype)
+ # The same frame, integrated over the same 1.25 times its LAF by the two other kornia SIFT descriptors.
+ lafs = torch.tensor([[[[12.0, 0.0, 24.0], [0.0, 12.0, 24.0]]]], device=device, dtype=work_dtype)
+ patch = LAFDescriptor(SIFTDescriptor(41, rootsift=False), patch_size=41).to(device, work_dtype)(image, lafs)
+ pyramid = SIFTDescriptorFromPyramid(rootsift=False).to(device, work_dtype)(image, lafs)
+ # About 0.87 with either; the scale-space descriptor in its former (row, column, angle) order scored 0.44.
+ for other in (patch[0], pyramid[0]):
+ assert F.cosine_similarity(descriptor.to(work_dtype), other).item() > 0.8
+
def test_trilinear_histogram_bins(self, device, dtype):
- # Hand-computed votes in (row, column, angle) order. Cancel Gaussian
- # weighting to isolate spatial interpolation and the angle 7 -> 0 seam.
+ # Hand-computed votes indexed (row, column, angle); the descriptor stores them angle-major. Cancel
+ # Gaussian weighting to isolate spatial interpolation and the angle 7 -> 0 seam.
work_dtype = torch.float32 if dtype in (torch.float16, torch.bfloat16) else dtype
xx = torch.tensor([-0.6, -0.2, 0.2, 0.6, 0.0], device=device, dtype=work_dtype)
yy = torch.tensor([0.6, -0.6, 0.2, -0.2, 0.2], device=device, dtype=work_dtype)
mass = xx.new_tensor([1.0, 2.0, 3.0, 4.0, 2.0])
mag = (mass * torch.exp(0.78125 * (xx.square() + yy.square()))).view(1, 1, -1)
angle = xx.new_tensor([0.25, 1.5, 7.75, 4.0, 2.5]).view(1, 1, -1) * (torch.pi / 4)
- actual = _SIFTScaleSpaceDescriptor._descriptor_histograms(mag, angle, xx, yy).reshape(4, 4, 8)
+ actual = _SIFTScaleSpaceDescriptor._descriptor_histograms(mag, angle, xx, yy).reshape(8, 4, 4).permute(1, 2, 0)
expected = torch.zeros_like(actual)
expected[3, 0, 0], expected[3, 0, 1] = 0.75, 0.25
expected[0, 1, 1:3] = 1.0
@@ -73,8 +141,8 @@ class TestSharedSIFTScaleSpace(BaseTester):
angle = 2 * torch.pi + torch.arange(8, device=device, dtype=torch.float64).view(1, 8, 1) * (torch.pi / 4)
centre = torch.zeros(1, device=device, dtype=torch.float64)
votes = _SIFTScaleSpaceDescriptor._descriptor_histograms(torch.ones_like(angle), angle, centre, centre)
- # Summing the 16 spatial cells leaves each frame's angular histogram.
- histogram = votes.reshape(8, 16, 8).sum(1)
+ # Summing the 16 spatial cells, the trailing axis of each angle bin, leaves each frame's angular histogram.
+ histogram = votes.reshape(8, 8, 16).sum(2)
self.assert_close(histogram, torch.eye(8, device=device, dtype=torch.float64), rtol=0.0, atol=1e-12)
def test_histogram_gradcheck(self, device):
diff --git a/tests/feature/test_siftdesc.py b/tests/feature/test_siftdesc.py
index 587dc306f..9056354e8 100644
--- a/tests/feature/test_siftdesc.py
+++ b/tests/feature/test_siftdesc.py
@@ -18,6 +18,8 @@
import pytest
import torch
+from kornia.core.exceptions import BaseError
+from kornia.feature import convert_sift_descriptor_layout
from kornia.feature.siftdesc import (
DenseSIFTDescriptor,
SIFTDescriptor,
@@ -413,3 +415,66 @@ class TestDenseSIFTDescriptor(BaseTester):
expected[:, :bins] = torch.eye(bins, device=device, dtype=torch.float64)
# The float32 pi in the orientation offset and the bin scale leaked up to 1e-7 into the lower bin.
self.assert_close(histograms[0, :, 0], expected, rtol=0.0, atol=1e-12)
+
+
+class TestConvertSIFTDescriptorLayout(BaseTester):
+ def test_smoke(self, device, dtype):
+ descriptors = torch.rand(2, 5, 128, device=device, dtype=dtype)
+ converted = convert_sift_descriptor_layout(descriptors, "kornia", "opencv")
+ assert converted.shape == descriptors.shape
+ assert converted.dtype == dtype and converted.device == descriptors.device
+
+ def test_index_mapping(self, device, dtype):
+ # kornia stores (angle, row, column) and OpenCV (row, column, angle), with the angle bins counted the other
+ # way round: kornia index a * 16 + y * 4 + x is OpenCV index (y * 4 + x) * 8 + (-a mod 8).
+ one_hot = torch.eye(128, device=device, dtype=dtype)
+ converted = convert_sift_descriptor_layout(one_hot, "kornia", "opencv")
+ assert torch.equal(converted.sum(0), torch.ones(128, device=device, dtype=dtype))
+ for kornia_index, opencv_index in ((0, 0), (18, 23), (13, 104), (32, 6), (127, 121)):
+ assert converted[kornia_index].argmax().item() == opencv_index
+
+ @pytest.mark.parametrize("num_ang_bins, num_spatial_bins", [(8, 4), (6, 3), (4, 1)])
+ def test_round_trip(self, device, dtype, num_ang_bins, num_spatial_bins):
+ descriptors = torch.rand(3, 2, num_ang_bins * num_spatial_bins**2, device=device, dtype=dtype)
+ bins = {"num_ang_bins": num_ang_bins, "num_spatial_bins": num_spatial_bins}
+ opencv = convert_sift_descriptor_layout(descriptors, "kornia", "opencv", **bins)
+ assert not torch.equal(opencv, descriptors)
+ assert torch.equal(convert_sift_descriptor_layout(opencv, "opencv", "kornia", **bins), descriptors)
+ assert torch.equal(convert_sift_descriptor_layout(descriptors, "kornia", "kornia", **bins), descriptors)
+
+ def test_angle_bins_follow_each_convention(self, device, dtype):
+ # Intensity grows downwards, so every gradient points along +y. kornia measures angles from +x towards +y
+ # (image rows run downwards), which puts it in bin 2 of 8. OpenCV measures them towards -y: bin 6.
+ ramp = torch.arange(32, device=device, dtype=torch.float32).view(32, 1).expand(32, 32)
+ descriptor = SIFTDescriptor(32, rootsift=False).to(device)(ramp[None, None]).to(dtype)
+ assert descriptor.view(8, 16).sum(-1).argmax().item() == 2
+ opencv = convert_sift_descriptor_layout(descriptor, "kornia", "opencv")
+ assert opencv.view(16, 8).sum(0).argmax().item() == 6
+
+ def test_exception(self, device, dtype):
+ descriptors = torch.rand(2, 128, device=device, dtype=dtype)
+ with pytest.raises(ValueError, match="layout"):
+ convert_sift_descriptor_layout(descriptors, "kornia", "vlfeat")
+ with pytest.raises(ValueError, match="layout"):
+ convert_sift_descriptor_layout(descriptors, "colmap", "kornia")
+ with pytest.raises(BaseError):
+ convert_sift_descriptor_layout(torch.rand(2, 100, device=device, dtype=dtype), "kornia", "opencv")
+ # -4 spatial bins square to the size of 4, and 0 angle bins match an empty descriptor.
+ with pytest.raises(ValueError, match="bin counts must be positive"):
+ convert_sift_descriptor_layout(descriptors, "kornia", "opencv", num_spatial_bins=-4)
+ with pytest.raises(ValueError, match="bin counts must be positive"):
+ convert_sift_descriptor_layout(descriptors[:, :0], "kornia", "opencv", num_ang_bins=0)
+
+ def test_gradcheck(self, device):
+ if device.type == "mps":
+ pytest.skip("MPS does not support float64 gradcheck")
+ descriptors = torch.rand(2, 128, device=device, dtype=torch.float64)
+ self.gradcheck(lambda d: convert_sift_descriptor_layout(d, "kornia", "opencv"), (descriptors,))
+
+ def test_dynamo(self, device, dtype, torch_optimizer):
+ descriptors = torch.rand(2, 128, device=device, dtype=dtype)
+
+ def op(d: torch.Tensor) -> torch.Tensor:
+ return convert_sift_descriptor_layout(d, "kornia", "opencv")
+
+ self.assert_close(torch_optimizer(op, fullgraph=True)(descriptors), op(descriptors))