🐍 Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(feature): sample SOLD2 line descriptors with the reference grid normalization (#4558)
Leonardo Vannie5ea9a0bdf2c
diff --git a/changelog.d/4558.fixed.md b/changelog.d/4558.fixed.mdnew file mode 100644index 000000000..49d82b19e--- /dev/null+++ b/changelog.d/4558.fixed.md@@ -0,0 +1,8 @@+SOLD2's line matcher now samples line descriptors at the positions the reference implementation+uses. `keypoints_to_grid` normalized keypoints with the corner-aligned mapping and fed them to+`grid_sample(align_corners=False)`, so every sample drifted by `p / (size - 1)` image pixels toward+the far edge relative to the grid the pretrained weights were trained with, up to one image pixel+and one eighth of a descriptor pixel on a 480x640 image. It now uses the reference formula+`keypoints * 2 / img_size - 1`, under which image pixel `p` reads descriptor coordinate+`p / grid_size - 0.5`. Match decisions can change anywhere except at the top-left origin; the shift+grows from zero there to one image pixel at the far edge. Fixes #4554.diff --git a/kornia/feature/sold2/sold2.py b/kornia/feature/sold2/sold2.pyindex 6a7392334..48e3c77e3 100644--- a/kornia/feature/sold2/sold2.py+++ b/kornia/feature/sold2/sold2.py@@ -25,7 +25,6 @@ from kornia.core.check import KORNIA_CHECK_SHAPEfrom kornia.core.download import hf_url, load_state_dict_from_urlfrom kornia.core.utils import dataclass_to_dict, dict_to_dataclassfrom kornia.feature.sold2.structures import DetectorCfg, LineMatcherCfg-from kornia.geometry.conversions import normalize_pixel_coordinatesfrom .backbones import SOLD2Netfrom .sold2_detector import LineSegmentDetectionModule, line_map_to_segments, prob_to_junctions@@ -329,7 +328,20 @@ class WunschLineMatcher(nn.Module):def keypoints_to_grid(keypoints: torch.Tensor, img_size: Tuple[int, int]) -> torch.Tensor:- """Convert a list of keypoints into a grid in [-1, 1]² that can be used in torch.nn.functional.interpolate.+ """Convert a list of keypoints into a grid in [-1, 1]² that can be used in torch.nn.functional.grid_sample.++ The normalization is the reference implementation's ``keypoints * 2 / img_size - 1``+ (cvg/SOLD2, ``sold2/misc/geometry_utils.py``), the convention the pretrained weights were trained+ with. It pairs with the ``align_corners=False`` sampling in :class:`WunschLineMatcher`: image pixel+ ``p`` on an axis of size ``S`` lands on descriptor-map coordinate ``p * S_desc / S - 0.5``, which is+ ``p / grid_size - 0.5`` whatever ``img_size`` is, so ``p = grid_size * (i + 0.5)`` reads descriptor+ ``i`` exactly. It is deliberately not+ :func:`kornia.geometry.conversions.normalize_pixel_coordinates`, whose corner-aligned mapping+ ``2p / (S - 1) - 1`` drifts by ``p / (S - 1)`` image pixels toward the far edge under this sampler.+ It is also not the half-pixel mapping ``(2p + 1) / S - 1``, from which it differs by a constant+ half image pixel at every ``p``. Changing either the formula or the ``align_corners`` of the+ sampler would break compatibility with the pretrained weights (compare+ :meth:`kornia.feature.xfeat.XFeat` and its ``normgrid``, which keep their own trained pairing).Args:keypoints: a torch.Tensor [N, 2] of N keypoints (ij coordinates convention).@@ -338,7 +350,8 @@ def keypoints_to_grid(keypoints: torch.Tensor, img_size: Tuple[int, int]) -> tor"""KORNIA_CHECK_SHAPE(keypoints, ["N", "2"])n_points = len(keypoints)- grid_points = normalize_pixel_coordinates(keypoints[:, [1, 0]], img_size[0], img_size[1])+ xy = keypoints[:, [1, 0]]+ grid_points = torch.stack((xy[:, 0] * 2.0 / img_size[1] - 1.0, xy[:, 1] * 2.0 / img_size[0] - 1.0), dim=-1)grid_points = grid_points.view(-1, n_points, 1, 2)return grid_pointsdiff --git a/tests/feature/test_sold2.py b/tests/feature/test_sold2.pyindex 76e2bcbf0..67f0e8c15 100644--- a/tests/feature/test_sold2.py+++ b/tests/feature/test_sold2.py@@ -17,8 +17,11 @@import pytestimport torch+import torch.nn.functional as F+from kornia.core.check import ShapeErrorfrom kornia.feature.sold2 import SOLD2, SOLD2_detector+from kornia.feature.sold2.sold2 import keypoints_to_gridfrom testing.base import BaseTester@@ -81,3 +84,77 @@ class TestSOLD2(BaseTester):model = SOLD2().to(img.device, img.dtype).eval()model_jit = torch.jit.script(model)self.assert_close(model(img), model_jit(img))+++class TestKeypointsToGrid(BaseTester):+ # keypoints_to_grid feeds F.grid_sample(..., align_corners=False) in WunschLineMatcher, so its+ # normalization has to be the one the reference implementation (cvg/SOLD2,+ # sold2/misc/geometry_utils.py) trained the weights with: keypoints * 2 / img_size - 1. Until+ # #4554 it used the corner-aligned normalize_pixel_coordinates, which drifts by p / (S - 1)+ # image pixels toward the far edge under that sampler.++ def test_smoke(self, device, dtype):+ kp = torch.tensor([[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]], device=device, dtype=dtype)+ grid = keypoints_to_grid(kp, (32, 64))+ assert grid.shape == (1, 3, 1, 2)+ assert grid.dtype == dtype+ assert grid.device == kp.device++ def test_exception(self, device, dtype):+ with pytest.raises(ShapeError, match=r"Expected shape: \['N', '2'\]"):+ keypoints_to_grid(torch.zeros(3, 3, device=device, dtype=dtype), (32, 64))+ with pytest.raises(ShapeError, match=r"Expected shape: \['N', '2'\]"):+ keypoints_to_grid(torch.zeros(1, 3, 2, device=device, dtype=dtype), (32, 64))++ def test_integer_keypoints_follow_the_default_dtype(self, device):+ # Integer keypoints promote through the float arithmetic to the ambient default dtype, the+ # dtype grid_sample will expect for a descriptor map built under the same default, and the+ # values are the reference ones (0 -> -1, the half size -> 0).+ kp = torch.tensor([[0, 0], [16, 32]], device=device, dtype=torch.int64)+ grid = keypoints_to_grid(kp, (32, 64))+ assert grid.dtype == torch.get_default_dtype()+ self.assert_close(grid[0, :, 0], torch.tensor([[-1.0, -1.0], [0.0, 0.0]], device=device))++ def test_convention_matches_reference_normalization_4554(self, device, dtype):+ # Reference: cvg/SOLD2 sold2/misc/geometry_utils.py, keypoints_to_grid.+ # grid = keypoints.float() * 2 / torch.tensor(img_size) - 1, then (x, y) reorder.+ # The figures are the issue's: on a 480x640 image with grid_size 8 (a 60x80 descriptor+ # map), grid_sample(align_corners=False) reads descriptor coordinate (g + 1) * S_desc / 2 - 0.5.+ H, W, g = 480, 640, 8+ kp = torch.tensor([[0.0, 0.0], [240.0, 320.0], [479.0, 639.0], [100.0, 639.0]], device=device, dtype=dtype)+ grid = keypoints_to_grid(kp, (H, W))++ reference = kp * 2.0 / torch.tensor([H, W], device=device, dtype=dtype) - 1.0+ reference = reference[:, [1, 0]].view(1, -1, 1, 2)+ self.assert_close(grid, reference, atol=0.0, rtol=0.0)++ desc_size = torch.tensor([W // g, H // g], device=device, dtype=dtype) # (x, y)+ reads = (grid[0, :, 0] + 1.0) * desc_size / 2.0 - 0.5+ expected = torch.tensor(+ [[-0.5, -0.5], [39.5, 29.5], [79.375, 59.375], [79.375, 12.0]], device=device, dtype=dtype+ )+ # Pre-#4554 the same keypoints read (-0.5, -0.5), (39.5625, 29.5625), (79.5, 59.5),+ # (79.5, 12.026), i.e. half a descriptor pixel past the last centre at the far edge.+ self.assert_close(reads, expected)++ def test_convention_cell_keypoint_reads_its_own_descriptor_4554(self, device, dtype):+ # Under the reference normalization image pixel p reads descriptor coordinate p / g - 0.5, so+ # the keypoint (g * (i + 0.5), g * (j + 0.5)) lands exactly on descriptor (i, j) and sampling+ # with the matcher's align_corners=False returns that descriptor untouched. (That keypoint is+ # half an image pixel past the centre of cell (i, j) under kornia's pixel-centre convention,+ # which is the constant offset from the half-pixel mapping the docstring records.)+ # Power-of-two sizes keep every coordinate exact at half precision.+ H, W, g = 32, 64, 8+ hd, wd = H // g, W // g+ desc = torch.rand(1, 5, hd, wd, device=device, dtype=dtype)+ ii, jj = torch.meshgrid(torch.arange(hd, device=device), torch.arange(wd, device=device), indexing="ij")+ kp = torch.stack(((ii.flatten() + 0.5) * g, (jj.flatten() + 0.5) * g), dim=-1).to(dtype)+ grid = keypoints_to_grid(kp, (H, W))+ sampled = F.grid_sample(desc, grid, align_corners=False)[0, :, :, 0] # (C, hd * wd)+ self.assert_close(sampled, desc[0].reshape(5, -1))++ def test_dynamo(self, device, dtype, torch_optimizer):+ kp = torch.tensor([[1.0, 2.0], [30.0, 60.0]], device=device, dtype=dtype)+ op = keypoints_to_grid+ op_optimized = torch_optimizer(op)+ self.assert_close(op(kp, (32, 64)), op_optimized(kp, (32, 64)))