π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
feat: add ALIKED local feature detector and descriptor (#3617)
Dmytro Mishkin42e4f78c38ec
diff --git a/kornia/feature/__init__.py b/kornia/feature/__init__.pyindex 1d334191d..48ac6e7a0 100644--- a/kornia/feature/__init__.py+++ b/kornia/feature/__init__.py@@ -21,6 +21,7 @@ This subpackage provides modules for keypoint detection, descriptors, and featur"""from .affine_shape import LAFAffineShapeEstimator, LAFAffNetShapeEstimator, PatchAffineShapeEstimator+from .aliked import ALIKED, ALIKEDFeaturesfrom .dedode import DeDoDefrom .defmo import DeFMOfrom .disk import DISK, DISKFeatures@@ -95,10 +96,12 @@ from .sosnet import SOSNetfrom .tfeat import TFeat__all__ = [+ "ALIKED","DISK","KORNIA_CHECK_LAF","SOLD2","TLU",+ "ALIKEDFeatures","BlobDoG","BlobDoGSingle","BlobHessian",diff --git a/kornia/feature/aliked/__init__.py b/kornia/feature/aliked/__init__.pynew file mode 100644index 000000000..f28636b31--- /dev/null+++ b/kornia/feature/aliked/__init__.py@@ -0,0 +1,21 @@+# 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.+#++"""Kornia Feature ALIKED β ALIKED local feature detector and descriptor."""++from .aliked import ALIKED, ALIKEDFeatures+from .deform_conv2d import deform_conv2ddiff --git a/kornia/feature/aliked/aliked.py b/kornia/feature/aliked/aliked.pynew file mode 100644index 000000000..310af37b9--- /dev/null+++ b/kornia/feature/aliked/aliked.py@@ -0,0 +1,980 @@+# 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.+#++# Adapted from the ALIKED implementation in LightGlue+# (https://github.com/cvg/LightGlue/blob/main/lightglue/aliked.py)+# which itself is based on the original ALIKED code by Zhao Xiaoming et al.:+# https://github.com/Shiaoming/ALIKED+#+# BSD 3-Clause License+#+# Copyright (c) 2022, Zhao Xiaoming+# All rights reserved.+#+# Redistribution and use in source and binary forms, with or without+# modification, are permitted provided that the following conditions are met:+#+# 1. Redistributions of source code must retain the above copyright notice,+# this list of conditions and the following disclaimer.+# 2. Redistributions in binary form must reproduce the above copyright notice,+# this list of conditions and the following disclaimer in the documentation+# and/or other materials provided with the distribution.+# 3. Neither the name of the copyright holder nor the names of its contributors+# may be used to endorse or promote products derived from this software+# without specific prior written permission.+#+# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"+# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE+# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE+# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE+# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR+# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF+# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS+# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN+# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)+# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE+# POSSIBILITY OF SUCH DAMAGE.+#+# Authors:+# Xiaoming Zhao, Xingming Wu, Weihai Chen, Peter C.Y. Chen, Qingsong Xu, and+# Zhengguo Li++from __future__ import annotations++from dataclasses import dataclass+from typing import Any, Callable, Optional, Tuple++import torch+import torch.nn.functional as F+from torch import nn+from torch.nn.modules.utils import _pair++from kornia.color import grayscale_to_rgb+from kornia.geometry.subpix import nms2d++from .deform_conv2d import deform_conv2d++# ---------------------------------------------------------------------------+# Output data structure+# ---------------------------------------------------------------------------+++@dataclass+class ALIKEDFeatures:+ r"""Keypoints, descriptors and scores detected by ALIKED for a single image.++ Since ALIKED detects a varying number of keypoints per image,+ ``ALIKEDFeatures`` is not batched.++ Args:+ keypoints: pixel coordinates ``(N, 2)`` as ``[x, y]``.+ descriptors: L2-normalised descriptors ``(N, D)``.+ keypoint_scores: detection confidence scores ``(N,)``.+ """++ keypoints: torch.Tensor+ descriptors: torch.Tensor+ keypoint_scores: torch.Tensor++ @property+ def n(self) -> int:+ """Number of detected keypoints."""+ return self.keypoints.shape[0]++ def to(self, *args: Any, **kwargs: Any) -> ALIKEDFeatures:+ """Move all tensors to a new device / dtype."""+ return ALIKEDFeatures(+ self.keypoints.to(*args, **kwargs),+ self.descriptors.to(*args, **kwargs),+ self.keypoint_scores.to(*args, **kwargs),+ )+++# ---------------------------------------------------------------------------+# Helpers+# ---------------------------------------------------------------------------+++def _conv1x1(in_planes: int, out_planes: int, stride: int = 1) -> nn.Conv2d:+ return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False)+++def _conv3x3(in_planes: int, out_planes: int, stride: int = 1, groups: int = 1, dilation: int = 1) -> nn.Conv2d:+ return nn.Conv2d(+ in_planes,+ out_planes,+ kernel_size=3,+ stride=stride,+ padding=dilation,+ groups=groups,+ bias=False,+ dilation=dilation,+ )+++def get_patches(tensor: torch.Tensor, required_corners: torch.Tensor, ps: int) -> torch.Tensor:+ """Extract ps x ps patches centred at required_corners from a CHW tensor."""+ c, h, w = tensor.shape+ corner = (required_corners - ps / 2 + 1).long()+ corner[:, 0] = corner[:, 0].clamp(min=0, max=w - 1 - ps)+ corner[:, 1] = corner[:, 1].clamp(min=0, max=h - 1 - ps)+ offset = torch.arange(0, ps)+ x, y = torch.meshgrid(offset, offset, indexing="ij")+ patches = torch.stack((x, y)).permute(2, 1, 0).unsqueeze(2)+ patches = patches.to(corner) + corner[None, None]+ pts = patches.reshape(-1, 2)+ sampled = tensor.permute(1, 2, 0)[tuple(pts.T)[::-1]]+ sampled = sampled.reshape(ps, ps, -1, c)+ return sampled.permute(2, 3, 0, 1)+++# ---------------------------------------------------------------------------+# LAF helpers+# ---------------------------------------------------------------------------+++def _affine_from_cov(cov: torch.Tensor) -> torch.Tensor:+ """Build a 2x2 affine matrix from a batch of 2x2 covariance matrices.++ The affine is ``U @ diag(sqrt(eigenvalues))``, where ``U`` contains the+ orthonormal eigenvectors of ``cov`` as *columns*. This gives an ellipse+ whose axes align with the principal directions of the covariance.++ Args:+ cov: symmetric positive-semi-definite matrices ``(N, 2, 2)``.++ Returns:+ Affine matrices ``(N, 2, 2)``.+ """+ # eigh returns eigenvalues sorted ascending; columns of eigenvectors are evecs.+ eigenvalues, eigenvectors = torch.linalg.eigh(cov)+ scales = eigenvalues.clamp(min=1e-8).sqrt() # (N, 2)+ # Each column of eigenvectors multiplied by the corresponding scale.+ return eigenvectors * scales[:, None, :] # (N, 2, 2)+++def _laf_from_kpts_and_affine(+ keypoints_px: torch.Tensor,+ affine: torch.Tensor,+) -> torch.Tensor:+ """Assemble a ``(N, 2, 3)`` LAF from pixel keypoints and 2x2 affine matrices.++ Args:+ keypoints_px: ``(N, 2)`` pixel coordinates ``[x, y]``.+ affine: ``(N, 2, 2)`` affine (rotation+scale) part of the LAF.++ Returns:+ LAF tensor ``(N, 2, 3)`` following the kornia convention+ ``[[a, b, cx], [c, d, cy]]``.+ """+ centers = keypoints_px.unsqueeze(-1) # (N, 2, 1)+ return torch.cat([affine, centers], dim=-1) # (N, 2, 3)+++# ---------------------------------------------------------------------------+# Differentiable Keypoint Detection (DKD)+# ---------------------------------------------------------------------------+++class DKD(nn.Module):+ """Differentiable keypoint detection from a score map.++ Args:+ radius: soft detection radius; NMS kernel size is ``2 * radius + 1``.+ top_k: if ``> 0`` return exactly the ``top_k`` highest-scoring+ keypoints; otherwise threshold mode is used.+ scores_th: score threshold when ``top_k <= 0``.+ If ``> 0`` keep keypoints with ``score > scores_th``;+ otherwise keep keypoints above the per-image mean score.+ n_limit: maximum number of keypoints returned in threshold mode.+ """++ def __init__(+ self,+ radius: int = 2,+ top_k: int = 0,+ scores_th: float = 0.2,+ n_limit: int = 20000,+ ) -> None:+ super().__init__()+ self.radius = radius+ self.top_k = top_k+ self.scores_th = scores_th+ self.n_limit = n_limit+ self.kernel_size = 2 * self.radius + 1+ self.temperature = 0.1+ self.unfold = nn.Unfold(kernel_size=self.kernel_size, padding=self.radius)+ x = torch.linspace(-self.radius, self.radius, self.kernel_size)+ hw_grid = torch.stack(torch.meshgrid([x, x], indexing="ij")).view(2, -1).t()[:, [1, 0]]+ self.register_buffer("hw_grid", hw_grid)++ def forward(+ self,+ scores_map: torch.Tensor,+ sub_pixel: bool = True,+ image_size: Optional[torch.Tensor] = None,+ return_affine: bool = False,+ ) -> tuple[list[torch.Tensor], ...]:+ """Detect keypoints from a score map.++ Args:+ scores_map: ``(B, 1, H, W)`` detection score map.+ sub_pixel: whether to apply soft-argmax sub-pixel refinement.+ image_size: optional ``(B, 2)`` tensor of valid image sizes ``(W, H)``+ for border masking.+ return_affine: if ``True``, also return per-keypoint 2x2 local affine+ matrices estimated from the soft-argmax weight covariance.++ Returns:+ A 3-tuple ``(keypoints, keypoint_scores, score_dispersities)`` β or a+ 4-tuple ``(..., local_affines)`` when ``return_affine=True``.+ Each ``keypoints[i]`` is ``(N_i, 2)`` normalised to ``[-1, 1]``.+ Each ``local_affines[i]`` is ``(N_i, 2, 2)`` (only when ``sub_pixel=True``+ and ``return_affine=True``; otherwise identity matrices are returned).+ """+ b, _c, h, w = scores_map.shape+ scores_nograd = scores_map.detach()+ nms_scores = nms2d(scores_nograd, (self.kernel_size, self.kernel_size))++ # remove border+ nms_scores[:, :, : self.radius, :] = 0+ nms_scores[:, :, :, : self.radius] = 0+ if image_size is not None:+ for i in range(b):+ iw, ih = image_size[i].long()+ nms_scores[i, :, ih.item() - self.radius :, :] = 0+ nms_scores[i, :, :, iw.item() - self.radius :] = 0+ else:+ nms_scores[:, :, -self.radius :, :] = 0+ nms_scores[:, :, :, -self.radius :] = 0++ if self.top_k > 0:+ topk = torch.topk(nms_scores.view(b, -1), self.top_k)+ indices_keypoints = [topk.indices[i] for i in range(b)]+ else:+ if self.scores_th > 0:+ masks = nms_scores > self.scores_th+ if masks.sum() == 0:+ th = scores_nograd.reshape(b, -1).mean(dim=1)+ masks = nms_scores > th.reshape(b, 1, 1, 1)+ else:+ th = scores_nograd.reshape(b, -1).mean(dim=1)+ masks = nms_scores > th.reshape(b, 1, 1, 1)+ masks = masks.reshape(b, -1)++ indices_keypoints = []+ scores_view = scores_nograd.reshape(b, -1)+ for mask, scores in zip(masks, scores_view):+ indices = mask.nonzero()[:, 0]+ if len(indices) > self.n_limit:+ kpts_sc = scores[indices]+ sort_idx = kpts_sc.sort(descending=True)[1]+ indices = indices[sort_idx[: self.n_limit]]+ indices_keypoints.append(indices)++ wh = torch.tensor([w - 1, h - 1], device=scores_nograd.device, dtype=scores_nograd.dtype)++ keypoints = []+ scoredispersitys = []+ kptscores = []+ local_affines: list[torch.Tensor] = []+ if sub_pixel:+ patches = self.unfold(scores_map) # B x (kernel**2) x (H*W)+ for b_idx in range(b):+ patch = patches[b_idx].t() # (H*W) x (kernel**2)+ indices_kpt = indices_keypoints[b_idx]+ patch_scores = patch[indices_kpt] # M x (kernel**2)+ keypoints_xy_nms = torch.stack(+ [indices_kpt % w, torch.div(indices_kpt, w, rounding_mode="trunc")],+ dim=1,+ )++ max_v = patch_scores.max(dim=1).values.detach()[:, None]+ x_exp = ((patch_scores - max_v) / self.temperature).exp()+ x_sum = x_exp.sum(dim=1, keepdim=True)++ xy_residual = x_exp @ self.hw_grid / x_sum # type: ignore[operator]++ hw_grid_dist2 = (+ torch.norm(+ (self.hw_grid[None, :, :] - xy_residual[:, None, :]) / self.radius, # type: ignore[index]+ dim=-1,+ )+ ** 2+ )+ scoredispersity = (x_exp * hw_grid_dist2).sum(dim=1) / x_exp.sum(dim=1)++ keypoints_xy = keypoints_xy_nms + xy_residual+ keypoints_xy = keypoints_xy / wh * 2 - 1 # -> [-1, 1]++ kptscore = F.grid_sample(+ scores_map[b_idx].unsqueeze(0),+ keypoints_xy.view(1, 1, -1, 2),+ mode="bilinear",+ align_corners=True,+ )[0, 0, 0, :]++ keypoints.append(keypoints_xy)+ scoredispersitys.append(scoredispersity)+ kptscores.append(kptscore)++ if return_affine:+ # Weighted covariance of hw_grid positions under soft-argmax weights.+ # w_i = x_exp_i / sum(x_exp), mu = xy_residual (already computed).+ # cov = sum_i w_i (g_i - mu)(g_i - mu)^T -> (N, 2, 2)+ W = x_exp / x_sum # (N, KΒ²) normalised weights+ delta = self.hw_grid[None] - xy_residual[:, None] # type: ignore[index] # (N, KΒ², 2)+ cov = torch.einsum("ni,nij,nik->njk", W, delta, delta) # (N, 2, 2)+ local_affines.append(_affine_from_cov(cov))+ else:+ for b_idx in range(b):+ indices_kpt = indices_keypoints[b_idx]+ keypoints_xy_nms = torch.stack(+ [indices_kpt % w, torch.div(indices_kpt, w, rounding_mode="trunc")],+ dim=1,+ )+ keypoints_xy = keypoints_xy_nms / wh * 2 - 1+ kptscore = F.grid_sample(+ scores_map[b_idx].unsqueeze(0),+ keypoints_xy.view(1, 1, -1, 2),+ mode="bilinear",+ align_corners=True,+ )[0, 0, 0, :]+ keypoints.append(keypoints_xy)+ scoredispersitys.append(torch.zeros_like(kptscore))+ kptscores.append(kptscore)+ if return_affine:+ # No soft-argmax weights available; fall back to identity.+ N_i = keypoints_xy.shape[0]+ local_affines.append(+ torch.eye(2, device=scores_map.device, dtype=scores_map.dtype).unsqueeze(0).expand(N_i, -1, -1)+ )++ if return_affine:+ return keypoints, kptscores, scoredispersitys, local_affines+ return keypoints, kptscores, scoredispersitys+++# ---------------------------------------------------------------------------+# Image padding helper+# ---------------------------------------------------------------------------+++class InputPadder:+ """Pad an image so that both spatial dimensions are divisible by ``divis_by``."""++ def __init__(self, h: int, w: int, divis_by: int = 8) -> None:+ self.ht = h+ self.wd = w+ pad_ht = (((h // divis_by) + 1) * divis_by - h) % divis_by+ pad_wd = (((w // divis_by) + 1) * divis_by - w) % divis_by+ self._pad = [pad_wd // 2, pad_wd - pad_wd // 2, pad_ht // 2, pad_ht - pad_ht // 2]++ def pad(self, x: torch.Tensor) -> torch.Tensor:+ """Pad *x* (BCHW)."""+ return F.pad(x, self._pad, mode="replicate")++ def unpad(self, x: torch.Tensor) -> torch.Tensor:+ """Remove the padding added by :meth:`pad`."""+ ht, wd = x.shape[-2], x.shape[-1]+ c = [self._pad[2], ht - self._pad[3], self._pad[0], wd - self._pad[1]]+ return x[..., c[0] : c[1], c[2] : c[3]]+++# ---------------------------------------------------------------------------+# Building blocks+# ---------------------------------------------------------------------------+++class DeformableConv2d(nn.Module):+ """Deformable conv2d (DCNv1 or DCNv2) without torchvision dependency.++ Uses the pure-PyTorch :func:`~kornia.feature.aliked.deform_conv2d.deform_conv2d`+ implementation that matches ``torchvision.ops.deform_conv2d``.++ Args:+ in_channels: number of input channels.+ out_channels: number of output channels.+ kernel_size: spatial kernel size.+ stride: convolution stride.+ padding: zero-padding size.+ bias: whether to add a learnable bias.+ mask: if ``True`` use DCNv2 modulation mask (3 * k*k offsets instead of 2).+ """++ def __init__(+ self,+ in_channels: int,+ out_channels: int,+ kernel_size: int = 3,+ stride: int = 1,+ padding: int = 1,+ dilation: int = 1,+ bias: bool = False,+ mask: bool = False,+ ) -> None:+ super().__init__()+ self.stride = stride+ self.padding = padding+ self.dilation = dilation+ self.mask = mask+ self.channel_num = 3 * kernel_size * kernel_size if mask else 2 * kernel_size * kernel_size+ self.offset_conv = nn.Conv2d(+ in_channels,+ self.channel_num,+ kernel_size=kernel_size,+ stride=stride,+ padding=self.padding,+ dilation=dilation,+ bias=True,+ )+ self.regular_conv = nn.Conv2d(+ in_channels=in_channels,+ out_channels=out_channels,+ kernel_size=kernel_size,+ stride=stride,+ padding=self.padding,+ dilation=dilation,+ bias=bias,+ )++ def forward(self, x: torch.Tensor) -> torch.Tensor:+ h, w = x.shape[2:]+ max_offset = max(h, w) / 4.0+ out = self.offset_conv(x)+ if self.mask:+ o1, o2, mask_w = torch.chunk(out, 3, dim=1)+ offset = torch.cat((o1, o2), dim=1)+ mask_w = torch.sigmoid(mask_w)+ else:+ offset = out+ mask_w = None+ offset = offset.clamp(-max_offset, max_offset)+ return deform_conv2d(+ input=x,+ offset=offset,+ weight=self.regular_conv.weight,+ bias=self.regular_conv.bias,+ stride=self.stride,+ padding=self.padding,+ dilation=self.dilation,+ mask=mask_w,+ )+++def get_conv(+ inplanes: int,+ planes: int,+ kernel_size: int = 3,+ stride: int = 1,+ padding: int = 1,+ bias: bool = False,+ conv_type: str = "conv",+ mask: bool = False,+) -> nn.Module:+ """Return a standard or deformable conv2d layer."""+ if conv_type == "conv":+ return nn.Conv2d(inplanes, planes, kernel_size=kernel_size, stride=stride, padding=padding, bias=bias)+ if conv_type == "dcn":+ return DeformableConv2d(+ inplanes,+ planes,+ kernel_size=kernel_size,+ stride=stride,+ padding=_pair(padding)[0],+ bias=bias,+ mask=mask,+ )+ raise TypeError(f"Unknown conv_type: {conv_type!r}. Expected 'conv' or 'dcn'.")+++class ConvBlock(nn.Module):+ """Two-layer conv block with BN and an activation gate."""++ def __init__(+ self,+ in_channels: int,+ out_channels: int,+ gate: Optional[Callable[..., nn.Module]] = None,+ norm_layer: Optional[Callable[..., nn.Module]] = None,+ conv_type: str = "conv",+ mask: bool = False,+ ) -> None:+ super().__init__()+ self.gate = nn.ReLU(inplace=True) if gate is None else gate+ if norm_layer is None:+ norm_layer = nn.BatchNorm2d+ self.conv1 = get_conv(in_channels, out_channels, kernel_size=3, conv_type=conv_type, mask=mask)+ self.bn1 = norm_layer(out_channels)+ self.conv2 = get_conv(out_channels, out_channels, kernel_size=3, conv_type=conv_type, mask=mask)+ self.bn2 = norm_layer(out_channels)++ def forward(self, x: torch.Tensor) -> torch.Tensor:+ x = self.gate(self.bn1(self.conv1(x)))+ return self.gate(self.bn2(self.conv2(x)))+++class ResBlock(nn.Module):+ """Residual block (BasicBlock variant) supporting deformable convolutions."""++ expansion: int = 1++ def __init__(+ self,+ inplanes: int,+ planes: int,+ stride: int = 1,+ downsample: Optional[nn.Module] = None,+ groups: int = 1,+ base_width: int = 64,+ dilation: int = 1,+ gate: Optional[Callable[..., nn.Module]] = None,+ norm_layer: Optional[Callable[..., nn.Module]] = None,+ conv_type: str = "conv",+ mask: bool = False,+ ) -> None:+ super().__init__()+ if gate is None:+ self.gate = nn.ReLU(inplace=True)+ else:+ self.gate = gate+ if norm_layer is None:+ norm_layer = nn.BatchNorm2d+ if groups != 1 or base_width != 64:+ raise ValueError("ResBlock only supports groups=1 and base_width=64")+ if dilation > 1:+ raise NotImplementedError("Dilation > 1 not supported in ResBlock")+ self.conv1 = get_conv(inplanes, planes, kernel_size=3, conv_type=conv_type, mask=mask)+ self.bn1 = norm_layer(planes)+ self.conv2 = get_conv(planes, planes, kernel_size=3, conv_type=conv_type, mask=mask)+ self.bn2 = norm_layer(planes)+ self.downsample = downsample+ self.stride = stride++ def forward(self, x: torch.Tensor) -> torch.Tensor:+ identity = x+ out = self.gate(self.bn1(self.conv1(x)))+ out = self.bn2(self.conv2(out))+ if self.downsample is not None:+ identity = self.downsample(x)+ out = self.gate(out + identity)+ return out+++# ---------------------------------------------------------------------------+# Sparse Descriptor with Deformable Heads (SDDH)+# ---------------------------------------------------------------------------+++class SDDH(nn.Module):+ """Sparse descriptor head using deformable sampling positions.++ Args:+ dims: input feature dimension.+ kernel_size: patch size used to estimate sampling offsets.+ n_pos: number of deformable sampling positions per keypoint.+ gate: activation function for the offset network.+ conv2d: if ``True`` use a 1x1 conv to aggregate features; otherwise+ use a learnable weighted sum (``agg_weights``).+ mask: if ``True`` use DCNv2-style attention weighting on samples.+ """++ def __init__(+ self,+ dims: int,+ kernel_size: int = 3,+ n_pos: int = 8,+ gate: Optional[nn.Module] = None,+ conv2d: bool = False,+ mask: bool = False,+ ) -> None:+ super().__init__()+ if gate is None:+ gate = nn.ReLU()+ self.kernel_size = kernel_size+ self.n_pos = n_pos+ self.conv2d = conv2d+ self.mask = mask+ self.get_patches_func = get_patches++ self.channel_num = 3 * n_pos if mask else 2 * n_pos+ self.offset_conv = nn.Sequential(+ nn.Conv2d(dims, self.channel_num, kernel_size=kernel_size, stride=1, padding=0, bias=True),+ gate,+ nn.Conv2d(self.channel_num, self.channel_num, kernel_size=1, stride=1, padding=0, bias=True),+ )+ self.sf_conv = nn.Conv2d(dims, dims, kernel_size=1, stride=1, padding=0, bias=False)++ if not conv2d:+ agg_weights = nn.Parameter(torch.rand(n_pos, dims, dims))+ self.register_parameter("agg_weights", agg_weights)+ else:+ self.convM = nn.Conv2d(dims * n_pos, dims, kernel_size=1, stride=1, padding=0, bias=False)++ def forward(+ self,+ x: torch.Tensor,+ keypoints: list[torch.Tensor],+ ) -> tuple[list[torch.Tensor], list[torch.Tensor]]:+ """Compute descriptors at keypoint locations.++ Args:+ x: dense feature map ``(B, C, H, W)``.+ keypoints: list of ``(N_i, 2)`` normalised keypoint coordinates ``[-1, 1]``.++ Returns:+ A pair ``(descriptors, offsets)`` where each element is a list of length B.+ """+ b, c, h, w = x.shape+ wh = torch.tensor([[w - 1, h - 1]], device=x.device, dtype=x.dtype)+ max_offset = max(h, w) / 4.0++ offsets_list = []+ descriptors = []++ for ib in range(b):+ xi, kptsi = x[ib], keypoints[ib]+ kptsi_wh = (kptsi / 2 + 0.5) * wh+ N_kpts = len(kptsi)++ if self.kernel_size > 1:+ patch = self.get_patches_func(xi, kptsi_wh.long(), self.kernel_size)+ else:+ kptsi_wh_long = kptsi_wh.long()+ patch = xi[:, kptsi_wh_long[:, 1], kptsi_wh_long[:, 0]].permute(1, 0).reshape(N_kpts, c, 1, 1)++ offset = self.offset_conv(patch).clamp(-max_offset, max_offset)++ if self.mask:+ offset = offset[:, :, 0, 0].view(N_kpts, 3, self.n_pos).permute(0, 2, 1)+ mask_w = torch.sigmoid(offset[:, :, -1])+ offset = offset[:, :, :-1]+ else:+ offset = offset[:, :, 0, 0].view(N_kpts, 2, self.n_pos).permute(0, 2, 1)+ mask_w = None+ offsets_list.append(offset)++ pos = kptsi_wh.unsqueeze(1) + offset # [N_kpts, n_pos, 2]+ pos = 2.0 * pos / wh[None] - 1+ pos = pos.reshape(1, N_kpts * self.n_pos, 1, 2)++ features = F.grid_sample(xi.unsqueeze(0), pos, mode="bilinear", align_corners=True)+ features = features.reshape(c, N_kpts, self.n_pos, 1).permute(1, 0, 2, 3)++ if mask_w is not None:+ features = torch.einsum("ncpo,np->ncpo", features, mask_w)++ features = torch.selu_(self.sf_conv(features)).squeeze(-1) # [N_kpts, C, n_pos]++ if not self.conv2d:+ descs = torch.einsum("ncp,pcd->nd", features, self.agg_weights) # codespell:ignore+ else:+ features = features.reshape(N_kpts, -1)[:, :, None, None]+ descs = self.convM(features).squeeze(-1).squeeze(-1)++ descs = F.normalize(descs, p=2.0, dim=1)+ descriptors.append(descs)++ return descriptors, offsets_list+++# ---------------------------------------------------------------------------+# ALIKED main module+# ---------------------------------------------------------------------------++_ALIKED_CFGS: dict[str, tuple[int, int, int, int, int, int, int]] = {+ # c1, c2, c3, c4, dim, K, M+ "aliked-t16": (8, 16, 32, 64, 64, 3, 16),+ "aliked-n16": (16, 32, 64, 128, 128, 3, 16),+ "aliked-n16rot": (16, 32, 64, 128, 128, 3, 16),+ "aliked-n32": (16, 32, 64, 128, 128, 3, 32),+}++_CHECKPOINT_URL = "https://github.com/Shiaoming/ALIKED/raw/main/models/{}.pth"+++class ALIKED(nn.Module):+ r"""ALIKED local feature detector and descriptor.++ ALIKED (Adaptive Local Image KEypoint Detection) combines a multi-scale+ ResNet backbone with deformable descriptor sampling (SDDH) and a+ differentiable keypoint detector (DKD).++ See :cite:`zhao2023aliked` for details.++ Args:+ model_name: backbone configuration, one of+ ``'aliked-t16'``, ``'aliked-n16'``, ``'aliked-n16rot'``, ``'aliked-n32'``.+ max_num_keypoints: maximum number of keypoints to detect.+ ``-1`` means no limit (threshold-based mode).+ detection_threshold: minimum detection score in threshold mode.+ nms_radius: NMS radius (kernel size ``= 2 * nms_radius + 1``).++ Example:+ >>> aliked = ALIKED.from_pretrained('aliked-n16')+ >>> images = torch.rand(1, 3, 256, 256)+ >>> features = aliked(images)+ """++ n_limit_max: int = 20000++ def __init__(+ self,+ model_name: str = "aliked-n16",+ max_num_keypoints: int = -1,+ detection_threshold: float = 0.2,+ nms_radius: int = 2,+ ) -> None:+ super().__init__()++ if model_name not in _ALIKED_CFGS:+ raise ValueError(f"Unknown model_name {model_name!r}. Choose from {list(_ALIKED_CFGS)}.")++ self.model_name = model_name+ self.max_num_keypoints = max_num_keypoints+ self.detection_threshold = detection_threshold+ self.nms_radius = nms_radius++ c1, c2, c3, c4, dim, K, M = _ALIKED_CFGS[model_name]+ conv_types = ["conv", "conv", "dcn", "dcn"]+ conv2d = False+ mask = False++ self.pool2 = nn.AvgPool2d(kernel_size=2, stride=2)+ self.pool4 = nn.AvgPool2d(kernel_size=4, stride=4)+ self.norm = nn.BatchNorm2d+ self.gate = nn.SELU(inplace=True)++ self.block1 = ConvBlock(3, c1, self.gate, self.norm, conv_type=conv_types[0])+ self.block2 = self._make_resblock(c1, c2, conv_types[1], mask)+ self.block3 = self._make_resblock(c2, c3, conv_types[2], mask)+ self.block4 = self._make_resblock(c3, c4, conv_types[3], mask)++ self.conv1 = _conv1x1(c1, dim // 4)+ self.conv2 = _conv1x1(c2, dim // 4)+ self.conv3 = _conv1x1(c3, dim // 4)+ self.conv4 = _conv1x1(dim, dim // 4) # note: c4 == dim for all configs++ self.upsample2 = nn.Upsample(scale_factor=2, mode="bilinear", align_corners=True)+ self.upsample4 = nn.Upsample(scale_factor=4, mode="bilinear", align_corners=True)+ self.upsample8 = nn.Upsample(scale_factor=8, mode="bilinear", align_corners=True)+ self.upsample32 = nn.Upsample(scale_factor=32, mode="bilinear", align_corners=True)++ self.score_head = nn.Sequential(+ _conv1x1(dim, 8),+ self.gate,+ _conv3x3(8, 4),+ self.gate,+ _conv3x3(4, 4),+ self.gate,+ _conv3x3(4, 1),+ )+ self.desc_head = SDDH(dim, K, M, gate=self.gate, conv2d=conv2d, mask=mask)+ self.dkd = DKD(+ radius=nms_radius,+ top_k=-1 if detection_threshold > 0 else max_num_keypoints,+ scores_th=detection_threshold,+ n_limit=max_num_keypoints if max_num_keypoints > 0 else self.n_limit_max,+ )++ def _make_resblock(self, c_in: int, c_out: int, conv_type: str, mask: bool) -> ResBlock:+ return ResBlock(+ c_in,+ c_out,+ stride=1,+ downsample=nn.Conv2d(c_in, c_out, 1),+ gate=self.gate,+ norm_layer=self.norm,+ conv_type=conv_type,+ mask=mask,+ )++ def extract_dense_map(self, image: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:+ """Run the backbone and return ``(feature_map, score_map)``.++ Args:+ image: ``(B, 3, H, W)`` float image. Inputs are internally padded to+ a multiple of 32 and the padding is removed before returning.++ Returns:+ ``feature_map``: ``(B, dim, H, W)`` L2-normalised dense features.+ ``score_map``: ``(B, 1, H, W)`` detection score map in ``(0, 1)``.+ """+ div_by = 2**5+ padder = InputPadder(image.shape[-2], image.shape[-1], div_by)+ image = padder.pad(image)++ x1 = self.block1(image)+ x2 = self.block2(self.pool2(x1))+ x3 = self.block3(self.pool4(x2))+ x4 = self.block4(self.pool4(x3))++ x1 = self.gate(self.conv1(x1))+ x2 = self.gate(self.conv2(x2))+ x3 = self.gate(self.conv3(x3))+ x4 = self.gate(self.conv4(x4))++ x2_up = self.upsample2(x2)+ x3_up = self.upsample8(x3)+ x4_up = self.upsample32(x4)+ x1234 = torch.cat([x1, x2_up, x3_up, x4_up], dim=1)++ score_map = torch.sigmoid(self.score_head(x1234))+ feature_map = F.normalize(x1234, p=2, dim=1)++ feature_map = padder.unpad(feature_map)+ score_map = padder.unpad(score_map)++ return feature_map, score_map++ def forward(+ self,+ images: torch.Tensor,+ image_size: Optional[torch.Tensor] = None,+ ) -> list[ALIKEDFeatures]:+ """Detect and describe local features in a batch of images.++ Args:+ images: ``(B, 3, H, W)`` float images (can be grayscale ``(B, 1, H, W)``+ β will be broadcast to 3 channels automatically).+ image_size: optional ``(B, 2)`` tensor of valid ``(W, H)`` for+ border masking when images are padded to a common size.++ Returns:+ A list of :class:`ALIKEDFeatures` of length B, one per image.+ Keypoints are in pixel coordinates ``[x, y]``.+ """+ if images.shape[1] == 1:+ images = grayscale_to_rgb(images)++ feature_map, score_map = self.extract_dense_map(images)+ keypoints, kptscores, _scoredispersitys = self.dkd(score_map, image_size=image_size)+ descriptors, _offsets = self.desc_head(feature_map, keypoints)++ B = images.shape[0]+ _, _, h, w = images.shape+ wh = torch.tensor([w - 1, h - 1], device=images.device, dtype=images.dtype)++ results = []+ for i in range(B):+ # Convert normalised [-1,1] coords back to pixel coordinates+ kps_px = wh * (keypoints[i] + 1) / 2.0+ results.append(ALIKEDFeatures(kps_px, descriptors[i], kptscores[i]))+ return results++ def forward_laf(+ self,+ img: torch.Tensor,+ mask: Optional[torch.Tensor] = None,+ ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:+ """Detect and describe local features, returning results in kornia LAF format.++ Local Affine Frames are estimated from the soft-argmax weight covariance+ computed inside :class:`DKD`: the 2x2 affine matrix captures the dominant+ orientation and scale of each detected keypoint without any additional+ network parameters.++ All per-image tensors are zero-padded along the keypoint dimension so+ that the outputs are proper batched tensors.++ Args:+ img: image to extract features with shape :math:`(B,C,H,W)`.+ mask: optional spatial mask ``(B, 1, H, W)`` with values in+ ``[0, 1]``; the score map is multiplied by this mask before+ keypoint detection so that features are suppressed in masked+ regions.++ Returns:+ - Detected local affine frames with shape :math:`(B,N,2,3)`.+ - Response function values for corresponding LAFs with shape :math:`(B,N,1)`.+ - Local descriptors of shape :math:`(B,N,D)`.++ """+ if img.shape[1] == 1:+ img = grayscale_to_rgb(img)++ feature_map, score_map = self.extract_dense_map(img)++ if mask is not None:+ # Resize mask to score map resolution and apply.+ mask_rs = F.interpolate(mask.float(), size=score_map.shape[-2:], mode="bilinear", align_corners=True)+ score_map = score_map * mask_rs++ dkd_out = self.dkd(score_map, return_affine=True)+ keypoints, kptscores, _scoredispersitys, local_affines = dkd_out # type: ignore[misc]+ descriptors, _offsets = self.desc_head(feature_map, keypoints)++ B, _, H, W = img.shape+ wh = torch.tensor([W - 1, H - 1], device=img.device, dtype=img.dtype)++ lafs_list: list[torch.Tensor] = []+ for i in range(B):+ kps_px = wh * (keypoints[i] + 1) / 2.0 # (N, 2)+ laf_i = _laf_from_kpts_and_affine(kps_px, local_affines[i]) # (N, 2, 3)+ lafs_list.append(laf_i)++ # Pad to the maximum number of keypoints in the batch.+ n_max = max(laf.shape[0] for laf in lafs_list) if lafs_list else 0++ def _pad(t: torch.Tensor, n: int, fill: float = 0.0) -> torch.Tensor:+ pad_n = n - t.shape[0]+ if pad_n == 0:+ return t+ pad_shape = (pad_n,) + t.shape[1:]+ return torch.cat([t, t.new_full(pad_shape, fill)], dim=0)++ lafs = torch.stack([_pad(laf, n_max) for laf in lafs_list]) # (B, N, 2, 3)+ responses = torch.stack([_pad(s, n_max).unsqueeze(-1) for s in kptscores]) # (B, N, 1)+ descs = torch.stack([_pad(d, n_max) for d in descriptors]) # (B, N, D)++ return lafs, responses, descs++ @classmethod+ def from_pretrained(+ cls,+ model_name: str = "aliked-n16",+ max_num_keypoints: int = -1,+ detection_threshold: float = 0.2,+ nms_radius: int = 2,+ device: Optional[torch.device] = None,+ ) -> ALIKED:+ """Load a pretrained ALIKED model from the official checkpoint repository.++ Args:+ model_name: one of ``'aliked-t16'``, ``'aliked-n16'``,+ ``'aliked-n16rot'``, ``'aliked-n32'``.+ max_num_keypoints: passed to :class:`ALIKED` constructor.+ detection_threshold: passed to :class:`ALIKED` constructor.+ nms_radius: passed to :class:`ALIKED` constructor.+ device: target device; defaults to CPU.++ Returns:+ Pretrained :class:`ALIKED` in eval mode.+ """+ if device is None:+ device = torch.device("cpu")+ model = cls(+ model_name=model_name,+ max_num_keypoints=max_num_keypoints,+ detection_threshold=detection_threshold,+ nms_radius=nms_radius,+ ).to(device)+ url = _CHECKPOINT_URL.format(model_name)+ state_dict = torch.hub.load_state_dict_from_url(url, map_location=device)+ model.load_state_dict(state_dict, strict=True)+ model.eval()+ return modeldiff --git a/kornia/feature/aliked/deform_conv2d.py b/kornia/feature/aliked/deform_conv2d.pynew file mode 100644index 000000000..b898a19df--- /dev/null+++ b/kornia/feature/aliked/deform_conv2d.py@@ -0,0 +1,212 @@+# 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.+#++"""Pure-PyTorch implementation of deform_conv2d matching torchvision.ops.deform_conv2d.++Implements both DCNv1 (mask=None) and DCNv2 (mask provided) as described in:+ - Deformable Convolutional Networks (https://arxiv.org/abs/1703.06211)+ - Deformable ConvNets v2 (https://arxiv.org/abs/1811.11168)+"""++from __future__ import annotations++from typing import Optional, Tuple, Union++import torch+from torch import Tensor+++def deform_conv2d(+ input: Tensor,+ offset: Tensor,+ weight: Tensor,+ bias: Optional[Tensor] = None,+ stride: Union[int, Tuple[int, int]] = (1, 1),+ padding: Union[int, Tuple[int, int]] = (0, 0),+ dilation: Union[int, Tuple[int, int]] = (1, 1),+ mask: Optional[Tensor] = None,+) -> Tensor:+ """Deformable 2D convolution (DCNv1/v2) without torchvision dependency.++ Matches the signature and behaviour of ``torchvision.ops.deform_conv2d``.++ Args:+ input: input feature map ``(B, C_in, H_in, W_in)``.+ offset: offset tensor ``(B, 2 * n_offset_groups * kH * kW, H_out, W_out)``.+ Layout per kernel point: ``(dy, dx)`` interleaved.+ weight: convolution kernel ``(C_out, C_in / groups, kH, kW)``.+ bias: optional bias ``(C_out,)``.+ stride: convolution stride ``(sH, sW)``.+ padding: zero-padding ``(pH, pW)``.+ dilation: kernel dilation ``(dH, dW)``.+ mask: optional DCNv2 modulation mask+ ``(B, n_offset_groups * kH * kW, H_out, W_out)`` in ``[0, 1]``.++ Returns:+ Output feature map ``(B, C_out, H_out, W_out)``.+ """+ B, C_in, H_in, W_in = input.shape+ C_out, C_in_per_group, kH, kW = weight.shape++ if isinstance(padding, int):+ padding = (padding, padding)+ if isinstance(dilation, int):+ dilation = (dilation, dilation)+ if isinstance(stride, int):+ stride = (stride, stride)++ sH, sW = stride+ pH, pW = padding+ dH, dW = dilation++ groups = C_in // C_in_per_group+ K = kH * kW+ n_off_grps = offset.shape[1] // (2 * K)+ c_per_off_grp = C_in // n_off_grps++ H_out = (H_in + 2 * pH - dH * (kH - 1) - 1) // sH + 1+ W_out = (W_in + 2 * pW - dW * (kW - 1) - 1) // sW + 1++ # parse offsets: interleaved (dy, dx) per kernel point per group+ offset = offset.reshape(B, n_off_grps, 2 * K, H_out, W_out)+ off_y = offset[:, :, 0::2, :, :] # [B, n_off_grps, K, H_out, W_out]+ off_x = offset[:, :, 1::2, :, :]++ if mask is not None:+ mask = mask.reshape(B, n_off_grps, K, H_out, W_out)++ # base sampling grid+ grid_oh = torch.arange(H_out, device=input.device, dtype=input.dtype)+ grid_ow = torch.arange(W_out, device=input.device, dtype=input.dtype)++ base_h = (grid_oh * sH - pH).reshape(1, 1, 1, H_out, 1)+ base_w = (grid_ow * sW - pW).reshape(1, 1, 1, 1, W_out)++ kh_offs = torch.arange(kH, device=input.device, dtype=input.dtype) * dH+ kw_offs = torch.arange(kW, device=input.device, dtype=input.dtype) * dW+ kern_h = kh_offs.repeat_interleave(kW).reshape(1, 1, K, 1, 1)+ kern_w = kw_offs.repeat(kH).reshape(1, 1, K, 1, 1)++ # Absolute fractional sampling positions [B, n_off_grps, K, H_out, W_out]+ sample_h = base_h + kern_h + off_y+ sample_w = base_w + kern_w + off_x++ # bilinear interpolation with zero-padding+ sampled = _bilinear_sample(input, sample_h, sample_w, n_off_grps, c_per_off_grp)+ # sampled: [B, n_off_grps, c_per_off_grp, K, H_out, W_out]++ # apply mask (DCNv2 modulation)+ if mask is not None:+ sampled = sampled * mask.unsqueeze(2) # broadcast over channels++ # reshape for grouped matmul+ sampled = sampled.reshape(B, C_in, K, H_out, W_out)++ C_out_per_group = C_out // groups+ sampled = sampled.reshape(B, groups, C_in_per_group, K, H_out * W_out)+ weight_flat = weight.reshape(groups, C_out_per_group, C_in_per_group, K)++ out = torch.einsum("bgckn,gock->bgon", sampled, weight_flat)+ out = out.reshape(B, C_out, H_out, W_out)++ if bias is not None:+ out = out + bias.reshape(1, -1, 1, 1)++ return out+++def _bilinear_sample(+ input: Tensor,+ sample_h: Tensor,+ sample_w: Tensor,+ n_off_grps: int,+ c_per_off_grp: int,+) -> Tensor:+ """Sample input at fractional (sample_h, sample_w) positions with zero-padding.++ Uses the same corner-validity bilinear interpolation as torchvision's+ deformable-conv C++ kernel.++ Args:+ input: ``(B, C_in, H_in, W_in)``+ sample_h: ``(B, n_off_grps, K, H_out, W_out)``+ sample_w: ``(B, n_off_grps, K, H_out, W_out)``+ n_off_grps: number of offset groups.+ c_per_off_grp: input channels per offset group.++ Returns:+ Sampled tensor ``(B, n_off_grps, c_per_off_grp, K, H_out, W_out)``.+ """+ B, _C_in, H_in, W_in = input.shape++ h0 = sample_h.floor()+ w0 = sample_w.floor()++ lh = sample_h - h0+ lw = sample_w - w0++ h0 = h0.long()+ w0 = w0.long()+ h1 = h0 + 1+ w1 = w0 + 1++ def _valid(h: Tensor, w: Tensor) -> Tensor:+ return ((h >= 0) & (h < H_in) & (w >= 0) & (w < W_in)).to(input.dtype)++ m00 = _valid(h0, w0)+ m01 = _valid(h0, w1)+ m10 = _valid(h1, w0)+ m11 = _valid(h1, w1)++ h0c = h0.clamp(0, max(H_in - 1, 0))+ h1c = h1.clamp(0, max(H_in - 1, 0))+ w0c = w0.clamp(0, max(W_in - 1, 0))+ w1c = w1.clamp(0, max(W_in - 1, 0))++ # input -> [B, n_off_grps, c_per_off_grp, H_in * W_in]+ input_flat = input.reshape(B, n_off_grps, c_per_off_grp, H_in * W_in)++ flat_size = sample_h.shape[2] * sample_h.shape[3] * sample_h.shape[4] # K*H_out*W_out++ def _gather(hh: Tensor, ww: Tensor) -> Tensor:+ idx = (hh * W_in + ww).reshape(B, n_off_grps, flat_size)+ idx = idx.unsqueeze(2).expand(-1, -1, c_per_off_grp, -1)+ return torch.gather(input_flat, 3, idx)++ v00 = _gather(h0c, w0c)+ v01 = _gather(h0c, w1c)+ v10 = _gather(h1c, w0c)+ v11 = _gather(h1c, w1c)++ K = sample_h.shape[2]+ H_out = sample_h.shape[3]+ W_out = sample_h.shape[4]+ shape = (B, n_off_grps, c_per_off_grp, K, H_out, W_out)++ v00 = v00.reshape(shape)+ v01 = v01.reshape(shape)+ v10 = v10.reshape(shape)+ v11 = v11.reshape(shape)++ lh = lh.unsqueeze(2)+ lw = lw.unsqueeze(2)+ m00 = m00.unsqueeze(2)+ m01 = m01.unsqueeze(2)+ m10 = m10.unsqueeze(2)+ m11 = m11.unsqueeze(2)++ return v00 * m00 * (1 - lh) * (1 - lw) + v01 * m01 * (1 - lh) * lw + v10 * m10 * lh * (1 - lw) + v11 * m11 * lh * lwdiff --git a/kornia/geometry/subpix/nms.py b/kornia/geometry/subpix/nms.pyindex fa035a0e9..f2cd723a6 100644--- a/kornia/geometry/subpix/nms.py+++ b/kornia/geometry/subpix/nms.py@@ -72,15 +72,130 @@ class NonMaximaSuppression2d(nn.Module):if len(x.shape) != 4:raise AssertionError(x.shape)B, CH, H, W = x.size()- # find local maximum values- x_padded = F.pad(x, list(self.padding)[::-1], mode="replicate")- B, CH, HP, WP = x_padded.size()-- neighborhood = F.conv2d(x_padded.view(B * CH, 1, HP, WP), self.kernel.to(x.device, x.dtype), stride=1).view(- B, CH, -1, H, W- )- max_non_center = neighborhood.max(dim=2)[0]- mask = x > max_non_center++ if self.kernel_size == (3, 3):+ # 8-comparison explicit path: no extra memory for conv kernel.+ left = slice(0, -2)+ center = slice(1, -1)+ right = slice(2, None)+ mask = torch.zeros(B, CH, H, W, device=x.device, dtype=torch.bool)+ ct = x[..., center, center]+ mask[..., 1:-1, 1:-1] = (+ (ct > x[..., left, left])+ & (ct > x[..., left, center])+ & (ct > x[..., left, right])+ & (ct > x[..., center, left])+ & (ct > x[..., center, right])+ & (ct > x[..., right, left])+ & (ct > x[..., right, center])+ & (ct > x[..., right, right])+ )+ elif self.kernel_size == (5, 5):+ # 24-comparison explicit path for 5x5 neighbourhood.+ c2 = slice(0, -4)+ c1 = slice(1, -3)+ c0 = slice(2, -2)+ p1 = slice(3, -1)+ p2 = slice(4, None)+ mask = torch.zeros(B, CH, H, W, device=x.device, dtype=torch.bool)+ ct = x[..., c0, c0]+ mask[..., 2:-2, 2:-2] = (+ (ct > x[..., c2, c2])+ & (ct > x[..., c2, c1])+ & (ct > x[..., c2, c0])+ & (ct > x[..., c2, p1])+ & (ct > x[..., c2, p2])+ & (ct > x[..., c1, c2])+ & (ct > x[..., c1, c1])+ & (ct > x[..., c1, c0])+ & (ct > x[..., c1, p1])+ & (ct > x[..., c1, p2])+ & (ct > x[..., c0, c2])+ & (ct > x[..., c0, c1])+ & (ct > x[..., c0, p1])+ & (ct > x[..., c0, p2])+ & (ct > x[..., p1, c2])+ & (ct > x[..., p1, c1])+ & (ct > x[..., p1, c0])+ & (ct > x[..., p1, p1])+ & (ct > x[..., p1, p2])+ & (ct > x[..., p2, c2])+ & (ct > x[..., p2, c1])+ & (ct > x[..., p2, c0])+ & (ct > x[..., p2, p1])+ & (ct > x[..., p2, p2])+ )+ elif self.kernel_size == (7, 7):+ # 48-comparison explicit path for 7x7 neighbourhood.+ c3 = slice(0, -6)+ c2 = slice(1, -5)+ c1 = slice(2, -4)+ c0 = slice(3, -3)+ p1 = slice(4, -2)+ p2 = slice(5, -1)+ p3 = slice(6, None)+ mask = torch.zeros(B, CH, H, W, device=x.device, dtype=torch.bool)+ ct = x[..., c0, c0]+ mask[..., 3:-3, 3:-3] = (+ (ct > x[..., c3, c3])+ & (ct > x[..., c3, c2])+ & (ct > x[..., c3, c1])+ & (ct > x[..., c3, c0])+ & (ct > x[..., c3, p1])+ & (ct > x[..., c3, p2])+ & (ct > x[..., c3, p3])+ & (ct > x[..., c2, c3])+ & (ct > x[..., c2, c2])+ & (ct > x[..., c2, c1])+ & (ct > x[..., c2, c0])+ & (ct > x[..., c2, p1])+ & (ct > x[..., c2, p2])+ & (ct > x[..., c2, p3])+ & (ct > x[..., c1, c3])+ & (ct > x[..., c1, c2])+ & (ct > x[..., c1, c1])+ & (ct > x[..., c1, c0])+ & (ct > x[..., c1, p1])+ & (ct > x[..., c1, p2])+ & (ct > x[..., c1, p3])+ & (ct > x[..., c0, c3])+ & (ct > x[..., c0, c2])+ & (ct > x[..., c0, c1])+ & (ct > x[..., c0, p1])+ & (ct > x[..., c0, p2])+ & (ct > x[..., c0, p3])+ & (ct > x[..., p1, c3])+ & (ct > x[..., p1, c2])+ & (ct > x[..., p1, c1])+ & (ct > x[..., p1, c0])+ & (ct > x[..., p1, p1])+ & (ct > x[..., p1, p2])+ & (ct > x[..., p1, p3])+ & (ct > x[..., p2, c3])+ & (ct > x[..., p2, c2])+ & (ct > x[..., p2, c1])+ & (ct > x[..., p2, c0])+ & (ct > x[..., p2, p1])+ & (ct > x[..., p2, p2])+ & (ct > x[..., p2, p3])+ & (ct > x[..., p3, c3])+ & (ct > x[..., p3, c2])+ & (ct > x[..., p3, c1])+ & (ct > x[..., p3, c0])+ & (ct > x[..., p3, p1])+ & (ct > x[..., p3, p2])+ & (ct > x[..., p3, p3])+ )+ else:+ # General path: conv2d maps every neighbour into its own channel.+ x_padded = F.pad(x, list(self.padding)[::-1], mode="replicate")+ B, CH, HP, WP = x_padded.size()+ neighborhood = F.conv2d(x_padded.view(B * CH, 1, HP, WP), self.kernel.to(x.device, x.dtype), stride=1).view(+ B, CH, -1, H, W+ )+ max_non_center = neighborhood.max(dim=2)[0]+ mask = x > max_non_center+if mask_only:return maskreturn x * (mask.to(x.dtype))diff --git a/tests/feature/test_aliked.py b/tests/feature/test_aliked.pynew file mode 100644index 000000000..adfdc7dc7--- /dev/null+++ b/tests/feature/test_aliked.py@@ -0,0 +1,312 @@+# 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.+#++import pytest+import torch++from kornia.feature.aliked import ALIKED, ALIKEDFeatures+from kornia.feature.aliked.deform_conv2d import deform_conv2d++from testing.base import BaseTester+++def _has_torchvision() -> bool:+ try:+ import torchvision.ops # noqa: F401++ return True+ except ImportError:+ return False+++# ---------------------------------------------------------------------------+# deform_conv2d tests+# ---------------------------------------------------------------------------+++class TestDeformConv2d:+ """Tests for the pure-PyTorch deform_conv2d implementation."""++ @pytest.mark.parametrize("dtype", [torch.float32, torch.float64])+ def test_zero_offset_matches_regular_conv(self, device, dtype):+ """With all-zero offsets, deform_conv2d should equal regular conv2d."""+ B, C_in, H, W = 1, 4, 8, 8+ C_out, kH, kW = 8, 3, 3+ K = kH * kW++ x = torch.randn(B, C_in, H, W, device=device, dtype=dtype)+ weight = torch.randn(C_out, C_in, kH, kW, device=device, dtype=dtype)+ offset = torch.zeros(B, 2 * K, H, W, device=device, dtype=dtype)++ out_dcn = deform_conv2d(x, offset, weight, padding=1)+ out_reg = torch.nn.functional.conv2d(x, weight, padding=1)++ assert out_dcn.shape == out_reg.shape+ assert torch.allclose(out_dcn, out_reg, atol=1e-5)++ @pytest.mark.parametrize("dtype", [torch.float32])+ def test_output_shape(self, device, dtype):+ """Check output spatial dimensions for various settings."""+ B, C_in, H, W = 2, 3, 16, 16+ C_out, kH, kW = 6, 3, 3+ K = kH * kW+ padding, stride = 1, 1++ H_out = (H + 2 * padding - kH) // stride + 1+ W_out = (W + 2 * padding - kW) // stride + 1++ x = torch.randn(B, C_in, H, W, device=device, dtype=dtype)+ weight = torch.randn(C_out, C_in, kH, kW, device=device, dtype=dtype)+ offset = torch.zeros(B, 2 * K, H_out, W_out, device=device, dtype=dtype)++ out = deform_conv2d(x, offset, weight, padding=padding, stride=stride)+ assert out.shape == (B, C_out, H_out, W_out)++ @pytest.mark.skipif(not _has_torchvision(), reason="torchvision not installed")+ @pytest.mark.parametrize("dtype", [torch.float32])+ @pytest.mark.parametrize("use_mask", [False, True])+ def test_matches_torchvision(self, device, dtype, use_mask):+ """Pure-PyTorch implementation should match torchvision reference."""+ import torchvision.ops as tvops++ B, C_in, H, W = 2, 4, 10, 10+ C_out, kH, kW = 8, 3, 3+ K = kH * kW+ padding = 1++ H_out = H # padding=1, stride=1, 3x3 kernel+ W_out = W++ torch.manual_seed(0)+ x = torch.randn(B, C_in, H, W, device=device, dtype=dtype)+ weight = torch.randn(C_out, C_in, kH, kW, device=device, dtype=dtype)+ bias = torch.randn(C_out, device=device, dtype=dtype)+ offset = torch.randn(B, 2 * K, H_out, W_out, device=device, dtype=dtype) * 0.5+ mask = torch.rand(B, K, H_out, W_out, device=device, dtype=dtype) if use_mask else None++ out_ours = deform_conv2d(x, offset, weight, bias=bias, padding=padding, mask=mask)+ out_tv = tvops.deform_conv2d(x, offset, weight, bias=bias, padding=padding, mask=mask)++ assert torch.allclose(out_ours, out_tv, atol=1e-4), f"Max diff: {(out_ours - out_tv).abs().max():.2e}"++ def test_gradients(self, device):+ """Gradients should flow through the pure-PyTorch implementation."""+ B, C_in, H, W = 1, 2, 6, 6+ C_out, kH, kW = 4, 3, 3+ K = kH * kW++ x = torch.randn(B, C_in, H, W, device=device, requires_grad=True)+ weight = torch.randn(C_out, C_in, kH, kW, device=device, requires_grad=True)+ offset = (torch.randn(B, 2 * K, H, W, device=device) * 0.1).requires_grad_(True)++ out = deform_conv2d(x, offset, weight, padding=1)+ out.sum().backward()+ assert x.grad is not None+ assert weight.grad is not None+ assert offset.grad is not None+++# ---------------------------------------------------------------------------+# ALIKED tests+# ---------------------------------------------------------------------------+++class TestALIKED(BaseTester):+ def test_smoke(self, dtype, device):+ aliked = ALIKED().to(device, dtype)+ inp = torch.rand(1, 3, 64, 64, device=device, dtype=dtype)+ output = aliked(inp)+ assert isinstance(output, list)+ assert len(output) == 1+ assert isinstance(output[0], ALIKEDFeatures)++ def test_smoke_batch(self, dtype, device):+ aliked = ALIKED().to(device, dtype)+ inp = torch.rand(2, 3, 64, 64, device=device, dtype=dtype)+ output = aliked(inp)+ assert len(output) == 2+ assert all(isinstance(f, ALIKEDFeatures) for f in output)++ def test_grayscale_input(self, dtype, device):+ """1-channel input should be broadcast to 3 channels automatically."""+ aliked = ALIKED().to(device, dtype)+ inp = torch.rand(1, 1, 64, 64, device=device, dtype=dtype)+ output = aliked(inp)+ assert isinstance(output[0], ALIKEDFeatures)++ def test_output_shapes(self, dtype, device):+ """Keypoints should be (N,2), descriptors (N,D), scores (N,)."""+ aliked = ALIKED(model_name="aliked-t16").to(device, dtype)+ inp = torch.rand(1, 3, 64, 64, device=device, dtype=dtype)+ output = aliked(inp)+ feat = output[0]+ N = feat.n+ assert feat.keypoints.shape == (N, 2)+ assert feat.descriptors.shape[0] == N+ assert feat.keypoint_scores.shape == (N,)++ def test_descriptor_normalized(self, dtype, device):+ """Descriptors should be L2-normalised."""+ aliked = ALIKED(model_name="aliked-t16").to(device, dtype)+ inp = torch.rand(1, 3, 64, 64, device=device, dtype=dtype)+ output = aliked(inp)+ feat = output[0]+ if feat.n > 0:+ norms = feat.descriptors.norm(dim=-1)+ assert torch.allclose(norms, torch.ones_like(norms), atol=1e-4)++ def test_keypoints_in_image(self, dtype, device):+ """Keypoints should lie within the image boundaries."""+ H, W = 64, 64+ aliked = ALIKED(model_name="aliked-t16").to(device, dtype)+ inp = torch.rand(1, 3, H, W, device=device, dtype=dtype)+ output = aliked(inp)+ feat = output[0]+ if feat.n > 0:+ assert (feat.keypoints[:, 0] >= 0).all()+ assert (feat.keypoints[:, 0] <= W - 1).all()+ assert (feat.keypoints[:, 1] >= 0).all()+ assert (feat.keypoints[:, 1] <= H - 1).all()++ @pytest.mark.parametrize("model_name", ["aliked-t16", "aliked-n16", "aliked-n32"])+ def test_model_configs(self, device, model_name):+ """All model configurations should run without error."""+ aliked = ALIKED(model_name=model_name).to(device)+ inp = torch.rand(1, 3, 64, 64, device=device)+ output = aliked(inp)+ assert len(output) == 1++ def test_aliked_features_to(self, device):+ """ALIKEDFeatures.to() should move all tensors."""+ feat = ALIKEDFeatures(+ keypoints=torch.rand(10, 2),+ descriptors=torch.rand(10, 64),+ keypoint_scores=torch.rand(10),+ )+ feat_dev = feat.to(device)+ assert feat_dev.keypoints.device.type == device.type+ assert feat_dev.descriptors.device.type == device.type+ assert feat_dev.keypoint_scores.device.type == device.type++ @pytest.mark.slow+ @pytest.mark.parametrize("model_name", ["aliked-n16"])+ def test_pretrained(self, device, model_name):+ """Pretrained model should load and produce reasonable detections."""+ aliked = ALIKED.from_pretrained(model_name=model_name, device=device)+ inp = torch.rand(1, 3, 256, 256, device=device)+ with torch.no_grad():+ output = aliked(inp)+ assert len(output) == 1+ assert output[0].n > 0++ def test_gradcheck(self, device):+ """gradcheck on the fully-differentiable extract_dense_map sub-graph.++ The full pipeline includes discrete NMS/argmax steps that are not+ differentiable, so gradcheck is run on extract_dense_map which covers+ the backbone, feature pyramid, and score head. The model is placed+ in eval mode so BatchNorm uses fixed running statistics.+ """+ aliked = ALIKED(model_name="aliked-t16").to(device, torch.float64).eval()+ inp = torch.rand(1, 3, 32, 32, device=device, dtype=torch.float64, requires_grad=True)++ def fn(x: torch.Tensor) -> torch.Tensor:+ fm, sm = aliked.extract_dense_map(x)+ return fm, sm++ assert torch.autograd.gradcheck(fn, [inp], eps=1e-4, atol=1e-3, rtol=1e-3, fast_mode=True)+++# ---------------------------------------------------------------------------+# forward_laf tests+# ---------------------------------------------------------------------------+++class TestALIKEDForwardLAF(BaseTester):+ """Tests for ALIKED.forward_laf returning kornia LAF-format outputs."""++ def test_smoke(self, device, dtype):+ """forward_laf should return the three expected tensors."""+ aliked = ALIKED(model_name="aliked-t16", max_num_keypoints=32).to(device, dtype)+ inp = torch.rand(1, 3, 64, 64, device=device, dtype=dtype)+ lafs, responses, descs = aliked.forward_laf(inp)+ assert lafs.ndim == 4 # (B, N, 2, 3)+ assert responses.ndim == 3 # (B, N, 1)+ assert descs.ndim == 3 # (B, N, D)++ def test_output_shapes(self, device, dtype):+ """Shapes should be (B, N, 2, 3), (B, N, 1), (B, N, D)."""+ B, H, W = 2, 64, 64+ top_k = 20+ aliked = ALIKED(model_name="aliked-t16", max_num_keypoints=top_k).to(device, dtype)+ inp = torch.rand(B, 3, H, W, device=device, dtype=dtype)+ lafs, responses, descs = aliked.forward_laf(inp)+ N = lafs.shape[1]+ assert lafs.shape == (B, N, 2, 3)+ assert responses.shape == (B, N, 1)+ assert descs.shape[0] == B+ assert descs.shape[1] == N++ def test_laf_center_in_image(self, device, dtype):+ """LAF centres (col 2) should lie within image bounds."""+ H, W = 64, 64+ top_k = 30+ aliked = ALIKED(model_name="aliked-t16", max_num_keypoints=top_k).to(device, dtype)+ inp = torch.rand(1, 3, H, W, device=device, dtype=dtype)+ lafs, responses, _ = aliked.forward_laf(inp)+ # Only check keypoints with positive response (non-padding).+ valid = responses[0, :, 0] > 0+ if valid.any():+ centers = lafs[0, valid, :, 2] # (N_valid, 2) β [x, y]+ assert (centers[:, 0] >= 0).all()+ assert (centers[:, 0] <= W - 1).all()+ assert (centers[:, 1] >= 0).all()+ assert (centers[:, 1] <= H - 1).all()++ def test_batch_padding(self, device, dtype):+ """All images in the batch should share the same N (padded to max)."""+ B = 3+ aliked = ALIKED(model_name="aliked-t16", max_num_keypoints=25).to(device, dtype)+ inp = torch.rand(B, 3, 64, 64, device=device, dtype=dtype)+ lafs, responses, descs = aliked.forward_laf(inp)+ assert lafs.shape[0] == B+ assert responses.shape[0] == B+ assert descs.shape[0] == B++ def test_laf_with_mask(self, device, dtype):+ """Providing a mask should suppress keypoints in the masked region."""+ H, W = 64, 64+ aliked = ALIKED(model_name="aliked-t16", max_num_keypoints=40).to(device, dtype)+ inp = torch.rand(1, 3, H, W, device=device, dtype=dtype)+ # Suppress the entire image except the bottom-right quarter.+ mask = torch.zeros(1, 1, H, W, device=device, dtype=dtype)+ mask[:, :, H // 2 :, W // 2 :] = 1.0+ lafs_masked, _, _ = aliked.forward_laf(inp, mask=mask)+ assert lafs_masked.shape[0] == 1++ def test_laf_affine_shape(self, device, dtype):+ """The 2x2 affine part of each LAF should be non-degenerate for valid kpts."""+ top_k = 20+ aliked = ALIKED(model_name="aliked-t16", max_num_keypoints=top_k).to(device, dtype)+ inp = torch.rand(1, 3, 64, 64, device=device, dtype=dtype)+ lafs, responses, _ = aliked.forward_laf(inp)+ valid = responses[0, :, 0] > 0+ if valid.any():+ A = lafs[0, valid, :, :2] # (N_valid, 2, 2)+ # det(A) should be non-zero (non-degenerate)+ dets = torch.det(A)+ assert (dets.abs() > 1e-6).all()