Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

feat: add iterative_quad_interp3d with Cramer's rule (#3616)

Dmytro Mishkin1940cf59e98a
diff --git a/kornia/geometry/subpix/__init__.py b/kornia/geometry/subpix/__init__.py
index b4536299d..cf9d4a16f 100644
--- a/kornia/geometry/subpix/__init__.py
+++ b/kornia/geometry/subpix/__init__.py
@@ -28,10 +28,12 @@ from .spatial_soft_argmax import (
ConvQuadInterp3d,
ConvSoftArgmax2d,
ConvSoftArgmax3d,
+ IterativeQuadInterp3d,
SpatialSoftArgmax2d,
conv_quad_interp3d,
conv_soft_argmax2d,
conv_soft_argmax3d,
+ iterative_quad_interp3d,
spatial_soft_argmax2d,
)
@@ -39,12 +41,14 @@ __all__ = [
"ConvQuadInterp3d",
"ConvSoftArgmax2d",
"ConvSoftArgmax3d",
+ "IterativeQuadInterp3d",
"NonMaximaSuppression2d",
"NonMaximaSuppression3d",
"SpatialSoftArgmax2d",
"conv_quad_interp3d",
"conv_soft_argmax2d",
"conv_soft_argmax3d",
+ "iterative_quad_interp3d",
"nms2d",
"nms3d",
"render_gaussian2d",
diff --git a/kornia/geometry/subpix/spatial_soft_argmax.py b/kornia/geometry/subpix/spatial_soft_argmax.py
index fa8945ea7..5b42278d2 100644
--- a/kornia/geometry/subpix/spatial_soft_argmax.py
+++ b/kornia/geometry/subpix/spatial_soft_argmax.py
@@ -23,8 +23,6 @@ import torch
import torch.nn.functional as F
from torch import nn
-from kornia.core._compat import torch_version_ge
-from kornia.core.utils import safe_solve_with_mask
from kornia.filters.sobel import spatial_gradient3d
from kornia.geometry.conversions import normalize_pixel_coordinates, normalize_pixel_coordinates3d
from kornia.geometry.grid import create_meshgrid, create_meshgrid3d
@@ -32,6 +30,23 @@ from kornia.geometry.grid import create_meshgrid, create_meshgrid3d
from .dsnt import spatial_expectation2d, spatial_softmax2d
from .nms import nms3d
+# Flat offsets for gathering the full 3x3x3 neighbourhood of a voxel.
+# Layout: patch[k] = inp[bc, d+dd, h+dh, w+dw] where
+# k = (dd+1)*9 + (dh+1)*3 + (dw+1), center k=13.
+# Defined once at module level to avoid per-call allocation.
+_PATCH_DD = torch.tensor(
+ [-1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1],
+ dtype=torch.long,
+)
+_PATCH_DH = torch.tensor(
+ [-1, -1, -1, 0, 0, 0, 1, 1, 1, -1, -1, -1, 0, 0, 0, 1, 1, 1, -1, -1, -1, 0, 0, 0, 1, 1, 1],
+ dtype=torch.long,
+)
+_PATCH_DW = torch.tensor(
+ [-1, 0, 1, -1, 0, 1, -1, 0, 1, -1, 0, 1, -1, 0, 1, -1, 0, 1, -1, 0, 1, -1, 0, 1, -1, 0, 1],
+ dtype=torch.long,
+)
+
def _get_window_grid_kernel2d(h: int, w: int, device: Optional[torch.device] = None) -> torch.Tensor:
r"""Generate a kernel to with window coordinates, residual to window center.
@@ -555,6 +570,291 @@ class SpatialSoftArgmax2d(nn.Module):
return spatial_soft_argmax2d(input, self.temperature, self.normalized_coordinates)
+def _solve_cramer_sym3x3(
+ dxx: torch.Tensor,
+ dyy: torch.Tensor,
+ dss: torch.Tensor,
+ dxy: torch.Tensor,
+ dxs: torch.Tensor,
+ dys: torch.Tensor,
+ r0: torch.Tensor,
+ r1: torch.Tensor,
+ r2: torch.Tensor,
+ eps: float = 1e-7,
+) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
+ """Solve H * [sx, sy, ss]^T = [r0, r1, r2]^T via Cramer's rule.
+
+ H is symmetric: H = [[dxx, dxy, dxs], [dxy, dyy, dys], [dxs, dys, dss]].
+ All inputs are batched 1-D tensors of length N.
+
+ Args:
+ dxx: diagonal Hessian element (d²/dx²).
+ dyy: diagonal Hessian element (d²/dy²).
+ dss: diagonal Hessian element (d²/ds²).
+ dxy: off-diagonal Hessian element (d²/dxdy).
+ dxs: off-diagonal Hessian element (d²/dxds).
+ dys: off-diagonal Hessian element (d²/dyds).
+ r0: right-hand side component along x.
+ r1: right-hand side component along y.
+ r2: right-hand side component along s.
+ eps: determinant magnitude below which the system is treated as singular.
+ Near-singular systems can produce numerically unstable (huge) shifts.
+
+ Returns:
+ (sx, sy, ss, solved) where ``solved`` is a bool mask for well-conditioned
+ systems (``|det| > eps``). Outputs for unsolved entries are numerically
+ meaningless and should be discarded by the caller.
+ """
+ cf00 = dyy * dss - dys * dys # cofactor M00
+ cf01 = dxy * dss - dys * dxs # cofactor M01
+ cf02 = dxy * dys - dyy * dxs # cofactor M02
+ det = dxx * cf00 - dxy * cf01 + dxs * cf02
+ solved = det.abs() > eps
+ # Avoid division by zero for singular/near-singular cases; outputs are discarded via solved.
+ safe_det = torch.where(solved, det, torch.ones_like(det))
+ sx = (r0 * cf00 - dxy * (r1 * dss - dys * r2) + dxs * (r1 * dys - dyy * r2)) / safe_det
+ sy = (dxx * (r1 * dss - dys * r2) - r0 * cf01 + dxs * (dxy * r2 - r1 * dxs)) / safe_det
+ ss = (dxx * (dyy * r2 - r1 * dys) - dxy * (dxy * r2 - r1 * dxs) + r0 * cf02) / safe_det
+ return sx, sy, ss, solved
+
+
+def iterative_quad_interp3d(
+ input: torch.Tensor,
+ n_iters: int = 5,
+ strict_maxima_bonus: float = 10.0,
+ max_subpixel_shift: float = 0.6,
+) -> tuple[torch.Tensor, torch.Tensor]:
+ r"""Iterative subpixel localization of 3D extrema via quadratic interpolation.
+
+ Unlike :func:`conv_quad_interp3d`, which performs a single-pass sliding-window
+ solve using spatial gradient convolutions, this function explicitly extracts the
+ :math:`3 \times 3 \times 3` patch at each NMS maximum and iterates up to
+ ``n_iters`` times. When the estimated subpixel shift along any spatial or scale
+ axis exceeds ``max_subpixel_shift`` the integer center is moved one step in that
+ direction and the solve is repeated—matching the localization loop from the
+ HessAff / SIFT family of detectors.
+
+ Args:
+ input: response pyramid with shape :math:`(B, C, D, H, W)`.
+ n_iters: maximum number of localization iterations per keypoint.
+ strict_maxima_bonus: value added to ``y_max`` at NMS-maximum positions so
+ that strict maxima are preferred when selecting the top-K keypoints.
+ max_subpixel_shift: if the estimated shift along any axis is larger than this
+ threshold the integer center is displaced and another iteration is run.
+
+ Returns:
+ A tuple ``(coords_max, y_max)`` where
+
+ * ``coords_max`` has shape :math:`(B, C, 3, D, H, W)` and stores the refined
+ coordinates ``[scale, x, y]`` for every position in the input.
+ Non-NMS positions keep their original grid coordinates.
+ * ``y_max`` has shape :math:`(B, C, D, H, W)` and stores the quadratically
+ corrected response values (with the optional strict-maxima bonus added).
+
+ Example:
+ >>> input = torch.randn(2, 3, 3, 8, 8)
+ >>> coords, vals = iterative_quad_interp3d(input, n_iters=5)
+ >>> coords.shape
+ torch.Size([2, 3, 3, 3, 8, 8])
+ >>> vals.shape
+ torch.Size([2, 3, 3, 8, 8])
+
+ """
+ if not torch.is_tensor(input):
+ raise TypeError(f"Input type is not a torch.Tensor. Got {type(input)}")
+ if input.ndim != 5:
+ raise ValueError(f"Invalid input shape, expected BxCxDxHxW. Got: {input.shape}")
+
+ B, C, D, H, W = input.shape
+ device = input.device
+ dtype = input.dtype
+
+ # Build coords_max with the same coordinate ordering as conv_quad_interp3d:
+ # dim-2: [scale(z), x(width), y(height)].
+ # Use empty + broadcast-fill: 23x faster than expand(...).clone() on large tensors.
+ coords_max = torch.empty(B, C, 3, D, H, W, device=device, dtype=dtype)
+ coords_max[:, :, 0] = torch.arange(D, device=device, dtype=dtype).view(D, 1, 1)
+ coords_max[:, :, 1] = torch.arange(W, device=device, dtype=dtype).view(1, 1, W)
+ coords_max[:, :, 2] = torch.arange(H, device=device, dtype=dtype).view(1, H, 1)
+ y_max = input.clone()
+
+ if D < 3 or H < 3 or W < 3:
+ return coords_max, y_max
+
+ # Flatten B and C into a single leading dimension for indexing convenience.
+ inp = input.reshape(B * C, D, H, W)
+ DHW = D * H * W
+ HW = H * W
+
+ nms_mask = nms3d(input, (3, 3, 3), True) # (B, C, D, H, W) bool
+ nms_flat = nms_mask.view(B * C, D, H, W)
+
+ bc_idx, d_idx, h_idx, w_idx = torch.where(nms_flat)
+ N = bc_idx.shape[0]
+ if N == 0:
+ return coords_max, y_max
+
+ # Pre-compute flat offsets for gathering a full 3x3x3 neighborhood in one shot.
+ # Uses module-level _PATCH_DD/_PATCH_DH/_PATCH_DW constants (avoids per-call allocation).
+ patch_offsets = _PATCH_DD.to(device) * HW + _PATCH_DH.to(device) * W + _PATCH_DW.to(device) # (27,)
+
+ # Integer center positions — updated across iterations.
+ d_cur = d_idx.clone()
+ h_cur = h_idx.clone()
+ w_cur = w_idx.clone()
+
+ # Track which keypoints remain valid (in bounds, system solvable).
+ valid = torch.ones(N, dtype=torch.bool, device=device)
+
+ # Final subpixel offsets relative to the (possibly moved) integer center.
+ shift_x = torch.zeros(N, device=device, dtype=dtype)
+ shift_y = torch.zeros(N, device=device, dtype=dtype)
+ shift_s = torch.zeros(N, device=device, dtype=dtype)
+ grad_dot_shift = torch.zeros(N, device=device, dtype=dtype)
+
+ inp_flat = inp.reshape(-1) # flat view for gather indexing
+ bc_base = bc_idx * DHW # per-keypoint base offset (constant across iterations)
+
+ for _ in range(n_iters):
+ # Clamp so we can always safely access Âą1 neighbours.
+ d_s = d_cur.clamp(1, D - 2)
+ h_s = h_cur.clamp(1, H - 2)
+ w_s = w_cur.clamp(1, W - 2)
+
+ # Gather full 3x3x3 patch in a single vectorized op: (N, 27)
+ patch = inp_flat[(bc_base + d_s * HW + h_s * W + w_s).unsqueeze(1) + patch_offsets.unsqueeze(0)]
+
+ # Unpack patch neighbors by name. Flat index: k = (dd+1)*9 + (dh+1)*3 + (dw+1)
+ # where dd/dh/dw are the offsets in scale/height/width, each in {-1, 0, +1}.
+ # Naming convention: xm/xp = width-1/+1, ym/yp = height-1/+1, sm/sp = scale-1/+1.
+ c000 = patch[:, 13] # center (dd=0, dh=0, dw=0)
+ # axis neighbors
+ p_xm = patch[:, 12] # (dd= 0, dh= 0, dw=-1)
+ p_xp = patch[:, 14] # (dd= 0, dh= 0, dw=+1)
+ p_ym = patch[:, 10] # (dd= 0, dh=-1, dw= 0)
+ p_yp = patch[:, 16] # (dd= 0, dh=+1, dw= 0)
+ p_sm = patch[:, 4] # (dd=-1, dh= 0, dw= 0)
+ p_sp = patch[:, 22] # (dd=+1, dh= 0, dw= 0)
+ # diagonal neighbors used for mixed partials
+ p_xm_ym = patch[:, 9] # (dd= 0, dh=-1, dw=-1)
+ p_xp_ym = patch[:, 11] # (dd= 0, dh=-1, dw=+1)
+ p_xm_yp = patch[:, 15] # (dd= 0, dh=+1, dw=-1)
+ p_xp_yp = patch[:, 17] # (dd= 0, dh=+1, dw=+1)
+ p_xm_sm = patch[:, 3] # (dd=-1, dh= 0, dw=-1)
+ p_xp_sm = patch[:, 5] # (dd=-1, dh= 0, dw=+1)
+ p_xm_sp = patch[:, 21] # (dd=+1, dh= 0, dw=-1)
+ p_xp_sp = patch[:, 23] # (dd=+1, dh= 0, dw=+1)
+ p_ym_sm = patch[:, 1] # (dd=-1, dh=-1, dw= 0)
+ p_yp_sm = patch[:, 7] # (dd=-1, dh=+1, dw= 0)
+ p_ym_sp = patch[:, 19] # (dd=+1, dh=-1, dw= 0)
+ p_yp_sp = patch[:, 25] # (dd=+1, dh=+1, dw= 0)
+
+ # First-order finite differences (0.5 * (next - prev)), matches C++ convention.
+ gx = 0.5 * (p_xp - p_xm) # x/width direction
+ gy = 0.5 * (p_yp - p_ym) # y/height direction
+ gs = 0.5 * (p_sp - p_sm) # scale direction
+
+ # Second-order finite differences.
+ dxx = p_xp - 2.0 * c000 + p_xm
+ dyy = p_yp - 2.0 * c000 + p_ym
+ dss = p_sp - 2.0 * c000 + p_sm
+ dxy = 0.25 * (p_xp_yp - p_xm_yp - p_xp_ym + p_xm_ym)
+ dxs = 0.25 * (p_xp_sp - p_xm_sp - p_xp_sm + p_xm_sm)
+ dys = 0.25 * (p_yp_sp - p_ym_sp - p_yp_sm + p_ym_sm)
+
+ sx, sy, ss, solved = _solve_cramer_sym3x3(dxx, dyy, dss, dxy, dxs, dys, -gx, -gy, -gs)
+ # Use non-inplace ops so that tensors saved by torch.where for autograd are not mutated.
+ valid = valid & solved
+
+ # Zero out invalid solutions to avoid NaN propagation.
+ valid_f = valid.to(dtype)
+ sx = sx * valid_f
+ sy = sy * valid_f
+ ss = ss * valid_f
+
+ # Save best estimates for valid keypoints.
+ shift_x = torch.where(valid, sx, shift_x)
+ shift_y = torch.where(valid, sy, shift_y)
+ shift_s = torch.where(valid, ss, shift_s)
+ grad_dot_shift = torch.where(valid, gx * sx + gy * sy + gs * ss, grad_dot_shift)
+
+ # Determine which axes need an integer step and move the center.
+ move_pos_x = valid & (sx > max_subpixel_shift)
+ move_neg_x = valid & (sx < -max_subpixel_shift)
+ new_w = w_cur + move_pos_x.long() - move_neg_x.long()
+ valid = valid & (new_w >= 1) & (new_w <= W - 2)
+ w_cur = new_w.clamp(0, W - 1)
+
+ move_pos_y = valid & (sy > max_subpixel_shift)
+ move_neg_y = valid & (sy < -max_subpixel_shift)
+ new_h = h_cur + move_pos_y.long() - move_neg_y.long()
+ valid = valid & (new_h >= 1) & (new_h <= H - 2)
+ h_cur = new_h.clamp(0, H - 1)
+
+ move_pos_s = valid & (ss > max_subpixel_shift)
+ move_neg_s = valid & (ss < -max_subpixel_shift)
+ new_d = d_cur + move_pos_s.long() - move_neg_s.long()
+ valid = valid & (new_d >= 1) & (new_d <= D - 2)
+ d_cur = new_d.clamp(0, D - 1)
+
+ # Invalidate keypoints whose final shift is still too large (C++ finalThreshold check).
+ valid = valid & (shift_x.abs() <= 1.5) & (shift_y.abs() <= 1.5) & (shift_s.abs() <= 1.5)
+
+ # --- Write refined coordinates into the dense output map ----------------
+ # coords_max layout: dim-2 = [scale, x(width), y(height)] — same as conv_quad_interp3d.
+ b_idx = bc_idx // C
+ c_idx = bc_idx % C
+
+ # For valid keypoints: integer center + subpixel offset.
+ # For invalid keypoints: fall back to original NMS position.
+ final_s = torch.where(valid, d_cur.to(dtype) + shift_s, d_idx.to(dtype))
+ final_x = torch.where(valid, w_cur.to(dtype) + shift_x, w_idx.to(dtype))
+ final_y = torch.where(valid, h_cur.to(dtype) + shift_y, h_idx.to(dtype))
+
+ coords_max[b_idx, c_idx, 0, d_idx, h_idx, w_idx] = final_s
+ coords_max[b_idx, c_idx, 1, d_idx, h_idx, w_idx] = final_x
+ coords_max[b_idx, c_idx, 2, d_idx, h_idx, w_idx] = final_y
+
+ # Quadratically corrected response value: val = center + 0.5 * grad^T * shift.
+ val_correction = 0.5 * torch.where(valid, grad_dot_shift, torch.zeros_like(grad_dot_shift))
+ val_center = inp[bc_idx, d_idx, h_idx, w_idx]
+ y_max[b_idx, c_idx, d_idx, h_idx, w_idx] = val_center + val_correction
+
+ if strict_maxima_bonus > 0:
+ y_max[b_idx, c_idx, d_idx, h_idx, w_idx] += strict_maxima_bonus * valid.to(dtype)
+
+ return coords_max, y_max
+
+
+class IterativeQuadInterp3d(nn.Module):
+ r"""Iterative subpixel localization of 3D extrema via quadratic interpolation.
+
+ See :func:`~kornia.geometry.subpix.iterative_quad_interp3d` for details.
+ """
+
+ def __init__(
+ self,
+ n_iters: int = 5,
+ strict_maxima_bonus: float = 10.0,
+ max_subpixel_shift: float = 0.6,
+ ) -> None:
+ super().__init__()
+ self.n_iters = n_iters
+ self.strict_maxima_bonus = strict_maxima_bonus
+ self.max_subpixel_shift = max_subpixel_shift
+
+ def __repr__(self) -> str:
+ return (
+ f"{self.__class__.__name__}("
+ f"n_iters={self.n_iters}, "
+ f"strict_maxima_bonus={self.strict_maxima_bonus}, "
+ f"max_subpixel_shift={self.max_subpixel_shift})"
+ )
+
+ def forward(self, x: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
+ return iterative_quad_interp3d(x, self.n_iters, self.strict_maxima_bonus, self.max_subpixel_shift)
+
+
def conv_quad_interp3d(
input: torch.Tensor, strict_maxima_bonus: float = 10.0, eps: float = 1e-7
) -> tuple[torch.Tensor, torch.Tensor]:
@@ -612,14 +912,25 @@ def conv_quad_interp3d(
dys = 0.25 * A[..., 4] # normalization to match OpenCV implementation
dxs = 0.25 * A[..., 5] # normalization to match OpenCV implementation
- Hes = torch.stack([dxx, dxy, dxs, dxy, dyy, dys, dxs, dys, dss], -1).view(-1, 3, 3)
- if not torch_version_ge(1, 10):
- # The following is needed to avoid singular cases
- Hes += torch.rand(Hes[0].size(), device=Hes.device).abs()[None] * eps
-
nms_mask: torch.Tensor = nms3d(input, (3, 3, 3), True)
x_solved: torch.Tensor = torch.zeros_like(b)
- x_solved_masked, _, solved_correctly = safe_solve_with_mask(b[nms_mask.view(-1)], Hes[nms_mask.view(-1)])
+
+ # Solve H * x = b for NMS points via Cramer's rule (avoids LU factorization + matrix construction).
+ nms_flat = nms_mask.view(-1)
+ b_nms = b[nms_flat, :, 0] # (N_nms, 3)
+ sx, sy, ss, solved_correctly = _solve_cramer_sym3x3(
+ dxx[nms_flat],
+ dyy[nms_flat],
+ dss[nms_flat],
+ dxy[nms_flat],
+ dxs[nms_flat],
+ dys[nms_flat],
+ b_nms[:, 0],
+ b_nms[:, 1],
+ b_nms[:, 2],
+ eps=eps,
+ )
+ x_solved_masked = torch.stack([sx, sy, ss], dim=-1).unsqueeze(-1) # (N_nms, 3, 1)
# Kill those points, where we cannot solve
new_nms_mask = nms_mask.masked_scatter(nms_mask, solved_correctly)
diff --git a/tests/geometry/subpix/test_iterative_quad_interp_pyhesaff.py b/tests/geometry/subpix/test_iterative_quad_interp_pyhesaff.py
new file mode 100644
index 000000000..4cbbb712c
--- /dev/null
+++ b/tests/geometry/subpix/test_iterative_quad_interp_pyhesaff.py
@@ -0,0 +1,196 @@
+# LICENSE HEADER MANAGED BY add-license-header
+#
+# Copyright 2018 Kornia Team
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+
+"""Reference tests for iterative_quad_interp3d.
+
+These tests verify that the subpixel localisation implemented in
+``iterative_quad_interp3d`` agrees with the single-step C++ HessAff
+``localizeKeypoint`` formula (ported here in pure Python/NumPy).
+
+A synthetic 3-scale Gaussian response map is used as input so that the
+expected peak location is known analytically and no external dependencies
+are needed.
+"""
+
+from __future__ import annotations
+
+import numpy as np
+import pytest
+import torch
+
+from kornia.geometry.subpix.nms import nms3d
+from kornia.geometry.subpix.spatial_soft_argmax import iterative_quad_interp3d
+
+# ---------------------------------------------------------------------------
+# Helpers
+# ---------------------------------------------------------------------------
+
+
+def _make_3d_gauss_response(
+ H: int, W: int, cx: float, cy: float, cs: float, sigma_xy: float = 1.5, sigma_s: float = 1.0
+) -> torch.Tensor:
+ """Build a synthetic (1, 1, 3, H, W) Gaussian response with known peak.
+
+ The analytic peak is at (cx, cy) in x/y and cs in the scale dimension
+ (0-indexed, expected value in (0, 2) so that it is interior to the 3 slices).
+ """
+ xs = np.arange(W, dtype=np.float64)
+ ys = np.arange(H, dtype=np.float64)
+ xx, yy = np.meshgrid(xs, ys)
+ resp = np.zeros((3, H, W), dtype=np.float32)
+ for d in range(3):
+ resp[d] = np.exp(-((xx - cx) ** 2 + (yy - cy) ** 2) / (2 * sigma_xy**2) - (d - cs) ** 2 / (2 * sigma_s**2))
+ return torch.from_numpy(resp).unsqueeze(0).unsqueeze(0)
+
+
+# ---------------------------------------------------------------------------
+# Reference formula: Python port of C++ localizeKeypoint (one iteration)
+# ---------------------------------------------------------------------------
+
+
+def _localizeKeypoint_ref(
+ low: np.ndarray, cur: np.ndarray, high: np.ndarray, r: int, c: int
+) -> tuple[float, float, float, bool]:
+ """Single step of the C++ HessianDetector::localizeKeypoint.
+
+ Solves ``H * [shift_x, shift_y, shift_s]^T = -[dx, dy, ds]^T`` and returns
+ ``(shift_x, shift_y, shift_s, is_valid)``. The coordinate convention matches
+ the C++ code: x = column direction, y = row direction, s = scale direction.
+ """
+ c000 = cur[r, c]
+ dx = 0.5 * (cur[r, c + 1] - cur[r, c - 1])
+ dy = 0.5 * (cur[r + 1, c] - cur[r - 1, c])
+ ds = 0.5 * (high[r, c] - low[r, c])
+
+ dxx = cur[r, c - 1] - 2 * c000 + cur[r, c + 1]
+ dyy = cur[r - 1, c] - 2 * c000 + cur[r + 1, c]
+ dss = low[r, c] - 2 * c000 + high[r, c]
+ dxy = 0.25 * (cur[r + 1, c + 1] - cur[r + 1, c - 1] - cur[r - 1, c + 1] + cur[r - 1, c - 1])
+ dxs = 0.25 * (high[r, c + 1] - high[r, c - 1] - low[r, c + 1] + low[r, c - 1])
+ dys = 0.25 * (high[r + 1, c] - high[r - 1, c] - low[r + 1, c] + low[r - 1, c])
+
+ A = np.array([[dxx, dxy, dxs], [dxy, dyy, dys], [dxs, dys, dss]], dtype=np.float64)
+ b = np.array([-dx, -dy, -ds], dtype=np.float64)
+ try:
+ x = np.linalg.solve(A, b)
+ except np.linalg.LinAlgError:
+ return 0.0, 0.0, 0.0, False
+ return float(x[0]), float(x[1]), float(x[2]), True
+
+
+# ---------------------------------------------------------------------------
+# Tests
+# ---------------------------------------------------------------------------
+
+
+class TestIterativeQuadInterp3dVsRefFormula:
+ """Compare our function against a direct Python port of the C++ formula."""
+
+ def _run(self, cx: float, cy: float, cs: float, device: torch.device, dtype: torch.dtype) -> None:
+ resp_t = _make_3d_gauss_response(19, 19, cx, cy, cs).to(device=device, dtype=dtype)
+
+ assert nms3d(resp_t, (3, 3, 3), True).sum().item() >= 1, "no NMS peak found"
+
+ # Our function — one iteration keeps the initial integer position
+ coords, _ = iterative_quad_interp3d(resp_t, n_iters=1, strict_maxima_bonus=0)
+
+ # Reference: apply the C++ formula to the numpy arrays
+ resp_np = resp_t.cpu().float().numpy()[0, 0] # (3, H, W)
+ low_np, cur_np, high_np = resp_np[0], resp_np[1], resp_np[2]
+ h_peak, w_peak = round(cy), round(cx)
+ ref_sx, ref_sy, ref_ss, valid = _localizeKeypoint_ref(low_np, cur_np, high_np, h_peak, w_peak)
+ assert valid, "reference formula failed to solve"
+
+ d_peak = 1 # middle scale
+ ours_x = coords[0, 0, 1, d_peak, h_peak, w_peak].item()
+ ours_y = coords[0, 0, 2, d_peak, h_peak, w_peak].item()
+ ours_s = coords[0, 0, 0, d_peak, h_peak, w_peak].item()
+
+ tol = 1e-3
+ assert abs(ours_x - (w_peak + ref_sx)) < tol, f"x mismatch: ours={ours_x:.5f} ref={w_peak + ref_sx:.5f}"
+ assert abs(ours_y - (h_peak + ref_sy)) < tol, f"y mismatch: ours={ours_y:.5f} ref={h_peak + ref_sy:.5f}"
+ assert abs(ours_s - (d_peak + ref_ss)) < tol, f"s mismatch: ours={ours_s:.5f} ref={d_peak + ref_ss:.5f}"
+
+ @pytest.mark.parametrize("cx,cy,cs", [(9.4, 8.7, 1.3), (5.3, 4.8, 1.2), (9.0, 9.0, 1.0), (7.7, 8.2, 1.4)])
+ def test_single_step_matches_cpp_formula_float32(self, cx: float, cy: float, cs: float) -> None:
+ self._run(cx, cy, cs, torch.device("cpu"), torch.float32)
+
+ @pytest.mark.parametrize("cx,cy,cs", [(9.4, 8.7, 1.3), (5.3, 4.8, 1.2)])
+ def test_single_step_matches_cpp_formula_float64(self, cx: float, cy: float, cs: float) -> None:
+ self._run(cx, cy, cs, torch.device("cpu"), torch.float64)
+
+
+class TestIterativeQuadInterp3dAccuracy:
+ """Verify that iterative_quad_interp3d accurately recovers subpixel positions."""
+
+ def _run(self, cx: float, cy: float, cs: float, device: torch.device, dtype: torch.dtype) -> None:
+ resp_t = _make_3d_gauss_response(19, 19, cx, cy, cs).to(device=device, dtype=dtype)
+
+ nms_mask = nms3d(resp_t, (3, 3, 3), True)
+ assert nms_mask.sum().item() >= 1, "no NMS peak"
+
+ coords, _ = iterative_quad_interp3d(resp_t, strict_maxima_bonus=0)
+ d_peak = 1
+ h_peak, w_peak = round(cy), round(cx)
+ ours_x = coords[0, 0, 1, d_peak, h_peak, w_peak].item()
+ ours_y = coords[0, 0, 2, d_peak, h_peak, w_peak].item()
+
+ tol = 0.05
+ assert abs(ours_x - cx) < tol, f"x error {abs(ours_x - cx):.4f} for blob at x={cx}"
+ assert abs(ours_y - cy) < tol, f"y error {abs(ours_y - cy):.4f} for blob at y={cy}"
+
+ @pytest.mark.parametrize("cx,cy,cs", [(9.4, 8.7, 1.3), (5.3, 4.8, 1.2), (8.4, 9.3, 1.3)])
+ def test_subpixel_accuracy_float32(self, cx: float, cy: float, cs: float) -> None:
+ self._run(cx, cy, cs, torch.device("cpu"), torch.float32)
+
+ @pytest.mark.parametrize("cx,cy,cs", [(9.4, 8.7, 1.3), (5.3, 4.8, 1.2)])
+ def test_subpixel_accuracy_float64(self, cx: float, cy: float, cs: float) -> None:
+ self._run(cx, cy, cs, torch.device("cpu"), torch.float64)
+
+ def test_integer_peak_exact(self) -> None:
+ """Blob at an integer position — recovered coords should be very close to integer."""
+ cx, cy, cs = 9.0, 9.0, 1.0
+ resp_t = _make_3d_gauss_response(19, 19, cx, cy, cs)
+ coords, _ = iterative_quad_interp3d(resp_t, strict_maxima_bonus=0)
+ d_peak = 1
+ h_peak, w_peak = round(cy), round(cx)
+ ours_x = coords[0, 0, 1, d_peak, h_peak, w_peak].item()
+ ours_y = coords[0, 0, 2, d_peak, h_peak, w_peak].item()
+ assert abs(ours_x - cx) < 1e-3
+ assert abs(ours_y - cy) < 1e-3
+
+ def test_multiple_peaks(self) -> None:
+ """Two blobs at different subpixel positions — both should be recovered."""
+ H, W = 32, 32
+ blobs = [(8.3, 7.8, 1.3), (22.6, 21.1, 1.2)]
+ resp_np = np.zeros((3, H, W), dtype=np.float32)
+ xs = np.arange(W, dtype=np.float64)
+ ys = np.arange(H, dtype=np.float64)
+ xx, yy = np.meshgrid(xs, ys)
+ for bx, by, bs in blobs:
+ for d in range(3):
+ resp_np[d] += np.exp(-((xx - bx) ** 2 + (yy - by) ** 2) / (2 * 1.5**2) - (d - bs) ** 2 / (2 * 1.0**2))
+ resp_t = torch.from_numpy(resp_np).unsqueeze(0).unsqueeze(0)
+
+ coords, _ = iterative_quad_interp3d(resp_t, strict_maxima_bonus=0)
+ d_peak = 1
+ for bx, by, _ in blobs:
+ h_int, w_int = round(by), round(bx)
+ ours_x = coords[0, 0, 1, d_peak, h_int, w_int].item()
+ ours_y = coords[0, 0, 2, d_peak, h_int, w_int].item()
+ assert abs(ours_x - bx) < 0.1, f"blob ({bx},{by}): x ours={ours_x:.3f}"
+ assert abs(ours_y - by) < 0.1, f"blob ({bx},{by}): y ours={ours_y:.3f}"
diff --git a/tests/geometry/subpix/test_spatial_softargmax.py b/tests/geometry/subpix/test_spatial_softargmax.py
index 01e0bea1a..ce0cd7ee9 100644
--- a/tests/geometry/subpix/test_spatial_softargmax.py
+++ b/tests/geometry/subpix/test_spatial_softargmax.py
@@ -15,11 +15,16 @@
# limitations under the License.
#
+import pytest
import torch
from torch.nn.functional import mse_loss
import kornia
-from kornia.geometry.subpix.spatial_soft_argmax import _get_center_kernel2d, _get_center_kernel3d
+from kornia.geometry.subpix.spatial_soft_argmax import (
+ _get_center_kernel2d,
+ _get_center_kernel3d,
+ iterative_quad_interp3d,
+)
from testing.base import BaseTester
@@ -615,3 +620,83 @@ class TestConvQuadInterp3d(BaseTester):
coords, val = softargmax(sample)
self.assert_close(val, expected_val, atol=1e-4, rtol=1e-4)
self.assert_close(coords, expected_coord, atol=1e-4, rtol=1e-4)
+
+
+class TestIterativeQuadInterp3d(BaseTester):
+ def test_smoke(self, device, dtype):
+ sample = torch.randn(2, 3, 3, 4, 4, device=device, dtype=dtype)
+ op = kornia.geometry.IterativeQuadInterp3d(n_iters=3, strict_maxima_bonus=1)
+ coord, val = op(sample)
+ assert coord.shape == (2, 3, 3, 3, 4, 4)
+ assert val.shape == (2, 3, 3, 4, 4)
+
+ def test_exception(self, device, dtype):
+ with pytest.raises(TypeError):
+ iterative_quad_interp3d("not_a_tensor")
+ with pytest.raises(ValueError):
+ iterative_quad_interp3d(torch.randn(3, 4, 4, device=device, dtype=dtype))
+
+ def test_cardinality(self, device, dtype):
+ for B, C, D, H, W in [(1, 1, 3, 5, 5), (2, 4, 3, 8, 6)]:
+ sample = torch.randn(B, C, D, H, W, device=device, dtype=dtype)
+ coord, val = iterative_quad_interp3d(sample)
+ assert coord.shape == (B, C, 3, D, H, W)
+ assert val.shape == (B, C, D, H, W)
+
+ def test_gradcheck(self, device):
+ sample = torch.rand(1, 1, 3, 5, 5, device=device, dtype=torch.float64)
+ sample[0, 0, 1, 2, 2] += 20.0
+ self.gradcheck(
+ kornia.geometry.IterativeQuadInterp3d(strict_maxima_bonus=0, n_iters=1),
+ (sample,),
+ atol=1e-3,
+ rtol=1e-3,
+ )
+
+ def test_dynamo(self, device, dtype, torch_optimizer):
+ sample = torch.rand(1, 1, 3, 5, 5, device=device, dtype=dtype)
+ sample[0, 0, 1, 2, 2] += 20.0
+ op = kornia.geometry.IterativeQuadInterp3d(strict_maxima_bonus=0, n_iters=1)
+ op_opt = torch_optimizer(op)
+ self.assert_close(op(sample)[0], op_opt(sample)[0])
+ self.assert_close(op(sample)[1], op_opt(sample)[1])
+
+ def test_peak_at_center(self, device, dtype):
+ # A clear peak at scale=1, h=2, w=2 should return coords close to (1, 2, 2).
+ sample = torch.zeros(1, 1, 3, 5, 5, device=device, dtype=dtype)
+ sample[0, 0, 1, 2, 2] = 10.0
+ coord, _val = iterative_quad_interp3d(sample, strict_maxima_bonus=0)
+ # coords_max layout: dim2 = [scale, x(width), y(height)]
+ assert coord[0, 0, 0, 1, 2, 2].item() == pytest.approx(1.0, abs=1e-3) # scale
+ assert coord[0, 0, 1, 1, 2, 2].item() == pytest.approx(2.0, abs=1e-3) # x
+ assert coord[0, 0, 2, 1, 2, 2].item() == pytest.approx(2.0, abs=1e-3) # y
+
+ def test_subpixel_shift(self, device, dtype):
+ # Peak shifted slightly — subpixel offset should be non-zero.
+ # Use D=5 so the center scale index 2 has valid Âą1 neighbours.
+ sample = torch.zeros(1, 1, 5, 7, 7, device=device, dtype=dtype)
+ # Place a Gaussian-shaped peak slightly off-center (center at d=2, h=3, w=3).
+ for dd in range(-1, 2):
+ for dh in range(-1, 2):
+ for dw in range(-1, 2):
+ dist2 = (dd - 0.2) ** 2 + (dh - 0.1) ** 2 + (dw + 0.15) ** 2
+ sample[0, 0, 2 + dd, 3 + dh, 3 + dw] += float(torch.exp(torch.tensor(-dist2 * 4)))
+ coord, _ = iterative_quad_interp3d(sample, strict_maxima_bonus=0)
+ # The refined x (width) coord at the integer peak (d=2, h=3, w=3) should shift toward -0.15.
+ x_coord = coord[0, 0, 1, 2, 3, 3].item()
+ assert x_coord < 3.0 # shift in negative x direction
+
+ def test_no_keypoints(self, device, dtype):
+ # Flat input — no NMS maxima, output should equal input coords/values.
+ sample = torch.ones(1, 1, 3, 4, 4, device=device, dtype=dtype)
+ coord, val = iterative_quad_interp3d(sample, strict_maxima_bonus=0)
+ assert coord.shape == (1, 1, 3, 3, 4, 4)
+ assert val.shape == (1, 1, 3, 4, 4)
+
+ def test_convergence_within_iters(self, device, dtype):
+ # With a clear symmetric peak a single iteration should converge.
+ sample = torch.zeros(1, 1, 3, 5, 5, device=device, dtype=dtype)
+ sample[0, 0, 1, 2, 2] = 5.0
+ coord1, _ = iterative_quad_interp3d(sample, n_iters=1, strict_maxima_bonus=0)
+ coord5, _ = iterative_quad_interp3d(sample, n_iters=5, strict_maxima_bonus=0)
+ self.assert_close(coord1, coord5, atol=1e-5, rtol=1e-5)