Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

Add Homography Tracker API (#1389)

Dmytro Mishkin59e1978d9d54
diff --git a/conftest.py b/conftest.py
index 9f02acf1b..7d84642eb 100644
--- a/conftest.py
+++ b/conftest.py
@@ -92,3 +92,17 @@ def pytest_addoption(parser):
def add_np(doctest_namespace):
doctest_namespace["np"] = numpy
doctest_namespace["torch"] = torch
+ doctest_namespace["kornia"] = kornia
+
+
+# the commit hash for the data version
+sha: str = 'cb8f42bf28b9f347df6afba5558738f62a11f28a'
+
+
[email protected](scope='session')
+def data(request):
+ url = {
+ 'loftr_homo': f'https://github.com/kornia/data_test/blob/{sha}/loftr_outdoor_and_homography_data.pt?raw=true',
+ 'loftr_fund': f'https://github.com/kornia/data_test/blob/{sha}/loftr_indoor_and_fundamental_data.pt?raw=true',
+ }
+ return torch.hub.load_state_dict_from_url(url[request.param])
diff --git a/docs/source/conf.py b/docs/source/conf.py
index 7bfbaa555..cc2518aad 100644
--- a/docs/source/conf.py
+++ b/docs/source/conf.py
@@ -48,6 +48,7 @@ extensions = [
# substitutes the default values
docstring_default_arg_substitution = 'Default: '
+autodoc_preserve_defaults = True
bibtex_bibfiles = ['references.bib']
napoleon_use_ivar = True
diff --git a/docs/source/feature.rst b/docs/source/feature.rst
index b781d931a..4e91e7bd1 100644
--- a/docs/source/feature.rst
+++ b/docs/source/feature.rst
@@ -21,17 +21,36 @@ Descriptors
.. autoclass:: HardNet8
.. autoclass:: TFeat
.. autoclass:: SOSNet
+.. autoclass:: LAFDescriptor
+ :members: forward
+.. autofunction:: get_laf_descriptors
Matching
------------
+--------
.. autofunction:: match_nn
.. autofunction:: match_mnn
.. autofunction:: match_snn
.. autofunction:: match_smnn
-.. autoclass:: LoFTR
+.. autoclass:: DescriptorMatcher
+ :members: forward
+
+.. autoclass:: LocalFeature
+ :members: forward
+
+.. autoclass:: SIFTFeature
+ :members: forward
+
+.. autoclass:: GFTTAffNetHardNet
+ :members: forward
+
+.. autoclass:: LocalFeatureMatcher
+ :members: forward
+
+.. autoclass:: LoFTR
+ :members: forward
Local Affine Frames (LAF)
@@ -75,18 +94,25 @@ Module
.. autoclass:: ScaleSpaceDetector
:members: forward
+
.. autoclass:: PassLAF
:members: forward
+
.. autoclass:: PatchAffineShapeEstimator
:members: forward
+
.. autoclass:: LAFAffineShapeEstimator
:members: forward
+
.. autoclass:: LAFOrienter
:members: forward
+
.. autoclass:: PatchDominantGradientOrientation
:members: forward
+
.. autoclass:: OriNet
:members: forward
+
.. autoclass:: LAFAffNetShapeEstimator
:members: forward
diff --git a/docs/source/geometry.ransac.rst b/docs/source/geometry.ransac.rst
index 05d3328c4..e85ca5f58 100644
--- a/docs/source/geometry.ransac.rst
+++ b/docs/source/geometry.ransac.rst
@@ -6,3 +6,4 @@ kornia.geometry.ransac
Module with RANSAC
.. autoclass:: RANSAC
+ :members: forward
diff --git a/docs/source/index.rst b/docs/source/index.rst
index 6f0ed4c1f..3c2ac1431 100644
--- a/docs/source/index.rst
+++ b/docs/source/index.rst
@@ -72,6 +72,7 @@ Join the community
models/hardnet
models/affnet
+
.. toctree::
:caption: API REFERENCE
:maxdepth: 2
@@ -87,6 +88,7 @@ Join the community
losses
metrics
morphology
+ tracking
utils
x
diff --git a/docs/source/tracking.rst b/docs/source/tracking.rst
new file mode 100644
index 000000000..8b57a89f4
--- /dev/null
+++ b/docs/source/tracking.rst
@@ -0,0 +1,7 @@
+kornia.tracking
+===============
+
+.. currentmodule:: kornia.tracking
+
+.. autoclass:: HomographyTracker
+ :members:
diff --git a/kornia/feature/__init__.py b/kornia/feature/__init__.py
index 8430b30a2..16b4df144 100644
--- a/kornia/feature/__init__.py
+++ b/kornia/feature/__init__.py
@@ -18,6 +18,7 @@ non_maxima_suppression3d = nms3d
from .affine_shape import LAFAffineShapeEstimator, LAFAffNetShapeEstimator, PatchAffineShapeEstimator
from .defmo import DeFMO
from .hardnet import HardNet, HardNet8
+from .integrated import *
from .laf import (
denormalize_laf,
ellipse_to_laf,
@@ -37,7 +38,7 @@ from .laf import (
scale_laf,
set_laf_orientation,
)
-from .matching import match_mnn, match_nn, match_smnn, match_snn
+from .matching import *
from .mkd import MKDDescriptor
from .orientation import LAFOrienter, OriNet, PatchDominantGradientOrientation
from .scale_space_detector import PassLAF, ScaleSpaceDetector
@@ -71,6 +72,7 @@ __all__ = [
"get_laf_center",
"get_laf_orientation",
"set_laf_orientation",
+ "get_laf_descriptors",
"scale_laf",
"SIFTDescriptor",
"MKDDescriptor",
@@ -95,5 +97,11 @@ __all__ = [
"match_mnn",
"match_snn",
"match_smnn",
+ "LocalFeatureMatcher",
+ "LocalFeature",
+ "SIFTFeature",
+ "GFTTAffNetHardNet",
+ "LAFDescriptor",
+ "DescriptorMatcher",
"LoFTR",
]
diff --git a/kornia/feature/hardnet.py b/kornia/feature/hardnet.py
index 65398b547..0eff69fcb 100644
--- a/kornia/feature/hardnet.py
+++ b/kornia/feature/hardnet.py
@@ -22,17 +22,18 @@ class HardNet(nn.Module):
pretrained: Download and set pretrained weights to the model.
Returns:
- HardNet descriptor of the patches.
+ torch.Tensor: HardNet descriptor of the patches.
Shape:
- - Input: (B, 1, 32, 32)
- - Output: (B, 128)
+ - Input: :math:`(B, 1, 32, 32)`
+ - Output: :math:`(B, 128)`
Examples:
>>> input = torch.rand(16, 1, 32, 32)
>>> hardnet = HardNet()
>>> descs = hardnet(input) # 16x128
"""
+ patch_size = 32
def __init__(self, pretrained: bool = False) -> None:
super().__init__()
@@ -94,17 +95,18 @@ class HardNet8(nn.Module):
pretrained: Download and set pretrained weights to the model.
Returns:
- HardNet8 descriptor of the patches.
+ torch.Tensor: HardNet8 descriptor of the patches.
Shape:
- - Input: (B, 1, 32, 32)
- - Output: (B, 128)
+ - Input: :math:`(B, 1, 32, 32)`
+ - Output: :math:`(B, 128)`
Examples:
>>> input = torch.rand(16, 1, 32, 32)
>>> hardnet = HardNet8()
>>> descs = hardnet(input) # 16x128
"""
+ patch_size = 32
def __init__(self, pretrained: bool = False):
super().__init__()
diff --git a/kornia/feature/integrated.py b/kornia/feature/integrated.py
new file mode 100644
index 000000000..d97a48a64
--- /dev/null
+++ b/kornia/feature/integrated.py
@@ -0,0 +1,290 @@
+from typing import Dict, List, Optional, Tuple
+
+import torch
+import torch.nn as nn
+
+from kornia.color import rgb_to_grayscale
+from kornia.feature.affine_shape import LAFAffNetShapeEstimator
+from kornia.feature.hardnet import HardNet
+from kornia.feature.laf import extract_patches_from_pyramid, get_laf_center, raise_error_if_laf_is_not_valid
+from kornia.feature.orientation import LAFOrienter, PassLAF
+from kornia.feature.responses import BlobDoG, CornerGFTT
+from kornia.feature.scale_space_detector import ScaleSpaceDetector
+from kornia.feature.siftdesc import SIFTDescriptor
+from kornia.geometry import ConvQuadInterp3d, ScalePyramid
+
+
+def get_laf_descriptors(img: torch.Tensor,
+ lafs: torch.Tensor,
+ patch_descriptor: nn.Module,
+ patch_size: int = 32,
+ grayscale_descriptor: bool = True) -> torch.Tensor:
+ r"""Function to get local descriptors, corresponding to LAFs (keypoints).
+
+ Args:
+ img: image features with shape :math:`(B,C,H,W)`.
+ lafs: local affine frames :math:`(B,N,2,3)`.
+ patch_descriptor: patch descriptor module, e.g. :class:`~kornia.feature.SIFTDescriptor`
+ or :class:`~kornia.feature.HardNet`.
+ patch_size: patch size in pixels, which descriptor expects.
+ grayscale_descriptor: True if ``patch_descriptor`` expects single-channel image.
+
+ Returns:
+ Local descriptors of shape :math:`(B,N,D)` where :math:`D` is descriptor size.
+ """
+ raise_error_if_laf_is_not_valid(lafs)
+ patch_descriptor = patch_descriptor.to(img)
+ patch_descriptor.eval()
+
+ timg: torch.Tensor = img
+ if grayscale_descriptor and img.size(1) == 3:
+ timg = rgb_to_grayscale(img)
+
+ patches: torch.Tensor = extract_patches_from_pyramid(timg, lafs, patch_size)
+ # Descriptor accepts standard tensor [B, CH, H, W], while patches are [B, N, CH, H, W] shape
+ # So we need to reshape a bit :)
+ B, N, CH, H, W = patches.size()
+ return patch_descriptor(patches.view(B * N, CH, H, W)).view(B, N, -1)
+
+
+class LAFDescriptor(nn.Module):
+ r"""Module to get local descriptors, corresponding to LAFs (keypoints).
+
+ Internally uses :func:`~kornia.feature.get_laf_descriptors`.
+
+ Args:
+ patch_descriptor_module: patch descriptor module, e.g. :class:`~kornia.feature.SIFTDescriptor`
+ or :class:`~kornia.feature.HardNet`. Default: :class:`~kornia.feature.HardNet`.
+ patch_size: patch size in pixels, which descriptor expects.
+ grayscale_descriptor: ``True`` if patch_descriptor expects single-channel image.
+ """
+
+ def __init__(self,
+ patch_descriptor_module: nn.Module = HardNet(True),
+ patch_size: int = 32,
+ grayscale_descriptor: bool = True) -> None:
+ super().__init__()
+ self.descriptor = patch_descriptor_module
+ self.patch_size = patch_size
+ self.grayscale_descriptor = grayscale_descriptor
+
+ def __repr__(self) -> str:
+ return self.__class__.__name__ + '(' + \
+ 'descriptor=' + self.descriptor.__repr__() + ', ' + \
+ 'patch_size=' + str(self.patch_size) + ', ' + \
+ 'grayscale_descriptor=' + str(self.grayscale_descriptor) + ')'
+
+ def forward(self, img: torch.Tensor, lafs: torch.Tensor) -> torch.Tensor:
+ r"""Three stage local feature detection.
+
+ First the location and scale of interest points are determined by
+ detect function. Then affine shape and orientation.
+
+ Args:
+ img: image features with shape :math:`(B,C,H,W)`.
+ lafs: local affine frames :math:`(B,N,2,3)`.
+
+ Returns:
+ Local descriptors of shape :math:`(B,N,D)` where :math:`D` is descriptor size.
+ """
+ return get_laf_descriptors(img, lafs, self.descriptor, self.patch_size, self.grayscale_descriptor)
+
+
+class LocalFeature(nn.Module):
+ """Module, which combines local feature detector and descriptor.
+
+ Args:
+ detector: the detection module.
+ descriptor: the descriptor module.
+ """
+ def __init__(self,
+ detector: ScaleSpaceDetector,
+ descriptor: LAFDescriptor) -> None:
+ super().__init__()
+ self.detector = detector
+ self.descriptor = descriptor
+
+ def forward(self,
+ img: torch.Tensor,
+ mask: Optional[torch.Tensor] = None) -> Tuple[torch.Tensor,
+ torch.Tensor,
+ torch.Tensor]: # type: ignore
+ """
+ Args:
+ img: image to extract features with shape :math:`(B,C,H,W)`.
+ mask: a mask with weights where to apply the response function.
+ The shape must be the same as the input image.
+
+ 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)` where :math:`D` is descriptor size.
+ """
+ lafs, responses = self.detector(img, mask)
+ descs = self.descriptor(img, lafs)
+ return (lafs, responses, descs)
+
+
+class SIFTFeature(LocalFeature):
+ """Convenience module, which implements DoG detector + (Root)SIFT descriptor.
+
+ Still not as good as OpenCV/VLFeat because of https://github.com/kornia/kornia/pull/884, but we are working on it
+ """
+ def __init__(self,
+ num_features: int = 8000,
+ upright: bool = False,
+ rootsift: bool = True,
+ device: torch.device = torch.device('cpu')):
+ patch_size: int = 41
+ detector = ScaleSpaceDetector(num_features,
+ resp_module=BlobDoG(),
+ nms_module=ConvQuadInterp3d(10),
+ scale_pyr_module=ScalePyramid(3, 1.6, 32, double_image=True),
+ ori_module=PassLAF() if upright else LAFOrienter(19),
+ scale_space_response=True,
+ minima_are_also_good=True,
+ mr_size=6.0).to(device)
+ descriptor = LAFDescriptor(SIFTDescriptor(patch_size=patch_size, rootsift=rootsift),
+ patch_size=patch_size,
+ grayscale_descriptor=True).to(device)
+ super().__init__(detector, descriptor)
+
+
+class GFTTAffNetHardNet(LocalFeature):
+ """Convenience module, which implements GFTT detector + AffNet-HardNet descriptor."""
+ def __init__(self,
+ num_features: int = 8000,
+ upright: bool = False,
+ device: torch.device = torch.device('cpu')):
+ detector = ScaleSpaceDetector(num_features,
+ resp_module=CornerGFTT(),
+ nms_module=ConvQuadInterp3d(10, 1e-5),
+ scale_pyr_module=ScalePyramid(3, 1.6, 32, double_image=False),
+ ori_module=PassLAF() if upright else LAFOrienter(19),
+ aff_module=LAFAffNetShapeEstimator(True).eval(),
+ mr_size=6.0).to(device)
+ descriptor = LAFDescriptor(HardNet(True).eval(),
+ patch_size=32,
+ grayscale_descriptor=True).to(device)
+ super().__init__(detector, descriptor)
+
+
+class LocalFeatureMatcher(nn.Module):
+ r"""Module, which finds correspondences between two images based on local features.
+
+ Args:
+ local_feature: Local feature detector. See :class:`~kornia.feature.GFTTAffNetHardNet`.
+ matcher: Descriptor matcher, see :class:`~kornia.feature.DescriptorMatcher`.
+
+ Returns:
+ Dict[str, torch.Tensor]: Dictionary with image correspondences and confidence scores.
+
+ Example:
+ >>> img1 = torch.rand(1, 1, 320, 200)
+ >>> img2 = torch.rand(1, 1, 128, 128)
+ >>> input = {"image0": img1, "image1": img2}
+ >>> gftt_hardnet_matcher = LocalFeatureMatcher(
+ ... GFTTAffNetHardNet(10), kornia.feature.DescriptorMatcher('snn', 0.8)
+ ... )
+ >>> out = gftt_hardnet_matcher(input)
+ """
+
+ def __init__(self, local_feature: nn.Module, matcher: nn.Module) -> None:
+ super().__init__()
+ self.local_feature = local_feature
+ self.matcher = matcher
+ self.eval()
+
+ def extract_features(self,
+ image: torch.Tensor,
+ mask: Optional[torch.Tensor] = None) -> Dict[str, torch.Tensor]:
+ """Function for feature extraction from simple image."""
+ lafs0, resps0, descs0 = self.local_feature(image, mask)
+ return {"lafs": lafs0, "responses": resps0, "descriptors": descs0}
+
+ def no_match_output(self, device: torch.device, dtype: torch.dtype) -> dict:
+ return {
+ 'keypoints0': torch.empty(0, 2, device=device, dtype=dtype),
+ 'keypoints1': torch.empty(0, 2, device=device, dtype=dtype),
+ 'lafs0': torch.empty(0, 0, 2, 3, device=device, dtype=dtype),
+ 'lafs1': torch.empty(0, 0, 2, 3, device=device, dtype=dtype),
+ 'confidence': torch.empty(0, device=device, dtype=dtype),
+ 'batch_indexes': torch.empty(0, device=device, dtype=torch.long)
+ }
+
+ def forward(self, data: Dict[str, torch.Tensor]) -> Dict[str, torch.Tensor]:
+ """
+ Args:
+ data: dictionary containing the input data in the following format:
+
+ Keyword Args:
+ image0: left image with shape :math:`(N, 1, H1, W1)`.
+ image1: right image with shape :math:`(N, 1, H2, W2)`.
+ mask0 (optional): left image mask. '0' indicates a padded position :math:`(N, H1, W1)`.
+ mask1 (optional): right image mask. '0' indicates a padded position :math:`(N, H2, W2)`.
+
+ Returns:
+ - ``keypoints0``, matching keypoints from image0 :math:`(NC, 2)`.
+ - ``keypoints1``, matching keypoints from image1 :math:`(NC, 2)`.
+ - ``confidence``, confidence score [0, 1] :math:`(NC)`.
+ - ``lafs0``, matching LAFs from image0 :math:`(1, NC, 2, 3)`.
+ - ``lafs1``, matching LAFs from image1 :math:`(1, NC, 2, 3)`.
+ - ``batch_indexes``, batch indexes for the keypoints and lafs :math:`(NC)`.
+ """
+ num_image_pairs: int = data['image0'].shape[0]
+
+ if ('lafs0' not in data.keys()) or ('descriptors0' not in data.keys()):
+ # One can supply pre-extracted local features
+ feats_dict0: Dict[str, torch.Tensor] = self.extract_features(data['image0'])
+ lafs0, descs0 = feats_dict0['lafs'], feats_dict0['descriptors']
+ else:
+ lafs0, descs0 = data['lafs0'], data['descriptors0']
+
+ if ('lafs1' not in data.keys()) or ('descriptors1' not in data.keys()):
+ feats_dict1: Dict[str, torch.Tensor] = self.extract_features(data['image1'])
+ lafs1, descs1 = feats_dict1['lafs'], feats_dict1['descriptors']
+ else:
+ lafs1, descs1 = data['lafs1'], data['descriptors1']
+
+ keypoints0: torch.Tensor = get_laf_center(lafs0)
+ keypoints1: torch.Tensor = get_laf_center(lafs1)
+
+ out_keypoints0: List[torch.Tensor] = []
+ out_keypoints1: List[torch.Tensor] = []
+ out_confidence: List[torch.Tensor] = []
+ out_batch_indexes: List[torch.Tensor] = []
+ out_lafs0: List[torch.Tensor] = []
+ out_lafs1: List[torch.Tensor] = []
+
+ for batch_idx in range(num_image_pairs):
+ dists, idxs = self.matcher(descs0[batch_idx], descs1[batch_idx])
+ if len(idxs) == 0:
+ continue
+
+ current_keypoints_0 = keypoints0[batch_idx, idxs[:, 0]]
+ current_keypoints_1 = keypoints1[batch_idx, idxs[:, 1]]
+ current_lafs_0 = lafs0[batch_idx, idxs[:, 0]]
+ current_lafs_1 = lafs1[batch_idx, idxs[:, 1]]
+
+ out_confidence.append(1.0 - dists)
+ batch_idxs = batch_idx * torch.ones(len(dists),
+ device=keypoints0.device,
+ dtype=torch.long)
+ out_keypoints0.append(current_keypoints_0)
+ out_keypoints1.append(current_keypoints_1)
+ out_lafs0.append(current_lafs_0)
+ out_lafs1.append(current_lafs_1)
+ out_batch_indexes.append(batch_idxs)
+
+ if len(out_batch_indexes) == 0:
+ return self.no_match_output(data['image0'].device,
+ data['image0'].dtype)
+
+ return {
+ 'keypoints0': torch.cat(out_keypoints0, dim=0).view(-1, 2),
+ 'keypoints1': torch.cat(out_keypoints1, dim=0).view(-1, 2),
+ 'lafs0': torch.cat(out_lafs0, dim=0).view(1, -1, 2, 3),
+ 'lafs1': torch.cat(out_lafs1, dim=0).view(1, -1, 2, 3),
+ 'confidence': torch.cat(out_confidence, dim=0).view(-1),
+ 'batch_indexes': torch.cat(out_batch_indexes, dim=0).view(-1)
+ }
diff --git a/kornia/feature/loftr/loftr.py b/kornia/feature/loftr/loftr.py
index 3f38a20b3..4617c389d 100644
--- a/kornia/feature/loftr/loftr.py
+++ b/kornia/feature/loftr/loftr.py
@@ -52,8 +52,10 @@ default_cfg = {'backbone_type': 'ResNetFPN',
class LoFTR(nn.Module):
r"""Module, which finds correspondences between two images.
+
This is based on the original code from paper "LoFTR: Detector-Free Local
Feature Matching with Transformers". See :cite:`LoFTR2021` for more details.
+
If the distance matrix dm is not provided, :py:func:`torch.cdist` is used.
Args:
@@ -65,7 +67,6 @@ class LoFTR(nn.Module):
Returns:
Dictionary with image correspondences and confidence scores.
-
Example:
>>> img1 = torch.rand(1, 1, 320, 200)
>>> img2 = torch.rand(1, 1, 128, 128)
@@ -97,22 +98,22 @@ class LoFTR(nn.Module):
self.load_state_dict(pretrained_dict['state_dict'])
self.eval()
- def forward(self, data: Dict) -> Dict:
+ def forward(self, data: dict) -> Dict[str, torch.Tensor]:
"""
Args:
- data: {
- 'image0': (torch.Tensor): (N, 1, H1, W1)
- 'image1': (torch.Tensor): (N, 1, H2, W2)
- 'mask0'(optional) : (torch.Tensor): (N, H1, W1) '0' indicates a padded position
- 'mask1'(optional) : (torch.Tensor): (N, H2, W2)
- }
+ data: dictionary containing the input data in the following format:
+
+ Keyword Args:
+ image0: left image with shape :math:`(N, 1, H1, W1)`.
+ image1: right image with shape :math:`(N, 1, H2, W2)`.
+ mask0 (optional): left image mask. '0' indicates a padded position :math:`(N, H1, W1)`.
+ mask1 (optional): right image mask. '0' indicates a padded position :math:`(N, H2, W2)`.
+
Returns:
- out: {
- "keypoints0": (torch.Tensor): (NC, 2) matching keypoints from image0
- "keypoints1": (torch.Tensor): (NC, 2) matching keypoints from image1
- "confidence": (torch.Tensor): (NC) - confidence score [0, 1]
- "batch_indexes": (torch.Tensor): (NC) - batch indexes for the keypoints
- }
+ - ``keypoints0``, matching keypoints from image0 :math:`(NC, 2)`.
+ - ``keypoints1``, matching keypoints from image1 :math:`(NC, 2)`.
+ - ``confidence``, confidence score [0, 1] :math:`(NC)`.
+ - ``batch_indexes``, batch indexes for the keypoints and lafs :math:`(NC)`.
"""
# 1. Local Feature CNN
diff --git a/kornia/feature/loftr/utils/coarse_matching.py b/kornia/feature/loftr/utils/coarse_matching.py
index 064cd97ac..4aa11224d 100644
--- a/kornia/feature/loftr/utils/coarse_matching.py
+++ b/kornia/feature/loftr/utils/coarse_matching.py
@@ -262,8 +262,8 @@ class CoarseMatching(nn.Module):
coarse_matches.update({
'gt_mask': mconf == 0,
'm_bids': b_ids[mconf != 0], # mconf == 0 => gt matches
- 'mkpts0_c': mkpts0_c[mconf != 0],
- 'mkpts1_c': mkpts1_c[mconf != 0],
+ 'mkpts0_c': mkpts0_c[mconf != 0].to(dtype=conf_matrix.dtype),
+ 'mkpts1_c': mkpts1_c[mconf != 0].to(dtype=conf_matrix.dtype),
'mconf': mconf[mconf != 0]
})
diff --git a/kornia/feature/loftr/utils/fine_matching.py b/kornia/feature/loftr/utils/fine_matching.py
index dbe3b6194..711d39a19 100644
--- a/kornia/feature/loftr/utils/fine_matching.py
+++ b/kornia/feature/loftr/utils/fine_matching.py
@@ -36,7 +36,7 @@ class FineMatching(nn.Module):
raise ValueError("M >0, when training, see coarse_matching.py")
# logger.warning('No matches found in coarse-level.')
data.update({
- 'expec_f': torch.empty(0, 3, device=feat_f0.device),
+ 'expec_f': torch.empty(0, 3, device=feat_f0.device, dtype=feat_f0.dtype),
'mkpts0_f': data['mkpts0_c'],
'mkpts1_f': data['mkpts1_c'],
})
@@ -49,7 +49,9 @@ class FineMatching(nn.Module):
# compute coordinates from heatmap
coords_normalized = dsnt.spatial_expectation2d(heatmap[None], True)[0] # [M, 2]
- grid_normalized = create_meshgrid(W, W, True, heatmap.device).reshape(1, -1, 2) # [1, WW, 2]
+ grid_normalized = create_meshgrid(
+ W, W, normalized_coordinates=True, device=heatmap.device, dtype=heatmap.dtype
+ ).reshape(1, -1, 2) # [1, WW, 2]
# compute std over <x, y>
var = torch.sum(grid_normalized**2 * heatmap.view(-1, WW, 1), dim=1) - coords_normalized**2 # [M, 2]
diff --git a/kornia/feature/matching.py b/kornia/feature/matching.py
index 9538057f1..cee95f33b 100644
--- a/kornia/feature/matching.py
+++ b/kornia/feature/matching.py
@@ -1,6 +1,9 @@
-from typing import Optional, Tuple
+from typing import Dict, List, Optional, Tuple
import torch
+import torch.nn as nn
+
+from kornia.feature import extract_patches_from_pyramid, get_laf_center
def match_nn(
@@ -167,7 +170,7 @@ def match_smnn(
if len(dists2) > 0 and len(dists1) > 0:
idx2 = idx2.flip(1)
- idxs_dm = torch.cdist(idx1.float(), idx2.float(), p=1)
+ idxs_dm = torch.cdist(idx1.float(), idx2.float(), p=1.0)
mutual_idxs1 = idxs_dm.min(dim=1)[0] < 1e-8
mutual_idxs2 = idxs_dm.min(dim=0)[0] < 1e-8
good_idxs1 = idx1[mutual_idxs1.view(-1)]
@@ -182,3 +185,47 @@ def match_smnn(
else:
matches_idxs, match_dists = torch.empty(0, 2, device=dm.device), torch.empty(0, 1, device=dm.device)
return match_dists.view(-1, 1), matches_idxs.view(-1, 2)
+
+
+class DescriptorMatcher(nn.Module):
+ """Module version of matching functions.
+
+ See :func:`~kornia.feature.match_nn`, :func:`~kornia.feature.match_snn`,
+ :func:`~kornia.feature.match_mnn` or :func:`~kornia.feature.match_smnn` for more details.
+
+ Args:
+ match_mode: type of matching, can be `nn`, `snn`, `mnn`, `smnn`.
+ th: threshold on distance ratio, or other quality measure.
+ """
+ known_modes = ['nn', 'mnn', 'snn', 'smnn']
+
+ def __init__(self, match_mode: str = 'snn', th: float = 0.8) -> None:
+ super().__init__()
+ _match_mode: str = match_mode.lower()
+ if _match_mode not in self.known_modes:
+ raise NotImplementedError(f"{match_mode} is not supported. Try one of {self.known_modes}")
+ self.match_mode = _match_mode
+ self.th = th
+
+ def forward(self, desc1: torch.Tensor, desc2: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
+ """
+ Args:
+ desc1: Batch of descriptors of a shape :math:`(B1, D)`.
+ desc2: Batch of descriptors of a shape :math:`(B2, D)`.
+
+ Return:
+ - Descriptor distance of matching descriptors, shape of :math:`(B3, 1)`.
+ - Long tensor indexes of matching descriptors in desc1 and desc2,
+ shape of :math:`(B3, 2)` where :math:`0 <= B3 <= B1`.
+ """
+ if self.match_mode == 'nn':
+ out = match_nn(desc1, desc2)
+ elif self.match_mode == 'mnn':
+ out = match_mnn(desc1, desc2)
+ elif self.match_mode == 'snn':
+ out = match_snn(desc1, desc2, self.th)
+ elif self.match_mode == 'smnn':
+ out = match_smnn(desc1, desc2, self.th)
+ else:
+ raise NotImplementedError
+ return out
diff --git a/kornia/feature/mkd.py b/kornia/feature/mkd.py
index 22b143eb5..5ff9eb8cd 100644
--- a/kornia/feature/mkd.py
+++ b/kornia/feature/mkd.py
@@ -659,7 +659,7 @@ class SimpleKD(nn.Module):
relative: bool = kernel_type == 'polar'
sigma: float = 1.4 * (patch_size / 64)
-
+ self.patch_size = patch_size
# Sequence of modules.
smoothing = GaussianBlur2d((5, 5), (sigma, sigma), 'replicate')
gradients = MKDGradients()
diff --git a/kornia/feature/orientation.py b/kornia/feature/orientation.py
index 4f27f8d21..9efa6e1a3 100644
--- a/kornia/feature/orientation.py
+++ b/kornia/feature/orientation.py
@@ -6,7 +6,7 @@ import torch.nn as nn
import torch.nn.functional as F
from kornia.constants import pi
-from kornia.feature import (
+from kornia.feature.laf import (
extract_patches_from_pyramid,
get_laf_orientation,
raise_error_if_laf_is_not_valid,
@@ -39,8 +39,8 @@ class PatchDominantGradientOrientation(nn.Module):
Zero angle points towards right.
Args:
- patch_size:
- num_angular_bins:
+ patch_size: size of the (square) input patch.
+ num_angular_bins: number of histogram bins.
eps: for safe division, and arctan.
"""
@@ -72,7 +72,7 @@ class PatchDominantGradientOrientation(nn.Module):
def forward(self, patch: torch.Tensor) -> torch.Tensor:
"""Args:
- patch: (torch.Tensor) shape [Bx1xHxW]
+ patch: shape [Bx1xHxW]
Returns:
torch.Tensor: angle shape [B]"""
if not isinstance(patch, torch.Tensor):
diff --git a/kornia/feature/scale_space_detector.py b/kornia/feature/scale_space_detector.py
index 4b57d8653..a68d6c458 100644
--- a/kornia/feature/scale_space_detector.py
+++ b/kornia/feature/scale_space_detector.py
@@ -130,11 +130,10 @@ class ScaleSpaceDetector(nn.Module):
dev: torch.device = img.device
dtype: torch.dtype = img.dtype
sp, sigmas, _ = self.scale_pyr(img)
- all_responses = []
- all_lafs = []
+ all_responses: List[torch.Tensor] = []
+ all_lafs: List[torch.Tensor] = []
for oct_idx, octave in enumerate(sp):
sigmas_oct = sigmas[oct_idx]
-
B, CH, L, H, W = octave.size()
# Run response function
if self.scale_space_response:
diff --git a/kornia/feature/siftdesc.py b/kornia/feature/siftdesc.py
index 33beb7050..d69a2eac0 100644
--- a/kornia/feature/siftdesc.py
+++ b/kornia/feature/siftdesc.py
@@ -62,8 +62,8 @@ class SIFTDescriptor(nn.Module):
SIFT descriptor of the patches with shape.
Shape:
- - Input: (B, 1, num_spatial_bins, num_spatial_bins)
- - Output: (B, num_ang_bins * num_spatial_bins ** 2)
+ - Input: :math:`(B, 1, \text{num_spatial_bins}, \text{num_spatial_bins})`
+ - Output: :math:`(B, \text{num_ang_bins * num_spatial_bins ** 2})`
Example:
>>> input = torch.rand(23, 1, 32, 32)
diff --git a/kornia/feature/sosnet.py b/kornia/feature/sosnet.py
index 762b88ba4..e4acabb28 100644
--- a/kornia/feature/sosnet.py
+++ b/kornia/feature/sosnet.py
@@ -18,18 +18,18 @@ class SOSNet(nn.Module):
pretrained: Download and set pretrained weights to the model.
Shape:
- - Input: (B, 1, 32, 32)
- - Output: (B, 128)
+ - Input: :math:`(B, 1, 32, 32)`
+ - Output: :math:`(B, 128)`
Examples:
>>> input = torch.rand(8, 1, 32, 32)
>>> sosnet = SOSNet()
>>> descs = sosnet(input) # 8x128
"""
+ patch_size = 32
def __init__(self, pretrained: bool = False) -> None:
super().__init__()
-
self.layers = nn.Sequential(
nn.InstanceNorm2d(1, affine=False),
nn.Conv2d(1, 32, kernel_size=3, padding=1, bias=False),
diff --git a/kornia/feature/tfeat.py b/kornia/feature/tfeat.py
index bf094aafd..2ca4b4e09 100644
--- a/kornia/feature/tfeat.py
+++ b/kornia/feature/tfeat.py
@@ -26,17 +26,18 @@ class TFeat(nn.Module):
pretrained: Download and set pretrained weights to the model.
Returns:
- TFeat descriptor of the patches.
+ torch.Tensor: TFeat descriptor of the patches.
Shape:
- - Input: (B, 1, 32, 32)
- - Output: (B, 128)
+ - Input: :math:`(B, 1, 32, 32)`
+ - Output: :math:`(B, 128)`
Examples:
>>> input = torch.rand(16, 1, 32, 32)
>>> tfeat = TFeat()
>>> descs = tfeat(input) # 16x128
"""
+ patch_size = 32
def __init__(self, pretrained: bool = False) -> None:
super().__init__()
diff --git a/kornia/geometry/ransac.py b/kornia/geometry/ransac.py
index 258b6803e..931d70aa1 100644
--- a/kornia/geometry/ransac.py
+++ b/kornia/geometry/ransac.py
@@ -1,6 +1,6 @@
"""Module containing RANSAC modules."""
import math
-from typing import Optional, Tuple, Union
+from typing import Optional, Tuple
import torch
import torch.nn as nn
@@ -24,23 +24,19 @@ class RANSAC(nn.Module):
Args:
model_type: type of model to estimate, e.g. "homography" or "fundamental".
+ inliers_threshold: threshold for the correspondence to be an inlier.
batch_size: number of generated samples at once.
max_iterations: maximum batches to generate. Actual number of models to try is ``batch_size * max_iterations``.
- inliers_threshold: threshold for the correspondence to be an inlier.
confidence: desired confidence of the result, used for the early stopping.
max_local_iterations: number of local optimization (polishing) iterations.
-
- Returns:
- - estimated model, shape of :math:`(3, 3)`.
- - the inlier/outlier mask, shape of :math:`(1, N), where N is number of input correspondences`.
"""
supported_models = ['homography', 'fundamental']
def __init__(self,
model_type: str = 'homography',
+ inl_th: float = 2.0,
batch_size: int = 2048,
max_iter: int = 10,
- inl_th: float = 2.0,
confidence: float = 0.99,
max_lo_iters: int = 5):
super().__init__()
@@ -139,7 +135,7 @@ class RANSAC(nn.Module):
kp1: torch.Tensor,
kp2: torch.Tensor,
inliers: torch.Tensor) -> torch.Tensor:
- # ToDo: Replace this with MAGSAC++ polisher
+ # TODO: Replace this with MAGSAC++ polisher
kp1_inl = kp1[inliers][None]
kp2_inl = kp2[inliers][None]
num_inl = kp1_inl.size(1)
@@ -155,15 +151,16 @@ class RANSAC(nn.Module):
kp1: torch.Tensor,
kp2: torch.Tensor,
weights: Optional[torch.Tensor] = None) -> Tuple[torch.Tensor, torch.Tensor]:
- """Main forward method to execute the RANSAC algorithm.
- Args:
- kp1 (torch.Tensor): source image keypoints :math:`(N, 2)`.
- kp2 (torch.Tensor): distance image keypoints :math:`(N, 2)`.
- weights (torch.Tensor): optional correspondences weights. Not used now
-
- Returns:
- - estimated model, shape of :math:`(1, 3, 3)`.
- - the inlier/outlier mask, shape of :math:`(1, N), where N is number of input correspondences`.
+ r"""Main forward method to execute the RANSAC algorithm.
+
+ Args:
+ kp1 (torch.Tensor): source image keypoints :math:`(N, 2)`.
+ kp2 (torch.Tensor): distance image keypoints :math:`(N, 2)`.
+ weights (torch.Tensor): optional correspondences weights. Not used now
+
+ Returns:
+ - Estimated model, shape of :math:`(1, 3, 3)`.
+ - The inlier/outlier mask, shape of :math:`(1, N)`, where N is number of input correspondences.
"""
if not isinstance(kp1, torch.Tensor):
raise TypeError(f"Input kp1 is not torch.Tensor. Got {type(kp1)}")
@@ -178,7 +175,7 @@ class RANSAC(nn.Module):
equal shape at at least [{self.minimal_sample_size}, 2], \
got {kp1.shape}, {kp2.shape}")
- best_score_total: float = 1.0
+ best_score_total: float = float(self.minimal_sample_size)
num_tc: int = len(kp1)
best_model_total = torch.zeros(3, 3, dtype=kp1.dtype, device=kp1.device)
inliers_best_total: torch.Tensor = torch.zeros(num_tc, 1, device=kp1.device, dtype=torch.bool)
@@ -192,7 +189,7 @@ class RANSAC(nn.Module):
# Estimate models
models = self.estimate_model_from_minsample(kp1_sampled, kp2_sampled)
models = self.remove_bad_models(models)
- if models is None:
+ if (models is None) or (len(models) == 0):
continue
# Score the models and select the best one
model, inliers, model_score = self.verify(kp1, kp2, models, self.inl_th)
@@ -201,6 +198,8 @@ class RANSAC(nn.Module):
# Local optimization
for lo_step in range(self.max_lo_iters):
model_lo = self.polish_model(kp1, kp2, inliers)
+ if (model_lo is None) or (len(model_lo) == 0):
+ continue
_, inliers_lo, score_lo = self.verify(kp1, kp2, model_lo, self.inl_th)
# print (f"Orig score = {best_model_score}, LO score = {score_lo} TC={num_tc}")
if score_lo > model_score:
diff --git a/kornia/testing/__init__.py b/kornia/testing/__init__.py
index a15fe048f..d75af0fbc 100644
--- a/kornia/testing/__init__.py
+++ b/kornia/testing/__init__.py
@@ -41,6 +41,13 @@ def tensor_to_gradcheck_var(tensor, dtype=torch.float64, requires_grad=True):
return tensor.requires_grad_(requires_grad).type(dtype)
+def dict_to(data: dict, device: torch.device, dtype: torch.dtype) -> dict:
+ out: dict = {}
+ for key, val in data.items():
+ out[key] = val.to(device, dtype) if isinstance(val, torch.Tensor) else val
+ return out
+
+
def compute_patch_error(x, y, h, w):
"""Compute the absolute error between patches."""
return torch.abs(x - y)[..., h // 4 : -h // 4, w // 4 : -w // 4].mean()
@@ -152,7 +159,6 @@ try:
return _assert_close(actual, expected, rtol=rtol, atol=atol, check_stride=False, equal_nan=True, **kwargs)
-
except ImportError:
# Partial backport of torch.testing.assert_close for torch<1.9
# TODO: remove this branch if kornia relies on torch>=1.9
diff --git a/kornia/tracking/__init__.py b/kornia/tracking/__init__.py
new file mode 100644
index 000000000..d9140dc93
--- /dev/null
+++ b/kornia/tracking/__init__.py
@@ -0,0 +1 @@
+from .planar_tracker import *
diff --git a/kornia/tracking/planar_tracker.py b/kornia/tracking/planar_tracker.py
new file mode 100644
index 000000000..a6fe0ffd3
--- /dev/null
+++ b/kornia/tracking/planar_tracker.py
@@ -0,0 +1,121 @@
+from typing import Dict, Optional, Tuple, Union
+
+import torch
+import torch.nn as nn
+
+from kornia.feature import DescriptorMatcher, GFTTAffNetHardNet, LocalFeatureMatcher, LoFTR
+from kornia.geometry.linalg import transform_points
+from kornia.geometry.ransac import RANSAC
+from kornia.geometry.transform.imgwarp import warp_perspective
+
+__all__ = [
+ "HomographyTracker",
+]
+
+
+class HomographyTracker(nn.Module):
+ r"""Module, which performs local-feature-based tracking of the target planar object in the
+ sequence of the frames.
+
+ Args:
+ initial_matcher: image matching module, e.g. :class:`~kornia.feature.LocalFeatureMatcher`
+ or :class:`~kornia.feature.LoFTR`. Default: :class:`~kornia.feature.GFTTAffNetHardNet`.
+ fast_matcher: fast image matching module, e.g. :class:`~kornia.feature.LocalFeatureMatcher`
+ or :class:`~kornia.feature.LoFTR`. Default: :class:`~kornia.feature.DescriptorMatcher`.
+ ransac: homography estimation module. Default: :class:`~kornia.geometry.RANSAC`.
+ minimum_inliers_num: threshold for number inliers for matching to be successful.
+ """
+ def __init__(self,
+ initial_matcher=LocalFeatureMatcher(GFTTAffNetHardNet(3000),
+ DescriptorMatcher('smnn', 0.95)),
+ fast_matcher=LoFTR('outdoor'),
+ ransac=RANSAC('homography',
+ inl_th=5.0,
+ batch_size=4096,
+ max_iter=10,
+ max_lo_iters=10),
+ minimum_inliers_num: int = 30) -> None:
+ super().__init__()
+ self.initial_matcher = initial_matcher
+ self.fast_matcher = fast_matcher
+ self.ransac = ransac
+ self.minimum_inliers_num = minimum_inliers_num
+ self.reset_tracking()
+
+ # placeholders
+ self.target: torch.Tensor
+ self.target_initial_representation: dict
+ self.target_fast_representation: dict
+ self.previous_homography: Optional[torch.Tensor]
+
+ def set_target(self, target: torch.Tensor) -> None:
+ self.target = target
+ self.target_initial_representation = {}
+ self.target_fast_representation = {}
+ if hasattr(self.initial_matcher, 'extract_features'):
+ self.target_initial_representation = self.initial_matcher.extract_features(target)
+ if hasattr(self.fast_matcher, 'extract_features'):
+ self.target_fast_representation = self.fast_matcher.extract_features(target)
+
+ def reset_tracking(self) -> None:
+ self.previous_homography = None
+
+ def no_match(self) -> Tuple[torch.Tensor, bool]:
+ return torch.empty(3, 3), False
+
+ def match_initial(self, x: torch.Tensor) -> Tuple[torch.Tensor, bool]:
+ """The frame `x` is matched with initial_matcher and verified with ransac."""
+ input_dict: Dict[str, torch.Tensor] = {"image0": self.target, "image1": x}
+
+ for k, v in self.target_initial_representation.items():
+ input_dict[f'{k}0'] = v
+
+ match_dict = self.initial_matcher(input_dict)
+ keypoints0 = match_dict['keypoints0'][match_dict['batch_indexes'] == 0]
+ keypoints1 = match_dict['keypoints1'][match_dict['batch_indexes'] == 0]
+
+ if len(keypoints0) < self.minimum_inliers_num:
+ return self.no_match()
+ H, inliers = self.ransac(keypoints0, keypoints1)
+
+ if inliers.sum().item() < self.minimum_inliers_num:
+ return self.no_match()
+ self.previous_homography = H.clone()
+
+ return H, True
+
+ def track_next_frame(self, x: torch.Tensor) -> Tuple[torch.Tensor, bool]:
+ """The frame `x` is prewarped according to the previous frame homography, matched with fast_matcher
+ verified with ransac."""
+ if self.previous_homography is not None: # mypy, shut up
+ Hwarp = self.previous_homography.clone()[None]
+ # make a bit of border for safety
+ Hwarp[:, 0:2, 0:2] = Hwarp[:, 0:2, 0:2] / 0.8
+ Hwarp[:, 0:2, 2] -= 10.0
+ Hinv = torch.inverse(Hwarp)
+ h, w = self.target.shape[2:]
+ frame_warped = warp_perspective(x, Hinv, (h, w))
+ input_dict = {"image0": self.target,
+ "image1": frame_warped}
+ for k, v in self.target_fast_representation.items():
+ input_dict[f'{k}0'] = v
+
+ match_dict = self.fast_matcher(input_dict)
+ keypoints0 = match_dict['keypoints0'][match_dict['batch_indexes'] == 0]
+ keypoints1 = match_dict['keypoints1'][match_dict['batch_indexes'] == 0]
+ keypoints1 = transform_points(Hwarp, keypoints1)
+
+ if len(keypoints0) < self.minimum_inliers_num:
+ self.reset_tracking()
+ return self.no_match()
+ H, inliers = self.ransac(keypoints0, keypoints1)
+ if inliers.sum().item() < self.minimum_inliers_num:
+ self.reset_tracking()
+ return self.no_match()
+ self.previous_homography = H.clone()
+ return H, True
+
+ def forward(self, x: torch.Tensor) -> Tuple[torch.Tensor, bool]:
+ if self.previous_homography is not None:
+ return self.track_next_frame(x)
+ return self.match_initial(x)
diff --git a/test/feature/test_integrated.py b/test/feature/test_integrated.py
new file mode 100644
index 000000000..9d4adfc06
--- /dev/null
+++ b/test/feature/test_integrated.py
@@ -0,0 +1,321 @@
+import pytest
+import torch
+import torch.nn as nn
+from torch.autograd import gradcheck
+
+import kornia
+import kornia.testing as utils # test utils
+from kornia.feature import (
+ DescriptorMatcher,
+ extract_patches_from_pyramid,
+ get_laf_descriptors,
+ GFTTAffNetHardNet,
+ LAFDescriptor,
+ LocalFeature,
+ ScaleSpaceDetector,
+ SIFTDescriptor,
+ SIFTFeature,
+)
+from kornia.feature.integrated import LocalFeatureMatcher
+from kornia.geometry import RANSAC, resize, transform_points
+from kornia.testing import assert_close
+
+
+class TestGetLAFDescriptors:
+ def test_same(self, device, dtype):
+ B, C, H, W = 1, 3, 64, 64
+ PS = 16
+ img = torch.rand(B, C, H, W, device=device, dtype=dtype)
+ img_gray = kornia.color.rgb_to_grayscale(img)
+ centers = torch.tensor([[H / 3.0, W / 3.],
+ [2.0 * H / 3.0, W / 2.]],
+ device=device,
+ dtype=dtype).view(1, 2, 2)
+ scales = torch.tensor([(H + W) / 4.0, (H + W) / 8.0],
+ device=device,
+ dtype=dtype).view(1, 2, 1, 1)
+ ori = torch.tensor([0.0, 30.],
+ device=device,
+ dtype=dtype).view(1, 2, 1)
+ lafs = kornia.feature.laf_from_center_scale_ori(centers, scales, ori)
+ sift = SIFTDescriptor(PS).to(device, dtype)
+ descs_test_from_rgb = get_laf_descriptors(img, lafs, sift, PS, True)
+ descs_test_from_gray = get_laf_descriptors(img_gray,
+ lafs, sift, PS, True)
+
+ patches = extract_patches_from_pyramid(img_gray, lafs, PS)
+ B1, N1, CH1, H1, W1 = patches.size()
+ # Descriptor accepts standard tensor [B, CH, H, W], while patches are [B, N, CH, H, W] shape
+ # So we need to reshape a bit :)
+ descs_reference = sift(patches.view(B1 * N1, CH1, H1, W1)).view(B1, N1, -1)
+ assert_close(descs_test_from_rgb, descs_reference)
+ assert_close(descs_test_from_gray, descs_reference)
+
+ def test_gradcheck(self, device):
+ B, C, H, W = 1, 1, 32, 32
+ dtype = torch.double
+ PS = 16
+ img = torch.rand(B, C, H, W, device=device)
+ centers = torch.tensor([[H / 3.0, W / 3.],
+ [2.0 * H / 3.0, W / 2.]],
+ device=device,
+ dtype=torch.double).view(1, 2, 2)
+ scales = torch.tensor([(H + W) / 4.0, (H + W) / 8.0],
+ device=device, dtype=torch.double).view(1, 2, 1, 1)
+ ori = torch.tensor([0.0, 30.],
+ device=device,
+ dtype=dtype).view(1, 2, 1)
+ lafs = kornia.feature.laf_from_center_scale_ori(centers, scales, ori)
+ img = utils.tensor_to_gradcheck_var(img) # to var
+ lafs = utils.tensor_to_gradcheck_var(lafs) # to var
+
+ class _MeanPatch(nn.Module):
+ def forward(self, inputs):
+ return inputs.mean(dim=(2, 3))
+
+ desc = _MeanPatch()
+ img = utils.tensor_to_gradcheck_var(img) # to var
+ assert gradcheck(get_laf_descriptors,
+ (img, lafs, desc, PS, True),
+ eps=1e-3, atol=1e-3, raise_exception=True)
+
+
+class TestLAFDescriptor:
+ def test_same(self, device, dtype):
+ B, C, H, W = 1, 3, 64, 64
+ PS = 16
+ img = torch.rand(B, C, H, W, device=device, dtype=dtype)
+ img_gray = kornia.color.rgb_to_grayscale(img)
+ centers = torch.tensor([[H / 3.0, W / 3.],
+ [2.0 * H / 3.0, W / 2.]],
+ device=device,
+ dtype=dtype).view(1, 2, 2)
+ scales = torch.tensor([(H + W) / 4.0, (H + W) / 8.0],
+ device=device,
+ dtype=dtype).view(1, 2, 1, 1)
+ ori = torch.tensor([0.0, 30.],
+ device=device,
+ dtype=dtype).view(1, 2, 1)
+ lafs = kornia.feature.laf_from_center_scale_ori(centers, scales, ori)
+ sift = SIFTDescriptor(PS).to(device, dtype)
+ lafsift = LAFDescriptor(sift, PS)
+ descs_test = lafsift(img, lafs)
+ patches = extract_patches_from_pyramid(img_gray, lafs, PS)
+ B1, N1, CH1, H1, W1 = patches.size()
+ # Descriptor accepts standard tensor [B, CH, H, W], while patches are [B, N, CH, H, W] shape
+ # So we need to reshape a bit :)
+ descs_reference = sift(patches.view(B1 * N1, CH1, H1, W1)).view(B1, N1, -1)
+ assert_close(descs_test, descs_reference)
+
+ def test_gradcheck(self, device):
+ dtype = torch.double
+ B, C, H, W = 1, 1, 32, 32
+ PS = 16
+ img = torch.rand(B, C, H, W, device=device)
+ centers = torch.tensor([[H / 3.0, W / 3.],
+ [2.0 * H / 3.0, W / 2.]],
+ device=device,
+ dtype=dtype).view(1, 2, 2)
+ scales = torch.tensor([(H + W) / 4.0, (H + W) / 8.0],
+ device=device,
+ dtype=dtype).view(1, 2, 1, 1)
+ ori = torch.tensor([0.0, 30.],
+ device=device,
+ dtype=dtype).view(1, 2, 1)
+ lafs = kornia.feature.laf_from_center_scale_ori(centers, scales, ori)
+ img = utils.tensor_to_gradcheck_var(img) # to var
+ lafs = utils.tensor_to_gradcheck_var(lafs) # to var
+
+ class _MeanPatch(nn.Module):
+ def forward(self, inputs):
+ return inputs.mean(dim=(2, 3))
+
+ lafdesc = LAFDescriptor(_MeanPatch(), PS)
+ img = utils.tensor_to_gradcheck_var(img) # to var
+ assert gradcheck(lafdesc,
+ (img, lafs),
+ eps=1e-3, atol=1e-3, raise_exception=True)
+
+
+class TestLocalFeature:
+ def test_smoke(self, device, dtype):
+ det = ScaleSpaceDetector(10)
+ desc = SIFTDescriptor(32)
+ local_feature = LocalFeature(det, desc).to(device, dtype)
+ assert local_feature is not None
+
+ def test_same(self, device, dtype):
+ B, C, H, W = 1, 1, 64, 64
+ PS = 16
+ img = torch.rand(B, C, H, W, device=device, dtype=dtype)
+ det = ScaleSpaceDetector(10)
+ desc = SIFTDescriptor(PS)
+ local_feature = LocalFeature(det, LAFDescriptor(desc, PS)).to(device, dtype)
+ lafs, responses, descs = local_feature(img)
+ lafs1, responses1 = det(img)
+ assert_close(lafs, lafs1)
+ assert_close(responses, responses1)
+ patches = extract_patches_from_pyramid(img, lafs1, PS)
+ B1, N1, CH1, H1, W1 = patches.size()
+ # Descriptor accepts standard tensor [B, CH, H, W], while patches are [B, N, CH, H, W] shape
+ # So we need to reshape a bit :)
+ descs1 = desc(patches.view(B1 * N1, CH1, H1, W1)).view(B1, N1, -1)
+ assert_close(descs, descs1)
+
+ @pytest.mark.skip("Takes too long time (but works)")
+ def test_gradcheck(self, device):
+ B, C, H, W = 1, 1, 32, 32
+ PS = 16
+ img = torch.rand(B, C, H, W, device=device)
+ local_feature = LocalFeature(ScaleSpaceDetector(2),
+ LAFDescriptor(SIFTDescriptor(PS), PS)).to(device)
+ img = utils.tensor_to_gradcheck_var(img) # to var
+ assert gradcheck(local_feature, img, eps=1e-4, atol=1e-4, raise_exception=True)
+
+
+class TestSIFTFeature:
+ # The real test is in TestLocalFeatureMatcher
+ def test_smoke(self, device, dtype):
+ sift = SIFTFeature()
+ assert sift is not None
+
+ @pytest.mark.skip("jacobian not well computed")
+ def test_gradcheck(self, device):
+ B, C, H, W = 1, 1, 32, 32
+ img = torch.rand(B, C, H, W, device=device)
+ local_feature = SIFTFeature(2, True).to(device).to(device)
+ img = utils.tensor_to_gradcheck_var(img) # to var
+ assert gradcheck(local_feature, img, eps=1e-4, atol=1e-4, raise_exception=True)
+
+
+class TestGFTTAffNetHardNet:
+ # The real test is in TestLocalFeatureMatcher
+ def test_smoke(self, device, dtype):
+ feat = GFTTAffNetHardNet().to(device, dtype)
+ assert feat is not None
+
+ @pytest.mark.skip("jacobian not well computed")
+ def test_gradcheck(self, device):
+ B, C, H, W = 1, 1, 32, 32
+ img = torch.rand(B, C, H, W, device=device)
+ local_feature = GFTTAffNetHardNet(2, True).to(device, torch.double)
+ img = utils.tensor_to_gradcheck_var(img) # to var
+ assert gradcheck(local_feature, img, eps=1e-4, atol=1e-4, raise_exception=True)
+
+
+class TestLocalFeatureMatcher:
+ def test_smoke(self, device):
+ matcher = LocalFeatureMatcher(SIFTFeature(5),
+ DescriptorMatcher('snn', 0.8)).to(device)
+ assert matcher is not None
+
+ @pytest.mark.parametrize("data", ["loftr_homo"], indirect=True)
+ def test_nomatch(self, device, dtype, data):
+ matcher = LocalFeatureMatcher(GFTTAffNetHardNet(100),
+ DescriptorMatcher('snn', 0.8)).to(device, dtype)
+ data_dev = utils.dict_to(data, device, dtype)
+ with torch.no_grad():
+ out = matcher({"image0": data_dev["image0"],
+ "image1": 0 * data_dev["image0"]})
+ assert (len(out['keypoints0']) == 0)
+
+ @pytest.mark.skip("Takes too long time (but works)")
+ def test_gradcheck(self, device):
+ matcher = LocalFeatureMatcher(SIFTFeature(5),
+ DescriptorMatcher('nn', 1.0)).to(device)
+ patches = torch.rand(1, 1, 32, 32, device=device)
+ patches05 = resize(patches, (48, 48))
+ patches = utils.tensor_to_gradcheck_var(patches) # to var
+ patches05 = utils.tensor_to_gradcheck_var(patches05) # to var
+
+ def proxy_forward(x, y):
+ return matcher({"image0": x, "image1": y})["keypoints0"]
+ assert gradcheck(proxy_forward, (patches, patches05), eps=1e-4, atol=1e-4, raise_exception=True)
+
+ @pytest.mark.parametrize("data", ["loftr_homo"], indirect=True)
+ def test_real_sift(self, device, dtype, data):
+ torch.random.manual_seed(0)
+ # This is not unit test, but that is quite good integration test
+ matcher = LocalFeatureMatcher(SIFTFeature(2000),
+ DescriptorMatcher('snn', 0.8)).to(device, dtype)
+ ransac = RANSAC('homography', 1.0, 2048, 10).to(device, dtype)
+ data_dev = utils.dict_to(data, device, dtype)
+ pts_src = data_dev['pts0']
+ pts_dst = data_dev['pts1']
+ with torch.no_grad():
+ out = matcher(data_dev)
+ homography, inliers = ransac(out['keypoints0'], out['keypoints1'])
+ assert (inliers.sum().item() > 50) # we have enough inliers
+ # Reprojection error of 5px is OK
+ assert_close(
+ transform_points(homography[None], pts_src[None]),
+ pts_dst[None],
+ rtol=5e-2,
+ atol=5)
+
+ @pytest.mark.parametrize("data", ["loftr_homo"], indirect=True)
+ def test_real_sift_preextract(self, device, dtype, data):
+ torch.random.manual_seed(0)
+ # This is not unit test, but that is quite good integration test
+ feat = SIFTFeature(2000)
+ matcher = LocalFeatureMatcher(feat,
+ DescriptorMatcher('snn', 0.8)).to(device)
+ ransac = RANSAC('homography', 1.0, 2048, 10).to(device, dtype)
+ data_dev = utils.dict_to(data, device, dtype)
+ pts_src = data_dev['pts0']
+ pts_dst = data_dev['pts1']
+
+ lafs, _, descs = feat(data_dev["image0"])
+ data_dev["lafs0"] = lafs
+ data_dev["descriptors0"] = descs
+
+ lafs2, _, descs2 = feat(data_dev["image1"])
+ data_dev["lafs1"] = lafs2
+ data_dev["descriptors1"] = descs2
+
+ with torch.no_grad():
+ out = matcher(data_dev)
+ homography, inliers = ransac(out['keypoints0'], out['keypoints1'])
+ assert (inliers.sum().item() > 50) # we have enough inliers
+ # Reprojection error of 5px is OK
+ assert_close(
+ transform_points(homography[None], pts_src[None]),
+ pts_dst[None],
+ rtol=5e-2,
+ atol=5)
+
+ @pytest.mark.parametrize("data", ["loftr_homo"], indirect=True)
+ def test_real_gftt(self, device, dtype, data):
+ torch.random.manual_seed(0)
+ # This is not unit test, but that is quite good integration test
+ matcher = LocalFeatureMatcher(GFTTAffNetHardNet(2000),
+ DescriptorMatcher('snn', 0.8)).to(device, dtype)
+ ransac = RANSAC('homography', 1.0, 2048, 10).to(device, dtype)
+ data_dev = utils.dict_to(data, device, dtype)
+ pts_src = data_dev['pts0']
+ pts_dst = data_dev['pts1']
+ with torch.no_grad():
+ out = matcher(data_dev)
+ homography, inliers = ransac(out['keypoints0'], out['keypoints1'])
+ assert (inliers.sum().item() > 50) # we have enough inliers
+ # Reprojection error of 5px is OK
+ assert_close(
+ transform_points(homography[None], pts_src[None]),
+ pts_dst[None],
+ rtol=5e-2,
+ atol=5)
+
+ @pytest.mark.skip("ScaleSpaceDetector now is not jittable")
+ def test_jit(self, device, dtype):
+ B, C, H, W = 1, 1, 32, 32
+ patches = torch.rand(B, C, H, W, device=device, dtype=dtype)
+ patches2x = resize(patches, (48, 48))
+ inputs = {"image0": patches, "image1": patches2x}
+ model = LocalFeatureMatcher(SIFTDescriptor(32),
+ DescriptorMatcher('snn', 0.8)).to(device).eval()
+ model_jit = torch.jit.script(model)
+
+ out = model(inputs)
+ out_jit = model_jit(inputs)
+ for k, v in out.items():
+ assert_close(v, out_jit[k])
diff --git a/test/feature/test_loftr.py b/test/feature/test_loftr.py
index ca4112ed0..4a4782f47 100644
--- a/test/feature/test_loftr.py
+++ b/test/feature/test_loftr.py
@@ -9,17 +9,31 @@ from kornia.testing import assert_close
class TestLoFTR:
- @pytest.mark.skipif(torch.__version__.startswith('1.6'),
- reason='1.6.0 not supporting the pretrained weights as they are packed.')
- def test_pretrained_outdoor_smoke(self, device):
- if device == torch.device('cpu'):
- loftr = LoFTR('outdoor').to(device)
-
- @pytest.mark.skipif(torch.__version__.startswith('1.6'),
- reason='1.6.0 not supporting the pretrained weights as they are packed.')
- def test_pretrained_indoor_smoke(self, device):
- if device == torch.device('cpu'):
- loftr = LoFTR('indoor').to(device)
+ def test_pretrained_outdoor_smoke(self, device, dtype):
+ loftr = LoFTR('outdoor').to(device, dtype)
+ assert loftr is not None
+
+ def test_pretrained_indoor_smoke(self, device, dtype):
+ loftr = LoFTR('indoor').to(device, dtype)
+ assert loftr is not None
+
+ @pytest.mark.parametrize("data", ["loftr_fund"], indirect=True)
+ def test_pretrained_indoor(self, device, dtype, data):
+ loftr = LoFTR('indoor').to(device, dtype)
+ data_dev = utils.dict_to(data, device, dtype)
+ with torch.no_grad():
+ out = loftr(data_dev)
+ assert_close(out['keypoints0'], data_dev["loftr_indoor_tentatives0"])
+ assert_close(out['keypoints1'], data_dev["loftr_indoor_tentatives1"])
+
+ @pytest.mark.parametrize("data", ["loftr_homo"], indirect=True)
+ def test_pretrained_outdoor(self, device, dtype, data):
+ loftr = LoFTR('outdoor').to(device, dtype)
+ data_dev = utils.dict_to(data, device, dtype)
+ with torch.no_grad():
+ out = loftr(data_dev)
+ assert_close(out['keypoints0'], data_dev["loftr_outdoor_tentatives0"])
+ assert_close(out['keypoints1'], data_dev["loftr_outdoor_tentatives1"])
@pytest.mark.skip("Takes too long time (but works)")
def test_gradcheck(self, device):
@@ -35,15 +49,14 @@ class TestLoFTR:
assert gradcheck(proxy_forward, (patches, patches05), eps=1e-4, atol=1e-4, raise_exception=True)
@pytest.mark.skip("does not like transformer.py:L99, zip iteration")
- @pytest.mark.jit
def test_jit(self, device, dtype):
B, C, H, W = 1, 1, 32, 32
patches = torch.rand(B, C, H, W, device=device, dtype=dtype)
patches2x = resize(patches, (48, 48))
input = {"image0": patches, "image1": patches2x}
model = LoFTR().to(patches.device, patches.dtype).eval()
- model_jit = torch.jit.script(LoFTR().to(patches.device, patches.dtype).eval())
+ model_jit = torch.jit.script(model)
out = model(input)
- out_jit = model(input)
+ out_jit = model_jit(input)
for k, v in out.items():
assert_close(v, out_jit[k])
diff --git a/test/feature/test_matching.py b/test/feature/test_matching.py
index 585cb6776..3223af235 100644
--- a/test/feature/test_matching.py
+++ b/test/feature/test_matching.py
@@ -1,8 +1,10 @@
import pytest
+import torch
from torch.autograd import gradcheck
import kornia.testing as utils # test utils
-from kornia.feature.matching import *
+from kornia.feature.matching import DescriptorMatcher, match_mnn, match_nn, match_smnn, match_snn
+from kornia.geometry import resize
from kornia.testing import assert_close
@@ -26,6 +28,10 @@ class TestMatchNN:
assert_close(dists, expected_dists)
assert_close(idxs, expected_idx)
+ dists1, idxs1 = match_nn(desc1, desc2)
+ assert_close(dists1, expected_dists)
+ assert_close(idxs1, expected_idx)
+
def test_gradcheck(self, device):
desc1 = torch.rand(5, 8, device=device)
desc2 = torch.rand(7, 8, device=device)
@@ -55,6 +61,10 @@ class TestMatchMNN:
expected_idx = torch.tensor([[0, 4], [1, 3], [2, 2], [3, 1], [4, 0]], device=device)
assert_close(dists, expected_dists)
assert_close(idxs, expected_idx)
+ matcher = DescriptorMatcher('mnn').to(device)
+ dists1, idxs1 = matcher(desc1, desc2)
+ assert_close(dists1, expected_dists)
+ assert_close(idxs1, expected_idx)
def test_gradcheck(self, device):
desc1 = torch.rand(5, 8, device=device)
@@ -85,6 +95,10 @@ class TestMatchSNN:
expected_idx = torch.tensor([[0, 4], [1, 3], [2, 2], [3, 1], [4, 0]], device=device)
assert_close(dists, expected_dists)
assert_close(idxs, expected_idx)
+ matcher = DescriptorMatcher('snn', 0.8).to(device)
+ dists1, idxs1 = matcher(desc1, desc2)
+ assert_close(dists1, expected_dists)
+ assert_close(idxs1, expected_idx)
def test_matching2(self, device):
desc1 = torch.tensor([[0, 0.0], [1, 1], [2, 2], [3, 3.0], [5, 5.0]], device=device)
@@ -95,6 +109,10 @@ class TestMatchSNN:
expected_idx = torch.tensor([[0, 4], [1, 3], [3, 1], [4, 0]], device=device)
assert_close(dists, expected_dists)
assert_close(idxs, expected_idx)
+ matcher = DescriptorMatcher('snn', 0.1).to(device)
+ dists1, idxs1 = matcher(desc1, desc2)
+ assert_close(dists1, expected_dists)
+ assert_close(idxs1, expected_idx)
def test_gradcheck(self, device):
desc1 = torch.rand(5, 8, device=device)
@@ -126,6 +144,10 @@ class TestMatchSMNN:
expected_idx = torch.tensor([[0, 4], [1, 3], [2, 2], [3, 1], [4, 0]], device=device)
assert_close(dists, expected_dists)
assert_close(idxs, expected_idx)
+ matcher = DescriptorMatcher('smnn', 0.8).to(device)
+ dists1, idxs1 = matcher(desc1, desc2)
+ assert_close(dists1, expected_dists)
+ assert_close(idxs1, expected_idx)
def test_matching2(self, device):
desc1 = torch.tensor([[0, 0.0], [1, 1], [2, 2], [3, 3.0], [5, 5.0]], device=device)
@@ -136,10 +158,26 @@ class TestMatchSMNN:
expected_idx = torch.tensor([[0, 4], [1, 3], [3, 1], [4, 0]], device=device)
assert_close(dists, expected_dists)
assert_close(idxs, expected_idx)
+ matcher = DescriptorMatcher('smnn', 0.1).to(device)
+ dists1, idxs1 = matcher(desc1, desc2)
+ assert_close(dists1, expected_dists)
+ assert_close(idxs1, expected_idx)
def test_gradcheck(self, device):
desc1 = torch.rand(5, 8, device=device)
desc2 = torch.rand(7, 8, device=device)
desc1 = utils.tensor_to_gradcheck_var(desc1) # to var
desc2 = utils.tensor_to_gradcheck_var(desc2) # to var
+ matcher = DescriptorMatcher('smnn', 0.8).to(device)
assert gradcheck(match_smnn, (desc1, desc2, 0.8), raise_exception=True, nondet_tol=1e-4)
+ assert gradcheck(matcher, (desc1, desc2), raise_exception=True, nondet_tol=1e-4)
+
+ @pytest.mark.jit
+ @pytest.mark.parametrize("match_type", ["nn", "snn", "mnn", "smnn"])
+ def test_jit(self, match_type, device, dtype):
+ desc1 = torch.rand(5, 8, device=device, dtype=dtype)
+ desc2 = torch.rand(7, 8, device=device, dtype=dtype)
+ matcher = DescriptorMatcher(match_type, 0.8).to(device)
+ matcher_jit = torch.jit.script(DescriptorMatcher(match_type, 0.8).to(device))
+ assert_close(matcher(desc1, desc2)[0], matcher_jit(desc1, desc2)[0])
+ assert_close(matcher(desc1, desc2)[1], matcher_jit(desc1, desc2)[1])
diff --git a/test/geometry/test_ransac.py b/test/geometry/test_ransac.py
index 1c04281c1..840efef23 100644
--- a/test/geometry/test_ransac.py
+++ b/test/geometry/test_ransac.py
@@ -7,6 +7,7 @@ from torch.autograd import gradcheck
import kornia
import kornia.testing as utils
from kornia.geometry import RANSAC
+from kornia.geometry.epipolar import sampson_epipolar_distance
from kornia.testing import assert_close
@@ -15,12 +16,14 @@ class TestRANSACHomography:
points1 = torch.rand(4, 2, device=device, dtype=dtype)
points2 = torch.rand(4, 2, device=device, dtype=dtype)
ransac = RANSAC('homography').to(device=device, dtype=dtype)
- H, inliers = ransac(points1, points2)
+ torch.random.manual_seed(0)
+ H, _ = ransac(points1, points2)
assert H.shape == (3, 3)
@pytest.mark.xfail(reason="might slightly and randomly imprecise due to RANSAC randomness")
def test_dirty_points(self, device, dtype):
# generate input data
+ torch.random.manual_seed(0)
H = torch.eye(3, dtype=dtype, device=device)
H[:2] = H[:2] + 0.1 * torch.rand_like(H[:2])
@@ -33,7 +36,7 @@ class TestRANSACHomography:
points_dst[:, -1, :] += 800
ransac = RANSAC('homography', inl_th=0.5, max_iter=20).to(device=device, dtype=dtype)
# compute transform from source to target
- dst_homo_src, inliers = ransac(points_src[0], points_dst[0])
+ dst_homo_src, _ = ransac(points_src[0], points_dst[0])
assert_close(
kornia.geometry.transform_points(dst_homo_src[None], points_src[:, :-1]),
@@ -41,9 +44,54 @@ class TestRANSACHomography:
rtol=1e-3,
atol=1e-3)
- @pytest.mark.jit
+ @pytest.mark.xfail(reason="might slightly and randomly imprecise due to RANSAC randomness")
+ @pytest.mark.parametrize("data", ["loftr_homo"], indirect=True)
+ def test_real_clean(self, device, dtype, data):
+ # generate input data
+ torch.random.manual_seed(0)
+ data_dev = utils.dict_to(data, device, dtype)
+ homography_gt = torch.inverse(data_dev['H_gt'])
+ homography_gt = homography_gt / homography_gt[2, 2]
+ pts_src = data_dev['pts0']
+ pts_dst = data_dev['pts1']
+ ransac = RANSAC('homography', inl_th=0.5, max_iter=20).to(device=device, dtype=dtype)
+ # compute transform from source to target
+ dst_homo_src, _ = ransac(pts_src, pts_dst)
+
+ assert_close(
+ kornia.geometry.transform_points(dst_homo_src[None], pts_src[None]),
+ pts_dst[None],
+ rtol=1e-3,
+ atol=1e-3)
+
+ @pytest.mark.xfail(reason="might slightly and randomly imprecise due to RANSAC randomness")
+ @pytest.mark.parametrize("data", ["loftr_homo"], indirect=True)
+ def test_real_dirty(self, device, dtype, data):
+ # generate input data
+ torch.random.manual_seed(0)
+ data_dev = utils.dict_to(data, device, dtype)
+ homography_gt = torch.inverse(data_dev['H_gt'])
+ homography_gt = homography_gt / homography_gt[2, 2]
+ pts_src = data_dev['pts0']
+ pts_dst = data_dev['pts1']
+
+ kp1 = data_dev['loftr_outdoor_tentatives0']
+ kp2 = data_dev['loftr_outdoor_tentatives1']
+
+ ransac = RANSAC('homography', inl_th=3.0, max_iter=30, max_lo_iters=10).to(device=device, dtype=dtype)
+ # compute transform from source to target
+ dst_homo_src, _ = ransac(kp1, kp2)
+
+ # Reprojection error of 5px is OK
+ assert_close(
+ kornia.geometry.transform_points(dst_homo_src[None], pts_src[None]),
+ pts_dst[None],
+ rtol=5,
+ atol=0.15)
+
@pytest.mark.skip(reason="find_homography_dlt is using try/except block")
def test_jit(self, device, dtype):
+ torch.random.manual_seed(0)
points1 = torch.rand(4, 2, device=device, dtype=dtype)
points2 = torch.rand(4, 2, device=device, dtype=dtype)
model = RANSAC('homography').to(device=device, dtype=dtype)
@@ -57,76 +105,63 @@ class TestRANSACHomography:
class TestRANSACFundamental:
def test_smoke(self, device, dtype):
+ torch.random.manual_seed(0)
points1 = torch.rand(8, 2, device=device, dtype=dtype)
points2 = torch.rand(8, 2, device=device, dtype=dtype)
ransac = RANSAC('fundamental').to(device=device, dtype=dtype)
- Fm, inliers = ransac(points1, points2)
+ Fm, _ = ransac(points1, points2)
assert Fm.shape == (3, 3)
- def test_dirty_points(self, device, dtype):
- points1 = torch.tensor(
- [
- [
- [0.8569, 0.5982],
- [0.0059, 0.9649],
- [0.1968, 0.8846],
- [0.6084, 0.3467],
- [0.9633, 0.5274],
- [0.8941, 0.8939],
- [0.0863, 0.5133],
- [0.2645, 0.8882]
- ]
- ],
- device=device,
- dtype=dtype,
- )
-
- points2 = torch.tensor(
- [
- [
- [0.0928, 0.3013],
- [0.0989, 0.9649],
- [0.0341, 0.4827],
- [0.8294, 0.4469],
- [0.2230, 0.2998],
- [0.1722, 0.8182],
- [0.5264, 0.8869],
- [0.8908, 0.1233]
- ]
- ],
- device=device,
- dtype=dtype,
- )
- # generated with OpenCV using above points
- # import cv2
- # Fm_expected, _ = cv2.findFundamentalMat(
- # points1.detach().numpy().reshape(-1, 1, 2),
- # points2.detach().numpy().reshape(-1, 1, 2), cv2.FM_8POINT)
-
- Fm_expected = torch.tensor(
- [
- [
- [0.2019, 0.6860, -0.6610],
- [0.5520, 0.8154, -0.8044],
- [-0.5002, -1.0254, 1.]
- ]
- ],
- device=device,
- dtype=dtype,
- )
+ @pytest.mark.xfail(reason="might slightly and randomly imprecise due to RANSAC randomness")
+ @pytest.mark.parametrize("data", ["loftr_fund"], indirect=True)
+ def test_real_clean(self, device, dtype, data):
+ torch.random.manual_seed(0)
+ # generate input data
+ data_dev = utils.dict_to(data, device, dtype)
+ pts_src = data_dev['pts0']
+ pts_dst = data_dev['pts1']
+ # compute transform from source to target
+ ransac = RANSAC('fundamental',
+ inl_th=0.5,
+ max_iter=20,
+ max_lo_iters=10).to(device=device, dtype=dtype)
+ fundamental_matrix, _ = ransac(pts_src, pts_dst)
+ gross_errors = sampson_epipolar_distance(pts_src[None],
+ pts_dst[None],
+ fundamental_matrix[None],
+ squared=False) > 1.0
+ assert gross_errors.sum().item() == 0
+
+ @pytest.mark.xfail(reason="might fail, because out F-RANSAC is not yet 7pt")
+ @pytest.mark.parametrize("data", ["loftr_fund"], indirect=True)
+ def test_real_dirty(self, device, dtype, data):
+ torch.random.manual_seed(0)
+ # generate input data
+ data_dev = utils.dict_to(data, device, dtype)
+ pts_src = data_dev['pts0']
+ pts_dst = data_dev['pts1']
+
+ kp1 = data_dev['loftr_indoor_tentatives0']
+ kp2 = data_dev['loftr_indoor_tentatives1']
+
ransac = RANSAC('fundamental',
- max_iter=1,
- inl_th=1.0).to(device=device, dtype=dtype)
- F_mat, inliers = ransac(points1[0], points2[0])
- assert_close(F_mat, Fm_expected[0], rtol=1e-3, atol=1e-3)
+ inl_th=1.0,
+ max_iter=20,
+ max_lo_iters=10).to(device=device, dtype=dtype)
+ # compute transform from source to target
+ fundamental_matrix, _ = ransac(kp1, kp2)
+ gross_errors = sampson_epipolar_distance(pts_src[None],
+ pts_dst[None],
+ fundamental_matrix[None],
+ squared=False) > 10.0
+ assert gross_errors.sum().item() < 2
- @pytest.mark.jit
def test_jit(self, device, dtype):
+ torch.random.manual_seed(0)
points1 = torch.rand(8, 2, device=device, dtype=dtype)
points2 = torch.rand(8, 2, device=device, dtype=dtype)
model = RANSAC('fundamental').to(device=device, dtype=dtype)
- model_jit = torch.jit.script(RANSAC('fundamental').to(device=device,
- dtype=dtype))
+ model_jit = torch.jit.script(model)
assert_close(model(points1, points2)[0],
model_jit(points1, points2)[0],
rtol=1e-3,
@@ -134,6 +169,7 @@ class TestRANSACFundamental:
@pytest.mark.skip(reason="RANSAC is random algorithm, so Jacobian is not defined")
def test_gradcheck(self, device):
+ torch.random.manual_seed(0)
points1 = torch.rand(8, 2, device=device, dtype=torch.float64, requires_grad=True)
points2 = torch.rand(8, 2, device=device, dtype=torch.float64)
model = RANSAC('fundamental').to(device=device, dtype=torch.float64)
diff --git a/test/geometry/transform/test_image_registrator.py b/test/geometry/transform/test_image_registrator.py
index 1a24b1176..774fe0913 100644
--- a/test/geometry/transform/test_image_registrator.py
+++ b/test/geometry/transform/test_image_registrator.py
@@ -4,56 +4,57 @@ from torch.autograd import gradcheck
import kornia
import kornia.testing as utils # test utils
-from kornia.geometry.transform import ImageRegistrator
+from kornia.geometry import transform_points
+from kornia.geometry.transform import denormalize_homography, ImageRegistrator
from kornia.testing import assert_close
class TestSimilarity:
def test_smoke(self, device, dtype):
- expected = torch.eye(3, device=device)[None]
+ expected = torch.eye(3, device=device, dtype=dtype)[None]
for r, sc, sh in zip([True, False], [True, False], [True, False]):
- sim = kornia.geometry.transform.Similarity(r, sc, sh).to(device)
+ sim = kornia.geometry.transform.Similarity(r, sc, sh).to(device, dtype)
assert_close(sim(), expected, atol=1e-4, rtol=1e-4)
def test_smoke_inverse(self, device, dtype):
- expected = torch.eye(3, device=device)[None]
+ expected = torch.eye(3, device=device, dtype=dtype)[None]
for r, sc, sh in zip([True, False], [True, False], [True, False]):
- s = kornia.geometry.transform.Similarity(r, sc, sh).to(device)
+ s = kornia.geometry.transform.Similarity(r, sc, sh).to(device, dtype)
assert_close(s.forward_inverse(), expected, atol=1e-4, rtol=1e-4)
def test_scale(self, device, dtype):
sc = 0.5
- sim = kornia.geometry.transform.Similarity(True, True, True).to(device)
+ sim = kornia.geometry.transform.Similarity(True, True, True).to(device, dtype)
sim.scale.data *= sc
expected = torch.tensor([[0.5, 0, 0.],
[0, 0.5, 0],
- [0, 0, 1]], device=device)[None]
+ [0, 0, 1]], device=device, dtype=dtype)[None]
inv_expected = torch.tensor([[2.0, 0, 0.],
[0, 2.0, 0],
- [0, 0, 1]], device=device)[None]
+ [0, 0, 1]], device=device, dtype=dtype)[None]
assert_close(sim.forward_inverse(), inv_expected, atol=1e-4, rtol=1e-4)
assert_close(sim(), expected, atol=1e-4, rtol=1e-4)
def test_repr(self, device, dtype):
for r, sc, sh in zip([True, False], [True, False], [True, False]):
- s = kornia.geometry.transform.Similarity(r, sc, sh).to(device)
- print(s)
+ s = kornia.geometry.transform.Similarity(r, sc, sh).to(device, dtype)
+ assert s is not None
class TestHomography:
def test_smoke(self, device, dtype):
- expected = torch.eye(3, device=device)[None]
- h = kornia.geometry.transform.Homography().to(device)
+ expected = torch.eye(3, device=device, dtype=dtype)[None]
+ h = kornia.geometry.transform.Homography().to(device, dtype)
assert_close(h(), expected, atol=1e-4, rtol=1e-4)
def test_smoke_inverse(self, device, dtype):
- expected = torch.eye(3, device=device)[None]
- h = kornia.geometry.transform.Homography().to(device)
+ expected = torch.eye(3, device=device, dtype=dtype)[None]
+ h = kornia.geometry.transform.Homography().to(device, dtype)
assert_close(h.forward_inverse(), expected, atol=1e-4, rtol=1e-4)
def test_repr(self, device, dtype):
- h = kornia.geometry.transform.Homography().to(device)
- print(h)
+ h = kornia.geometry.transform.Homography().to(device, dtype)
+ assert h is not None
class TestImageRegistrator:
@@ -63,16 +64,16 @@ class TestImageRegistrator:
'translation',
'scale',
'rotation']:
- ir = kornia.geometry.transform.ImageRegistrator(model_type).to(device)
- print(ir)
+ ir = kornia.geometry.transform.ImageRegistrator(model_type).to(device, dtype)
+ assert ir is not None
- def test_registration(self, device):
+ def test_registration_toy(self, device, dtype):
ch, height, width = 3, 16, 18
- homography = torch.eye(3, device=device)[None]
+ homography = torch.eye(3, device=device, dtype=dtype)[None]
homography[..., 0, 0] = 1.05
homography[..., 1, 1] = 1.05
homography[..., 0, 2] = 0.01
- img_src = torch.rand(1, ch, height, width, device=device)
+ img_src = torch.rand(1, ch, height, width, device=device, dtype=dtype)
img_dst = kornia.geometry.homography_warp(img_src,
homography,
(height, width),
@@ -80,10 +81,37 @@ class TestImageRegistrator:
IR = ImageRegistrator('Similarity',
num_iterations=500,
lr=3e-4,
- pyramid_levels=2).to(device=device)
+ pyramid_levels=2).to(device, dtype)
model = IR.register(img_src, img_dst)
assert_close(model, homography, atol=1e-3, rtol=1e-3)
model, intermediate = IR.register(img_src,
img_dst,
output_intermediate_models=True)
assert len(intermediate) == 2
+
+ @pytest.mark.parametrize("data", ["loftr_homo"], indirect=True)
+ def test_registration_real(self, device, dtype, data):
+ data_dev = utils.dict_to(data, device, dtype)
+ IR = ImageRegistrator('homography',
+ num_iterations=1200,
+ lr=2e-2,
+ pyramid_levels=5).to(device, dtype)
+ model = IR.register(data_dev['image0'], data_dev['image1'])
+ homography_gt = torch.inverse(data_dev['H_gt'])
+ homography_gt = homography_gt / homography_gt[2, 2]
+ h0, w0 = data['image0'].shape[2], data['image0'].shape[3]
+ h1, w1 = data['image1'].shape[2], data['image1'].shape[3]
+
+ model_denormalized = denormalize_homography(model, (h0, w0), (h1, w1))
+ model_denormalized = model_denormalized / model_denormalized[0, 2, 2]
+
+ bbox = torch.tensor([[[0, 0],
+ [w0, 0],
+ [w0, h0],
+ [0, h0]]], device=device, dtype=dtype)
+ bbox_in_2_gt = transform_points(homography_gt[None], bbox)
+ bbox_in_2_gt_est = transform_points(model_denormalized, bbox)
+ # The tolerance is huge, because the error is in pixels
+ # and transformation is quite significant, so
+ # 15 px reprojection error is not super huge
+ assert_close(bbox_in_2_gt, bbox_in_2_gt_est, atol=15, rtol=0.1)
diff --git a/test/tracking/test_planar_tracking.py b/test/tracking/test_planar_tracking.py
new file mode 100644
index 000000000..f131efdb7
--- /dev/null
+++ b/test/tracking/test_planar_tracking.py
@@ -0,0 +1,68 @@
+import pytest
+import torch
+
+from kornia.feature import DescriptorMatcher, GFTTAffNetHardNet, LocalFeatureMatcher, SIFTFeature
+from kornia.geometry import resize, transform_points
+from kornia.testing import assert_close
+from kornia.tracking import HomographyTracker
+
+
+def data():
+ url = 'https://github.com/kornia/data_test/blob/main/loftr_outdoor_and_homography_data.pt?raw=true'
+ return torch.hub.load_state_dict_from_url(url)
+
+
+class TestHomographyTracker:
+ def test_smoke(self, device):
+ tracker = HomographyTracker().to(device)
+ assert tracker is not None
+
+ def test_nomatch(self, device, dtype, data):
+ # This is not unit test, but that is quite good integration test
+ matcher = LocalFeatureMatcher(SIFTFeature(100),
+ DescriptorMatcher('smnn', 0.95)).to(device,
+ dtype)
+ tracker = HomographyTracker(matcher, matcher, minimum_inliers_num=100)
+ for k in data.keys():
+ if isinstance(data[k], torch.Tensor):
+ data[k] = data[k].to(device, dtype)
+ tracker.set_target(data["image0"])
+ torch.random.manual_seed(0)
+ _, success = tracker(torch.zeros_like(data["image0"]))
+ assert not success
+
+ def test_real(self, device, dtype, data):
+ # This is not unit test, but that is quite good integration test
+ matcher = LocalFeatureMatcher(GFTTAffNetHardNet(1000),
+ DescriptorMatcher('snn', 0.8)).to(device, dtype)
+ tracker = HomographyTracker(matcher, matcher).to(device, dtype)
+ for k in data.keys():
+ if isinstance(data[k], torch.Tensor):
+ data[k] = data[k].to(device, dtype)
+ h0, w0 = data["image0"].shape[2:]
+ data["image0"] = resize(data["image0"], (int(h0 // 2), int(w0 // 2)))
+ data["image1"] = resize(data["image1"], (int(h0 // 2), int(w0 // 2)))
+ with torch.no_grad():
+ tracker.set_target(data["image0"])
+ torch.random.manual_seed(0)
+ homography, success = tracker(data["image1"])
+ assert success
+ pts_src = data['pts0'].to(device, dtype) / 2.0
+ pts_dst = data['pts1'].to(device, dtype) / 2.0
+ # Reprojection error of 5px is OK
+ assert_close(
+ transform_points(homography[None], pts_src[None]),
+ pts_dst[None],
+ rtol=5e-2,
+ atol=5)
+ # next frame
+ with torch.no_grad():
+ torch.random.manual_seed(0)
+ homography, success = tracker(data["image1"])
+ assert success
+ assert_close(
+ transform_points(homography[None], pts_src[None]),
+ pts_dst[None],
+ rtol=5e-2,
+ atol=5)
diff --git a/test/utilities.py b/test/utilities.py
new file mode 100644
index 000000000..5c509f4c6
--- /dev/null
+++ b/test/utilities.py
@@ -0,0 +1,8 @@
+import pytest
+import torch
+
+
+def data_loftr():
+ url = 'https://github.com/kornia/data_test/blob/main/loftr_outdoor_and_homography_data.pt?raw=true'
+ return torch.hub.load_state_dict_from_url(url)