Implementation:Kornia Kornia Feature Matching Functions
| Knowledge Sources | |
|---|---|
| Domains | Vision, Feature_Matching |
| Last Updated | 2026-02-09 15:00 GMT |
Overview
Concrete tools for matching feature descriptors between images provided by Kornia's matching module.
Description
Kornia provides three descriptor matching functions: match_nn (nearest neighbor), match_mnn (mutual nearest neighbor), and match_snn (second nearest neighbor ratio test). All accept descriptor tensors and return match indices and distances. An optional precomputed distance matrix dm can be passed to avoid recomputation. These functions use torch.cdist for efficient distance computation on GPU.
Usage
Import the appropriate matching function based on your precision/recall requirements. Use match_snn for standard Lowe's ratio test filtering.
Code Reference
Source Location
- Repository: kornia
- File:
kornia/feature/matching.py - Lines: L81-187
Signatures
def match_nn(
desc1: torch.Tensor,
desc2: torch.Tensor,
dm: Optional[torch.Tensor] = None
) -> Tuple[torch.Tensor, torch.Tensor]
def match_mnn(
desc1: torch.Tensor,
desc2: torch.Tensor,
dm: Optional[torch.Tensor] = None
) -> Tuple[torch.Tensor, torch.Tensor]
def match_snn(
desc1: torch.Tensor,
desc2: torch.Tensor,
th: float = 0.8,
dm: Optional[torch.Tensor] = None
) -> Tuple[torch.Tensor, torch.Tensor]
Import
from kornia.feature import match_nn, match_mnn, match_snn
I/O Contract
Inputs
| Name | Type | Required | Description |
|---|---|---|---|
| desc1 | torch.Tensor | Yes | Descriptors from image 1 of shape (N1, D) |
| desc2 | torch.Tensor | Yes | Descriptors from image 2 of shape (N2, D) |
| th | float | No | SNN ratio threshold, default 0.8 (match_snn only) |
| dm | Optional[torch.Tensor] | No | Precomputed distance matrix of shape (N1, N2) |
Outputs
| Name | Type | Description |
|---|---|---|
| match_indices | torch.Tensor (M, 2) | Index pairs mapping desc1 to desc2 |
| match_distances | torch.Tensor (M,) | Distance for each matched pair |
Usage Examples
NN Matching
import torch
from kornia.feature import match_nn
desc1 = torch.rand(100, 128) # 100 descriptors, dim 128
desc2 = torch.rand(150, 128) # 150 descriptors, dim 128
indices, distances = match_nn(desc1, desc2)
# indices.shape == (100, 2)
# distances.shape == (100,)
MNN Matching
import torch
from kornia.feature import match_mnn
desc1 = torch.rand(100, 128)
desc2 = torch.rand(150, 128)
indices, distances = match_mnn(desc1, desc2)
# indices contains only mutual nearest neighbor pairs
SNN with Custom Threshold
import torch
from kornia.feature import match_snn
desc1 = torch.rand(100, 128)
desc2 = torch.rand(150, 128)
indices, distances = match_snn(desc1, desc2, th=0.75)
# indices contains matches passing the ratio test