Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(feature): sample LAF patches at the pixels the LAF names (#5681)

Dmytro Mishkinad6c10efdf51
diff --git a/changelog.d/5681.fixed.md b/changelog.d/5681.fixed.md
new file mode 100644
index 000000000..b9addbe78
--- /dev/null
+++ b/changelog.d/5681.fixed.md
@@ -0,0 +1 @@
+`extract_patches_simple` and `extract_patches_from_pyramid` now sample the pixels a LAF describes. They built their grids in the corner-aligned frame (`2x / (W - 1) - 1`) and then sampled with `align_corners=False`, so a LAF centred on pixel `x` was read at `x * W / (W - 1) - 0.5`: up to half a pixel off, and stretched by `W / (W - 1)`. An axis-aligned LAF of scale `PS / 2` with odd `PS` now returns exactly the image crop, and a LAF covering a whole `W`-pixel axis has scale `W / 2`, where it used to be `(W - 1) / 2`. Descriptors, LAF orientations and AffNet shapes change for every pipeline that cuts patches from LAFs: `SIFTFeature` and `SIFTFeatureScaleSpace` with the `"patch"` backend, `HesAffNetHardNet`, `GFTTAffNetHardNet`, `KeyNetHardNet` and `KeyNetAffNetHardNet`. The `"pyramid"` SIFT backends are unchanged.
diff --git a/kornia/feature/laf.py b/kornia/feature/laf.py
index 21d17ada8..bc7fcadd0 100644
--- a/kornia/feature/laf.py
+++ b/kornia/feature/laf.py
@@ -477,10 +477,10 @@ def generate_patch_grid_from_normalized_LAF(img: torch.Tensor, LAF: torch.Tensor
LAF_renorm = denormalize_laf(LAF, img)
grid = F.affine_grid(LAF_renorm.view(B * N, 2, 3), [B * N, ch, PS, PS], align_corners=False)
- # A singleton axis has no spatial extent; one pixel of denominator keeps the grid finite and
- # lets the border padding return that single pixel (see `denormalize_laf`).
- grid[..., :, 0] = 2.0 * grid[..., :, 0].clone() / float(max(w - 1, 1)) - 1.0
- grid[..., :, 1] = 2.0 * grid[..., :, 1].clone() / float(max(h - 1, 1)) - 1.0
+ # The grid is in pixels, centres at integers (the LAF frame); `grid_sample(align_corners=False)` puts pixel x at
+ # (2x + 1) / W - 1. A singleton axis maps every sample to its only pixel's centre.
+ grid[..., :, 0] = (2.0 * grid[..., :, 0].clone() + 1.0) / float(w) - 1.0
+ grid[..., :, 1] = (2.0 * grid[..., :, 1].clone() + 1.0) / float(h) - 1.0
return grid
@@ -588,6 +588,31 @@ def _sample_patches(img: torch.Tensor, grid: torch.Tensor, h: int, w: int) -> to
return _grid_sample_patches(img, folded, h, w).view(B, ch, N, PS, PS).permute(0, 2, 1, 3, 4)
+def _pyramid_grid_frame(nlaf: torch.Tensor, h: int, w: int) -> Tuple[torch.Tensor, torch.Tensor]:
+ r"""Return the scale ``k`` and translation ``t`` that map a normalized LAF's patch grid to sampling coordinates.
+
+ ``grid = affine_grid(A, align_corners=False) * k + t`` addresses, for ``grid_sample(align_corners=False)``, the
+ input pixels the LAF describes: pixel :math:`x` of the :math:`(h, w)` input sits at :math:`(2x + 1) / w - 1`.
+ ``pyrdown`` resizes to ``floor(side / 2)`` with ``align_corners=False``, so input pixel :math:`x` is pixel
+ :math:`(x + 0.5) w_l / w - 0.5` of level :math:`l` -- which that level's ``grid_sample`` addresses at the same
+ :math:`(2x + 1) / w - 1`. One grid therefore serves every pyramid level.
+
+ Args:
+ nlaf: normalized LAFs :math:`(B, N, 2, 3)` (``normalize_laf``'s frame).
+ h: input height.
+ w: input width.
+
+ Returns:
+ ``k`` of shape :math:`(2,)` and ``t`` of shape :math:`(B, N, 2)`, in ``nlaf``'s dtype and device.
+ """
+ # `denormalize_laf`'s extents: a singleton axis counts as one pixel.
+ wf, hf = float(max(w - 1, 1)), float(max(h - 1, 1))
+ min_size = min(wf, hf)
+ k = nlaf.new_tensor([2.0 * min_size / float(w), 2.0 * min_size / float(h)])
+ t = (2.0 * nlaf[..., :, 2] * nlaf.new_tensor([wf, hf]) + 1.0) / nlaf.new_tensor([float(w), float(h)]) - 1.0
+ return k, t
+
+
def _extract_patches_from_pyramid_levelwise(
img: torch.Tensor,
nlaf: torch.Tensor,
@@ -612,7 +637,7 @@ def _extract_patches_from_pyramid_levelwise(
chunk = _grid_chunk_lafs(B, N, ch, PS, _grid_elem_bytes(grid_dtype))
cur_img = img.to(grid_laf.dtype) if img.dtype != grid_laf.dtype else img
laf_a = grid_laf[..., :2]
- t = 2.0 * grid_laf[..., :, 2] - 1.0
+ k, t = _pyramid_grid_frame(grid_laf, heights[0], widths[0])
# Most calls fit in one bounded chunk, so their level-independent affine grid can be reused
# across the streaming pyramid. A multi-chunk call rebuilds each chunk's grid per level rather
@@ -641,11 +666,6 @@ def _extract_patches_from_pyramid_levelwise(
B, nc, PS, PS, 2
)
translation = t[:, st:en].view(B, nc, 1, 1, 2)
- # Match `normalize_laf` / `denormalize_laf`: a singleton axis counts as one pixel of
- # extent. Border padding still repeats that axis's only pixel, while the other axis
- # keeps its spatial variation instead of being collapsed by a shared zero `min_l`.
- min_l = float(min(max(h_l - 1, 1), max(w_l - 1, 1)))
- k = base_grid.new_tensor([2.0 * min_l / float(max(w_l - 1, 1)), 2.0 * min_l / float(max(h_l - 1, 1))])
grid = base_grid * k + translation
patches = _sample_patches(cur_img, grid, h_l, w_l).to(img.dtype)
mask = (pyr_idx[:, st:en] == level_idx).view(B, en - st, 1, 1, 1)
@@ -780,15 +800,12 @@ def extract_patches_from_pyramid(
# levelwise path preserves the same clamping and reduced-precision grid semantics. The atlas
# is built in the grid's dtype -- reduced-precision inputs are upcast once, so the replicate
# pad, `pyrdown` and every chunk's `grid_sample` run on kernels every torch build has, and no
- # full-atlas recast is paid per chunk. A 1-pixel axis in any *built level* -- a 1-pixel input
- # image, or a coarse level that `PS == 1` lets the pyramid descend to -- would make the level
- # constants' Python `size - 1` division below raise; the levelwise sampler treats that axis
- # as having zero spatial extent instead.
+ # full-atlas recast is paid per chunk.
atlas_elements = B * ch * atlas_h * atlas_w
atlas_bytes = atlas_elements * _grid_elem_bytes(grid_dtype)
if img.dtype != grid_dtype:
atlas_bytes += B * ch * h * w * _grid_elem_bytes(grid_dtype) # the one-time upcast copy
- if min(heights[-1], widths[-1]) < 2 or not _pyramid_atlas_fits(atlas_bytes):
+ if not _pyramid_atlas_fits(atlas_bytes):
return _extract_patches_from_pyramid_levelwise(img, nlaf, pyr_idx, heights, widths, PS)
sample_img = img.to(grid_dtype) if img.dtype != grid_dtype else img
atlas = sample_img.new_zeros(B, ch, atlas_h, atlas_w)
@@ -804,7 +821,7 @@ def extract_patches_from_pyramid(
# zero translation; reduced-precision inputs need float32 grid arithmetic because the atlas is
# wider than the original image.
laf_a = nlaf[..., :2].to(grid_dtype)
- t = 2.0 * nlaf[..., :, 2].to(grid_dtype) - 1.0
+ k, t = _pyramid_grid_frame(nlaf.to(grid_dtype), h, w)
# Gather all level-dependent conversion constants per patch, packed as (x, y) pairs so the
# remap below runs on the whole grid tensor step by step, never holding split-axis copies. A
@@ -813,11 +830,8 @@ def extract_patches_from_pyramid(
xoff = 0
constants = []
for h_l, w_l in zip(heights, widths):
- min_l = float(min(h_l - 1, w_l - 1))
constants.append(
(
- 2.0 * min_l / float(w_l - 1), # k: LAF frame -> level-normalized units
- 2.0 * min_l / float(h_l - 1),
-1.0 + 1.0 / float(w_l), # lo/hi: the level's outermost pixel centers
-1.0 + 1.0 / float(h_l),
1.0 - 1.0 / float(w_l),
@@ -829,7 +843,7 @@ def extract_patches_from_pyramid(
)
)
xoff += w_l + 2
- level_constants = torch.tensor(constants, dtype=grid_dtype, device=nlaf.device).view(-1, 5, 2)
+ level_constants = torch.tensor(constants, dtype=grid_dtype, device=nlaf.device).view(-1, 4, 2)
# The folded grid and its remap intermediates scale with B*N*PS^2, so sampling is chunked
# along N to bound peak memory; each chunk repeats exactly the single-call arithmetic, and
@@ -845,9 +859,7 @@ def extract_patches_from_pyramid(
nc = en - st
theta = torch.cat([laf_a[:, st:en], torch.zeros(B, nc, 2, 1, dtype=grid_dtype, device=nlaf.device)], dim=-1)
grid = F.affine_grid(theta.view(B * nc, 2, 3), [B * nc, ch, PS, PS], align_corners=False).view(B, nc, PS, PS, 2)
- k, lo, hi, level_scale, level_offset = (
- level_constants[safe_pyr_idx[:, st:en]].view(B, nc, 1, 1, 5, 2).unbind(-2)
- )
+ lo, hi, level_scale, level_offset = level_constants[safe_pyr_idx[:, st:en]].view(B, nc, 1, 1, 4, 2).unbind(-2)
grid = grid * k
grid = grid + t[:, st:en].view(B, nc, 1, 1, 2)
grid = grid.maximum(lo)
diff --git a/tests/feature/test_affine_shape_estimator.py b/tests/feature/test_affine_shape_estimator.py
index df95f0d92..69ed24ff3 100644
--- a/tests/feature/test_affine_shape_estimator.py
+++ b/tests/feature/test_affine_shape_estimator.py
@@ -172,9 +172,10 @@ class TestLAFAffineShapeEstimator(BaseTester):
aff = LAFAffineShapeEstimator(32, preserve_orientation=False).to(device, dtype)
inp = torch.zeros(1, 1, 32, 32, device=device, dtype=dtype)
inp[:, :, 15:-15, 9:-9] = 1
- laf = torch.tensor([[[[20.0, 0.0, 16.0], [0.0, 20.0, 16.0]]]], device=device, dtype=dtype)
+ # The bar (rows 15-16, columns 9-22) is centred on pixel (15.5, 15.5), where the LAF sits.
+ laf = torch.tensor([[[[20.0, 0.0, 15.5], [0.0, 20.0, 15.5]]]], device=device, dtype=dtype)
new_laf = aff(laf, inp)
- expected = torch.tensor([[[[35.078, 0.0, 16.0], [0.0, 11.403, 16.0]]]], device=device, dtype=dtype)
+ expected = torch.tensor([[[[36.6428, 0.0, 15.5], [0.0, 10.9162, 15.5]]]], device=device, dtype=dtype)
if dtype in (torch.float16, torch.bfloat16):
# Use the repository's dtype-specific tolerances for the newly supported half-precision path.
self.assert_close(new_laf, expected)
@@ -185,9 +186,10 @@ class TestLAFAffineShapeEstimator(BaseTester):
aff = LAFAffineShapeEstimator(32, preserve_orientation=True).to(device, dtype)
inp = torch.zeros(1, 1, 32, 32, device=device, dtype=dtype)
inp[:, :, 15:-15, 9:-9] = 1
- laf = torch.tensor([[[[0.0, 20.0, 16.0], [-20.0, 0.0, 16.0]]]], device=device, dtype=dtype)
+ # The bar (rows 15-16, columns 9-22) is centred on pixel (15.5, 15.5), where the LAF sits.
+ laf = torch.tensor([[[[0.0, 20.0, 15.5], [-20.0, 0.0, 15.5]]]], device=device, dtype=dtype)
new_laf = aff(laf, inp)
- expected = torch.tensor([[[[0.0, 35.078, 16.0], [-11.403, 0, 16.0]]]], device=device, dtype=dtype)
+ expected = torch.tensor([[[[0.0, 36.6428, 15.5], [-10.9162, 0, 15.5]]]], device=device, dtype=dtype)
if dtype in (torch.float16, torch.bfloat16):
# Orientation recovery adds small absolute noise to entries whose ideal value is zero.
self.assert_close(new_laf, expected, atol=2e-2, rtol=1e-3 if dtype == torch.float16 else 7.8e-3)
@@ -198,9 +200,10 @@ class TestLAFAffineShapeEstimator(BaseTester):
aff = LAFAffineShapeEstimator(32, preserve_orientation=False).to(device)
inp = torch.zeros(1, 1, 32, 32, device=device)
inp[:, :, 15:-15, 9:-9] = 1
- laf = torch.tensor([[[[0.0, 20.0, 16.0], [-20.0, 0.0, 16.0]]]], device=device)
+ # The bar (rows 15-16, columns 9-22) is centred on pixel (15.5, 15.5), where the LAF sits.
+ laf = torch.tensor([[[[0.0, 20.0, 15.5], [-20.0, 0.0, 15.5]]]], device=device)
new_laf = aff(laf, inp)
- expected = torch.tensor([[[[35.078, 0, 16.0], [0, 11.403, 16.0]]]], device=device)
+ expected = torch.tensor([[[[36.6428, 0, 15.5], [0, 10.9162, 15.5]]]], device=device)
self.assert_close(new_laf, expected, atol=1e-4, rtol=1e-4)
def test_degenerate_ellipse_falls_back_to_input_laf_float16(self, device, dtype):
@@ -297,7 +300,8 @@ class TestLAFAffineShapeEstimator(BaseTester):
def test_gradcheck(self, device):
batch_size, channels, height, width = 1, 1, 40, 40
patches = torch.rand(batch_size, channels, height, width, device=device, dtype=torch.float64)
- laf = torch.tensor([[[[5.0, 0.0, 26.0], [0.0, 5.0, 26.0]]]], device=device, dtype=torch.float64)
+ # Off the pixel lattice: a sample exactly on a pixel centre sits on a kink of bilinear interpolation.
+ laf = torch.tensor([[[[5.0, 0.0, 26.3], [0.0, 5.0, 26.3]]]], device=device, dtype=torch.float64)
self.gradcheck(
LAFAffineShapeEstimator(11).to(device),
(laf, patches),
@@ -367,17 +371,19 @@ class TestLAFAffNetShapeEstimator(BaseTester):
aff = LAFAffNetShapeEstimator(True).to(device, dtype).eval()
inp = torch.zeros(1, 1, 32, 32, device=device, dtype=dtype)
inp[:, :, 15:-15, 9:-9] = 1
- laf = torch.tensor([[[[20.0, 0.0, 16.0], [0.0, 20.0, 16.0]]]], device=device, dtype=dtype)
+ # The bar (rows 15-16, columns 9-22) is centred on pixel (15.5, 15.5), where the LAF sits.
+ laf = torch.tensor([[[[20.0, 0.0, 15.5], [0.0, 20.0, 15.5]]]], device=device, dtype=dtype)
new_laf = aff(laf, inp)
- expected = torch.tensor([[[[33.2073, 0.0, 16.0], [-1.3766, 12.0456, 16.0]]]], device=device, dtype=dtype)
+ expected = torch.tensor([[[[40.87576, 0.0, 15.5], [-0.38244, 9.78575, 15.5]]]], device=device, dtype=dtype)
if dtype in (torch.float16, torch.bfloat16):
# AffNet's convolutions carry reduced-precision noise proportional to the LAF's own scale
- # (~33 px), not to each entry's magnitude, so the small a21 entry (-1.38) cannot be held to a
- # relative bound: it misses by 0.024 (float16) and 0.031 (bfloat16), bitwise identical on
- # torch 2.9.1 and 2.14.0. The 1e-1 bound is ~3 float16 ULP at that scale, so it is set by the
- # dtype rather than by the observed miss and does not need re-tuning per platform. It still
- # discriminates: a genuine shape regression moves these entries by O(1).
- self.assert_close(new_laf, expected, atol=1e-1, rtol=1e-3 if dtype == torch.float16 else 7.8e-3)
+ # (~41 px), not to each entry's magnitude, so the small a21 entry (-0.38) cannot be held to a
+ # relative bound: the largest miss is 0.032 in float16 and 0.149 in bfloat16 (torch 2.14.0).
+ # The bounds are set by the dtype, not by the observed miss: ~3 float16 ULP (1e-1) and one
+ # bfloat16 ULP (0.25) at that scale. They still discriminate: a genuine shape regression
+ # moves these entries by O(1).
+ atol = 1e-1 if dtype == torch.float16 else 0.25
+ self.assert_close(new_laf, expected, atol=atol, rtol=1e-3 if dtype == torch.float16 else 7.8e-3)
else:
atol = 5e-3 if (device.type == "cuda" and dtype == torch.float32) else 1e-4
self.assert_close(new_laf, expected, atol=atol, rtol=1e-4)
diff --git a/tests/feature/test_integrated.py b/tests/feature/test_integrated.py
index 16075a595..536cbb099 100644
--- a/tests/feature/test_integrated.py
+++ b/tests/feature/test_integrated.py
@@ -72,7 +72,11 @@ class TestGetLAFDescriptors(BaseTester):
B, C, H, W = 1, 1, 32, 32
PS = 16
img = torch.rand(B, C, H, W, device=device)
- centers = torch.tensor([[H / 2.0, W / 2.0], [2.0 * H / 3.0, W / 2.0]], device=device, dtype=dtype).view(1, 2, 2)
+ # Off the pixel lattice: a sample exactly on a pixel centre sits on a kink of bilinear interpolation, where the
+ # central difference and the one-sided analytical derivative disagree.
+ centers = torch.tensor(
+ [[H / 2.0 + 0.3, W / 2.0 + 0.3], [2.0 * H / 3.0, W / 2.0 + 0.3]], device=device, dtype=dtype
+ ).view(1, 2, 2)
scales = torch.tensor([(H + W) / 5.0, (H + W) / 6.0], device=device, dtype=dtype).view(1, 2, 1, 1)
ori = torch.tensor([0.0, 30.0], device=device, dtype=dtype).view(1, 2, 1)
lafs = kornia.feature.laf_from_center_scale_ori(centers, scales, ori)
@@ -216,7 +220,11 @@ class TestLAFDescriptor(BaseTester):
B, C, H, W = 1, 1, 32, 32
PS = 16
img = torch.rand(B, C, H, W, device=device)
- centers = torch.tensor([[H / 2.0, W / 2.0], [2.0 * H / 3.0, W / 2.0]], device=device).view(1, 2, 2)
+ # Off the pixel lattice: a sample exactly on a pixel centre sits on a kink of bilinear interpolation, where the
+ # central difference and the one-sided analytical derivative disagree.
+ centers = torch.tensor([[H / 2.0 + 0.3, W / 2.0 + 0.3], [2.0 * H / 3.0, W / 2.0 + 0.3]], device=device).view(
+ 1, 2, 2
+ )
scales = torch.tensor([(H + W) / 5.0, (H + W) / 6.0], device=device).view(1, 2, 1, 1)
ori = torch.tensor([0.0, 30.0], device=device).view(1, 2, 1)
lafs = kornia.feature.laf_from_center_scale_ori(centers, scales, ori)
diff --git a/tests/feature/test_laf.py b/tests/feature/test_laf.py
index 2c660eeff..596c1742a 100644
--- a/tests/feature/test_laf.py
+++ b/tests/feature/test_laf.py
@@ -876,14 +876,16 @@ class TestExtractPatchesSimple(BaseTester):
def test_same_odd(self, device, dtype):
img = torch.arange(5)[None].repeat(5, 1)[None, None].to(device, dtype)
- laf = torch.tensor([[2.0, 0, 2.0], [0, 2.0, 2.0]]).reshape(1, 1, 2, 3).to(device, dtype)
+ # The whole image spans pixels -0.5 .. 4.5: centre 2, scale PS / 2.
+ laf = torch.tensor([[2.5, 0, 2.0], [0, 2.5, 2.0]]).reshape(1, 1, 2, 3).to(device, dtype)
patch = kornia.feature.extract_patches_simple(img, laf, 5, 1.0)
self.assert_close(img, patch[0])
def test_same_even(self, device, dtype):
img = torch.arange(4)[None].repeat(4, 1)[None, None].to(device, dtype)
- laf = torch.tensor([[1.5, 0, 1.5], [0, 1.5, 1.5]]).reshape(1, 1, 2, 3).to(device, dtype)
+ # The whole image spans pixels -0.5 .. 3.5: centre 1.5, scale PS / 2.
+ laf = torch.tensor([[2.0, 0, 1.5], [0, 2.0, 1.5]]).reshape(1, 1, 2, 3).to(device, dtype)
patch = kornia.feature.extract_patches_simple(img, laf, 4, 1.0)
self.assert_close(img, patch[0])
@@ -1020,14 +1022,16 @@ class TestExtractPatchesPyr(BaseTester):
def test_same_odd(self, device, dtype):
img = torch.arange(5)[None].repeat(5, 1)[None, None].to(device, dtype)
- laf = torch.tensor([[2.0, 0, 2.0], [0, 2.0, 2.0]]).reshape(1, 1, 2, 3).to(device, dtype)
+ # The whole image spans pixels -0.5 .. 4.5: centre 2, scale PS / 2.
+ laf = torch.tensor([[2.5, 0, 2.0], [0, 2.5, 2.0]]).reshape(1, 1, 2, 3).to(device, dtype)
patch = kornia.feature.extract_patches_from_pyramid(img, laf, 5, 1.0)
self.assert_close(img, patch[0])
def test_same_even(self, device, dtype):
img = torch.arange(4)[None].repeat(4, 1)[None, None].to(device, dtype)
- laf = torch.tensor([[1.5, 0, 1.5], [0, 1.5, 1.5]]).reshape(1, 1, 2, 3).to(device, dtype)
+ # The whole image spans pixels -0.5 .. 3.5: centre 1.5, scale PS / 2.
+ laf = torch.tensor([[2.0, 0, 1.5], [0, 2.0, 1.5]]).reshape(1, 1, 2, 3).to(device, dtype)
patch = kornia.feature.extract_patches_from_pyramid(img, laf, 4, 1.0)
self.assert_close(img, patch[0])
@@ -1092,14 +1096,14 @@ class TestExtractPatchesPyr(BaseTester):
def test_one_pixel_axis_preserves_non_singleton_extent(self, device, dtype):
# A singleton axis must collapse only itself. The other axis still has spatial extent, so
- # a full-image LAF over a 1x5 or 5x1 ramp must retain that ramp instead of degenerating to
- # the center pixel in both directions.
+ # a full-image LAF (scale W / 2 and H / 2) over a 1x5 or 5x1 ramp must retain that ramp
+ # instead of degenerating to the center pixel in both directions.
for h, w in ((1, 5), (5, 1)):
img = torch.arange(5, device=device, dtype=dtype).reshape(1, 1, h, w)
pixel_laf = torch.tensor(
[
- [float(max(w - 1, 1)) / 2.0, 0.0, float(w - 1) / 2.0],
- [0.0, float(max(h - 1, 1)) / 2.0, float(h - 1) / 2.0],
+ [float(w) / 2.0, 0.0, float(w - 1) / 2.0],
+ [0.0, float(h) / 2.0, float(h - 1) / 2.0],
],
device=device,
dtype=dtype,
@@ -1218,10 +1222,10 @@ class TestExtractPatchesPyr(BaseTester):
monkeypatch.setattr(laf_module, "_pyramid_atlas_fits", lambda *args: limit > 0)
img = torch.zeros(1, 1, size, size, device=device, dtype=dtype)
img[:, :, :, -1] = 1.0
- # A quarter pixel OUTSIDE the outermost pixel center, so the clamp engages strictly on
- # every backend: probing exactly at the center can round onto the clamp bound, where
- # the subgradient convention differs between CPU and MPS.
- center_x = 1.0 - 1.0 / (4.0 * size)
+ # A quarter pixel OUTSIDE the outermost pixel center (pixel size - 1, normalized 1), so
+ # the clamp engages strictly on every backend: probing exactly at the center can round
+ # onto the clamp bound, where the subgradient convention differs between CPU and MPS.
+ center_x = 1.0 + 0.25 / (size - 1)
nlaf = torch.tensor(
[[[[0.0, 0.0, center_x], [0.0, 0.0, 0.5]]]], device=device, dtype=dtype, requires_grad=True
)
@@ -1503,6 +1507,74 @@ def test_nonfinite_laf_backward_does_not_crash_the_interpreter():
)
+_EXTRACTORS = [kornia.feature.extract_patches_simple, kornia.feature.extract_patches_from_pyramid]
+
+
+class TestPatchSamplingFrame(BaseTester):
+ # A LAF lives in the image's pixel frame: pixel centres at integers, as `normalize_laf` and
+ # `get_laf_center` use. Sampling it with corner-aligned grid coordinates read pixel x * W / (W - 1) - 0.5 instead.
+
+ @pytest.mark.parametrize("extract", _EXTRACTORS)
+ def test_pure_crop_laf_returns_the_image_crop_5678(self, extract, device, dtype):
+ # Axis-aligned LAF of scale PS / 2 with an odd PS: one patch pixel per image pixel, centred on an integer pixel
+ # away from the image centre, where the corner-aligned grid was exact.
+ g = torch.Generator().manual_seed(0)
+ img = torch.rand(1, 1, 60, 75, generator=g).to(device=device, dtype=dtype)
+ x, y, ps = 30, 22, 41
+ laf = kornia.feature.laf_from_center_scale_ori(
+ torch.tensor([[[float(x), float(y)]]], device=device, dtype=dtype),
+ torch.full((1, 1, 1, 1), ps / 2.0, device=device, dtype=dtype),
+ )
+ patch = extract(img, laf, ps)[0, 0, 0]
+ self.assert_close(patch, img[0, 0, y - 20 : y + 21, x - 20 : x + 21])
+ self.assert_close(patch[20, 20], img[0, 0, y, x])
+
+ @pytest.mark.parametrize("extract", _EXTRACTORS)
+ def test_laf_centre_is_sampled_at_itself_with_unit_steps_5678(self, extract, device, dtype):
+ H, W = 9, 13
+ xs = torch.arange(W, device=device, dtype=dtype).view(1, 1, 1, W).expand(1, 1, H, W).contiguous()
+ ys = torch.arange(H, device=device, dtype=dtype).view(1, 1, H, 1).expand(1, 1, H, W).contiguous()
+ for x, y in [(3.0, 2.0), (9.0, 6.0), (10.0, 3.0)]:
+ laf = kornia.feature.laf_from_center_scale_ori(
+ torch.tensor([[[x, y]]], device=device, dtype=dtype),
+ torch.full((1, 1, 1, 1), 1.5, device=device, dtype=dtype),
+ )
+ px, py = extract(xs, laf, 3)[0, 0, 0], extract(ys, laf, 3)[0, 0, 0]
+ self.assert_close(px[1], torch.tensor([x - 1.0, x, x + 1.0], device=device, dtype=dtype))
+ self.assert_close(py[:, 1], torch.tensor([y - 1.0, y, y + 1.0], device=device, dtype=dtype))
+
+ @pytest.mark.parametrize("atlas", [True, False])
+ @pytest.mark.parametrize("level", [1, 2])
+ def test_pyramid_level_samples_the_same_pixels_5678(self, level, atlas, device, dtype, monkeypatch):
+ # `pyrdown` resizes to floor(side / 2) with align_corners=False, so input pixel x is pixel
+ # (x + 0.5) * W_l / W - 0.5 of level l, per axis. A patch taken from level l has to equal the plain
+ # extraction from that level at the LAF mapped there; odd sizes make W_l / W differ from 2 ** -l.
+ import kornia.feature.laf as laf_module
+
+ if dtype in (torch.float16, torch.bfloat16):
+ pytest.skip("pyrdown in half precision differs from the pyramid's float32 levels")
+ monkeypatch.setattr(laf_module, "_pyramid_atlas_fits", lambda *args: atlas)
+ g = torch.Generator().manual_seed(0)
+ img = torch.rand(1, 1, 61, 75, generator=g).to(device=device, dtype=dtype)
+ ps = 8
+ laf = kornia.feature.laf_from_center_scale_ori(
+ torch.tensor([[[37.3, 30.6]]], device=device, dtype=dtype),
+ torch.full((1, 1, 1, 1), 4.0 * 2**level + 0.5, device=device, dtype=dtype),
+ torch.full((1, 1, 1), 30.0, device=device, dtype=dtype),
+ )
+ level_img = img
+ for _ in range(level):
+ level_img = kornia.geometry.transform.pyrdown(level_img)
+ sx, sy = level_img.shape[-1] / img.shape[-1], level_img.shape[-2] / img.shape[-2]
+ level_laf = laf.clone()
+ level_laf[..., 0, :2] *= sx
+ level_laf[..., 1, :2] *= sy
+ level_laf[..., 0, 2] = (laf[..., 0, 2] + 0.5) * sx - 0.5
+ level_laf[..., 1, 2] = (laf[..., 1, 2] + 0.5) * sy - 0.5
+ expected = kornia.feature.extract_patches_simple(level_img, level_laf, ps)
+ self.assert_close(kornia.feature.extract_patches_from_pyramid(img, laf, ps), expected)
+
+
class TestLAFIsTouchingBoundary(BaseTester):
def test_shape(self, device):
inp = torch.rand(5, 3, 2, 3, device=device)