Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(geometry): use pixel offsets in the conv_soft_argmax2d/3d window kernel (#5059)

Mohammad Hijjawi732edcbacc60
diff --git a/changelog.d/5059.breaking.md b/changelog.d/5059.breaking.md
new file mode 100644
index 000000000..000521459
--- /dev/null
+++ b/changelog.d/5059.breaking.md
@@ -0,0 +1,7 @@
+`conv_soft_argmax2d`, `conv_soft_argmax3d`, `ConvSoftArgmax2d` and `ConvSoftArgmax3d` now measure each window's
+softmax-weighted offset from the window centre in pixels, so a window returns the softmax expectation of its pixel
+coordinates, as the docstring formula states. Previously the offset kernel ran from βˆ’1 to 1 along every axis whatever
+the window size, which scaled the offset by 2/(k βˆ’ 1): a 5-wide window reported a peak at x = 8 as x = 7, a 7-wide
+window as x = 6, and a 2-wide window doubled the offset. Window sizes 1 and 3 (the default) give the same output as
+before; any other `kernel_size` entry changes the coordinates along that axis, in pixels and in normalized coordinates.
+(#5017)
diff --git a/kornia/geometry/subpix/spatial_soft_argmax.py b/kornia/geometry/subpix/spatial_soft_argmax.py
index 3aa1c7e34..be67433c7 100644
--- a/kornia/geometry/subpix/spatial_soft_argmax.py
+++ b/kornia/geometry/subpix/spatial_soft_argmax.py
@@ -73,8 +73,9 @@ def _get_window_grid_kernel2d(h: int, w: int, device: Optional[torch.device] = N
"""
if device is None:
device = torch.device("cpu")
+ # pixel offsets from the window center, (k - 1) / 2 per axis, as _get_center_kernel2d averages to
window_grid2d = create_meshgrid(h, w, False, device=device)
- window_grid2d = normalize_pixel_coordinates(window_grid2d, h, w)
+ window_grid2d = window_grid2d - torch.tensor([(w - 1) / 2, (h - 1) / 2], device=device, dtype=window_grid2d.dtype)
return window_grid2d.permute(3, 0, 1, 2)
@@ -166,11 +167,10 @@ def _get_window_grid_kernel3d(d: int, h: int, w: int, device: Optional[torch.dev
"""
if device is None:
device = torch.device("cpu")
- grid2d = create_meshgrid(h, w, True, device=device)
- if d > 1:
- z = torch.linspace(-1, 1, d, device=device).view(d, 1, 1, 1)
- else: # only onr channel with index == 0
- z = torch.zeros(1, 1, 1, 1, device=device)
+ # voxel offsets from the window center, (k - 1) / 2 per axis, as _get_center_kernel3d averages to
+ grid2d = create_meshgrid(h, w, False, device=device)
+ grid2d = grid2d - torch.tensor([(w - 1) / 2, (h - 1) / 2], device=device, dtype=grid2d.dtype)
+ z = (torch.arange(d, device=device, dtype=grid2d.dtype) - (d - 1) / 2).view(d, 1, 1, 1)
grid3d = torch.cat([z.repeat(1, h, w, 1).contiguous(), grid2d.repeat(d, 1, 1, 1)], 3)
return grid3d.permute(3, 0, 1, 2).unsqueeze(1)
diff --git a/tests/geometry/subpix/test_spatial_softargmax.py b/tests/geometry/subpix/test_spatial_softargmax.py
index abb426b1a..7e7d64a6a 100644
--- a/tests/geometry/subpix/test_spatial_softargmax.py
+++ b/tests/geometry/subpix/test_spatial_softargmax.py
@@ -350,6 +350,24 @@ class TestConvSoftArgmax2d(BaseTester):
op_opt = torch_optimizer(op, fullgraph=True)
self.assert_close(op(data, temperature=temperature), op_opt(data, temperature=temperature))
+ @pytest.mark.parametrize("kernel_size", [(3, 3), (5, 5), (7, 7), (4, 6)])
+ def test_window_offset_in_pixels_5017(self, device, dtype, kernel_size):
+ # Every window that holds the one hot pixel puts all its softmax weight on it, so it reports that
+ # pixel, whatever the window size. The offset kernel used to span [-1, 1] instead of pixel offsets,
+ # which scaled the offset by 2 / (k - 1): a 5-wide window reported x = 7 for a peak at x = 8.
+ ky, kx = kernel_size
+ data = torch.zeros(1, 1, 15, 17, device=device, dtype=dtype)
+ data[..., 7, 8] = 50.0
+ coords = kornia.geometry.subpix.conv_soft_argmax2d(
+ data, kernel_size, (1, 1), (0, 0), normalized_coordinates=False
+ )
+ rows = torch.arange(coords.shape[-2], device=device)
+ cols = torch.arange(coords.shape[-1], device=device)
+ holds_peak = ((rows <= 7) & (rows > 7 - ky))[:, None] & ((cols <= 8) & (cols > 8 - kx))[None, :]
+ assert holds_peak.sum().item() == kx * ky
+ expected = torch.tensor([8.0, 7.0], device=device, dtype=dtype)[:, None].expand(2, kx * ky)
+ self.assert_close(coords[0, 0][:, holds_peak], expected, atol=1e-4, rtol=1e-4)
+
@pytest.mark.parametrize("temperature", [0.0, float("nan"), "tensor"])
@pytest.mark.parametrize(
"op, shape", [("conv_soft_argmax2d", (1, 1, 3, 3)), ("conv_soft_argmax3d", (1, 1, 3, 3, 3))]
@@ -513,6 +531,31 @@ class TestConvSoftArgmax3d(BaseTester):
for expected, actual in zip(op(data, temperature=temperature), op_opt(data, temperature=temperature)):
self.assert_close(expected, actual)
+ @pytest.mark.parametrize("kernel_size", [(3, 3, 3), (5, 5, 5), (5, 3, 4), (4, 4, 2)])
+ def test_window_offset_in_pixels_5017(self, device, dtype, kernel_size):
+ # 3-D counterpart of TestConvSoftArgmax2d::test_window_offset_in_pixels_5017: the depth offset used to
+ # come from linspace(-1, 1, d), so a 5-deep window reported depth 4 for a peak at depth 5.
+ if device.type == "cpu" and dtype in (torch.float16, torch.bfloat16):
+ pytest.skip("conv_soft_argmax3d has no CPU float16/bfloat16 kernel (avg_pool3d)")
+ kz, ky, kx = kernel_size
+ data = torch.zeros(1, 1, 11, 11, 13, device=device, dtype=dtype)
+ data[..., 5, 4, 6] = 50.0
+ coords = kornia.geometry.subpix.conv_soft_argmax3d(
+ data, kernel_size, (1, 1, 1), (0, 0, 0), normalized_coordinates=False, output_value=False
+ )
+ levels = torch.arange(coords.shape[-3], device=device)
+ rows = torch.arange(coords.shape[-2], device=device)
+ cols = torch.arange(coords.shape[-1], device=device)
+ holds_peak = (
+ ((levels <= 5) & (levels > 5 - kz))[:, None, None]
+ & ((rows <= 4) & (rows > 4 - ky))[None, :, None]
+ & ((cols <= 6) & (cols > 6 - kx))[None, None, :]
+ )
+ assert holds_peak.sum().item() == kx * ky * kz
+ # channels are (depth, x, y)
+ expected = torch.tensor([5.0, 6.0, 4.0], device=device, dtype=dtype)[:, None].expand(3, kx * ky * kz)
+ self.assert_close(coords[0, 0][:, holds_peak], expected, atol=1e-4, rtol=1e-4)
+
class TestConvQuadInterp3dModule(BaseTester):
def test_smoke(self, device, dtype):