π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
AdaLAM match filtering (clean) (#1831)
Dmytro Mishkin6e4b85a3bbf8
diff --git a/conftest.py b/conftest.pyindex ec05b0fa0..57a4be4f7 100644--- a/conftest.py+++ b/conftest.py@@ -99,6 +99,7 @@ def add_np(doctest_namespace):# the commit hash for the data versionsha: str = 'cb8f42bf28b9f347df6afba5558738f62a11f28a'+sha2: str = '824ff1518870864644df6842a4ec964040f64504'@pytest.fixture(scope='session')@@ -106,5 +107,6 @@ 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',+ 'adalam_idxs': f'https://github.com/kornia/data_test/blob/{sha2}/adalam_test.pt?raw=true',}return torch.hub.load_state_dict_from_url(url[request.param])diff --git a/docs/source/feature.rst b/docs/source/feature.rstindex d67d73b7d..5db5276cd 100644--- a/docs/source/feature.rst+++ b/docs/source/feature.rst@@ -36,6 +36,8 @@ Matching.. autofunction:: match_snn.. autofunction:: match_smnn.. autofunction:: match_fginn+.. autofunction:: match_adalam+.. autoclass:: DescriptorMatcher:members: forward@@ -83,7 +85,7 @@ Local Affine Frames (LAF).. autofunction:: laf_is_inside_image.. autofunction:: laf_to_three_points.. autofunction:: laf_from_three_points-.. autofunction:: raise_error_if_laf_is_not_valid+.. autofunction:: KORNIA_CHECK_LAF.. autofunction:: perspective_transform_lafsModulediff --git a/kornia/feature/__init__.py b/kornia/feature/__init__.pyindex 877df306b..418319bdd 100644--- a/kornia/feature/__init__.py+++ b/kornia/feature/__init__.py@@ -14,6 +14,7 @@ from .integrated import ()from .keynet import KeyNet, KeyNetDetectorfrom .laf import (+ KORNIA_CHECK_LAF,denormalize_laf,ellipse_to_laf,extract_patches_from_pyramid,@@ -29,7 +30,6 @@ from .laf import (make_upright,normalize_laf,perspective_transform_lafs,- raise_error_if_laf_is_not_valid,scale_laf,set_laf_orientation,)@@ -37,6 +37,7 @@ from .loftr import LoFTRfrom .matching import (DescriptorMatcher,GeometryAwareDescriptorMatcher,+ match_adalam,match_fginn,match_mnn,match_nn,@@ -66,6 +67,7 @@ __all__ = ["match_snn","match_smnn","match_fginn",+ "match_adalam","DescriptorMatcher","GeometryAwareDescriptorMatcher","get_laf_descriptors",@@ -115,7 +117,7 @@ __all__ = ["PatchAffineShapeEstimator","LAFOrienter","PatchDominantGradientOrientation",- "raise_error_if_laf_is_not_valid",+ "KORNIA_CHECK_LAF","laf_is_inside_image","laf_from_center_scale_ori","laf_to_three_points",diff --git a/kornia/feature/adalam/__init__.py b/kornia/feature/adalam/__init__.pynew file mode 100644index 000000000..08ab1cf18--- /dev/null+++ b/kornia/feature/adalam/__init__.py@@ -0,0 +1 @@+from .adalam import AdalamFilter, get_adalam_default_config, match_adalamdiff --git a/kornia/feature/adalam/adalam.py b/kornia/feature/adalam/adalam.pynew file mode 100644index 000000000..56e4bd665--- /dev/null+++ b/kornia/feature/adalam/adalam.py@@ -0,0 +1,230 @@+from typing import Dict, Optional, Tuple++import torch+from torch import Tensor++from kornia.feature.laf import get_laf_center, get_laf_orientation, get_laf_scale+from kornia.testing import KORNIA_CHECK_LAF, KORNIA_CHECK_SHAPE+from kornia.utils.helpers import get_cuda_device_if_available++from .core import adalam_core+from .utils import dist_matrix+++def get_adalam_default_config():+ DEFAULT_CONFIG = {+ 'area_ratio': 100, # Ratio between seed circle area and image area. Higher values produce more seeds with smaller neighborhoods. # noqa: E501+ 'search_expansion': 4, # Expansion factor of the seed circle radius for the purpose of collecting neighborhoods. Increases neighborhood radius without changing seed distribution # noqa: E501+ 'ransac_iters': 128, # Fixed number of inner GPU-RANSAC iterations+ 'min_inliers': 6, # Minimum number of inliers required to accept inliers coming from a neighborhood # noqa: E501+ 'min_confidence': 200, # Threshold used by the confidence-based GPU-RANSAC+ 'orientation_difference_threshold': 30, # Maximum difference in orientations for a point to be accepted in a neighborhood. Set to None to disable the use of keypoint orientations. # noqa: E501+ 'scale_rate_threshold': 1.5, # Maximum difference (ratio) in scales for a point to be accepted in a neighborhood. Set to None to disable the use of keypoint scales. # noqa: E501+ 'detected_scale_rate_threshold': 5, # Prior on maximum possible scale change detectable in image couples. Affinities with higher scale changes are regarded as outliers. # noqa: E501+ 'refit': True, # Whether to perform refitting at the end of the RANSACs. Generally improves accuracy at the cost of runtime. # noqa: E501+ 'force_seed_mnn': True, # Whether to consider only MNN for the purpose of selecting seeds. Generally improves accuracy at the cost of runtime. # noqa: E501+ # You can provide a MNN mask in input to skip MNN computation and still get the improvement.+ 'device': get_cuda_device_if_available(), # Device to be used for running AdaLAM. Use GPU if available. # noqa: E501+ }+ return DEFAULT_CONFIG+++def match_adalam(+ desc1: Tensor,+ desc2: Tensor,+ lafs1: Tensor,+ lafs2: Tensor,+ config: Dict = get_adalam_default_config(),+ hw1: Optional[Tensor] = None,+ hw2: Optional[Tensor] = None,+ dm: Optional[Tensor] = None,+) -> Tuple[Tensor, Tensor]:+ """Function, which performs descriptor matching, followed by AdaLAM filtering (see :cite:`AdaLAM2020` for more+ details)++ If the distance matrix dm is not provided, :py:func:`torch.cdist` is used.++ Args:+ desc1: Batch of descriptors of a shape :math:`(B1, D)`.+ desc2: Batch of descriptors of a shape :math:`(B2, D)`.+ lafs1: LAFs of a shape :math:`(1, B1, 2, 3)`.+ lafs2: LAFs of a shape :math:`(1, B1, 2, 3)`.+ config: dict with AdaLAM config+ dm: Tensor containing the distances from each descriptor in desc1+ to each descriptor in desc2, shape of :math:`(B1, B2)`.++ Return:+ - Descriptor distance of matching descriptors, shape of :math:`(B3, 1)`.+ - Long tensor indexes of matching descriptors in desc1 and desc2. Shape: :math:`(B3, 2)`,+ where 0 <= B3 <= B1.+ """+ KORNIA_CHECK_SHAPE(desc1, ["B", "DIM"])+ KORNIA_CHECK_SHAPE(desc2, ["B", "DIM"])+ KORNIA_CHECK_LAF(lafs1)+ KORNIA_CHECK_LAF(lafs2)++ adalam_object = AdalamFilter(config)+ idxs = adalam_object.match_and_filter(+ get_laf_center(lafs1).reshape(-1, 2),+ get_laf_center(lafs2).reshape(-1, 2),+ desc1,+ desc2,+ hw1,+ hw2,+ get_laf_orientation(lafs1).reshape(-1),+ get_laf_orientation(lafs2).reshape(-1),+ get_laf_scale(lafs1).reshape(-1),+ get_laf_scale(lafs2).reshape(-1),+ )+ quality = torch.ones(len(idxs), 1, dtype=desc1.dtype, device=desc1.device)+ return quality, idxs+++class AdalamFilter:+ DEFAULT_CONFIG = get_adalam_default_config()++ def __init__(self, custom_config: dict = None):+ """This class acts as a wrapper to the method AdaLAM for outlier filtering.++ init args:+ custom_config: dictionary overriding the default configuration. Missing parameters are kept as default.+ See documentation of DEFAULT_CONFIG for specific explanations on the accepted parameters.+ """+ self.config = AdalamFilter.DEFAULT_CONFIG.copy()++ if custom_config is not None:+ for key, val in custom_config.items():+ if key not in self.config.keys():+ print(+ "WARNING: custom configuration contains a key which is not recognized ({key}). "+ "Known configurations are {list(self.config.keys())}."+ )+ continue+ self.config[key] = val++ def filter_matches(+ self,+ k1: torch.Tensor,+ k2: torch.Tensor,+ putative_matches: torch.Tensor,+ scores: torch.Tensor,+ mnn: torch.Tensor = None,+ im1shape: tuple = None,+ im2shape: tuple = None,+ o1: torch.Tensor = None,+ o2: torch.Tensor = None,+ s1: torch.Tensor = None,+ s2: torch.Tensor = None,+ ):+ """Call the core functionality of AdaLAM, i.e. just outlier filtering. No sanity check is performed on the+ inputs.++ Inputs:+ k1: keypoint locations in the source image, in pixel coordinates.+ Expected a float32 tensor with shape (num_keypoints_in_source_image, 2).+ k2: keypoint locations in the destination image, in pixel coordinates.+ Expected a float32 tensor with shape (num_keypoints_in_destination_image, 2).+ putative_matches: Initial set of putative matches to be filtered.+ The current implementation assumes that these are unfiltered nearest neighbor matches,+ so it requires this to be a list of indices a_i such that the source keypoint i is associated to the destination keypoint a_i.+ For now to use AdaLAM on different inputs a workaround on the input format is required.+ Expected a long tensor with shape (num_keypoints_in_source_image,).+ scores: Confidence scores on the putative_matches. Usually holds Lowe's ratio scores.+ mnn: A mask indicating which putative matches are also mutual nearest neighbors. See documentation on 'force_seed_mnn' in the DEFAULT_CONFIG.+ If None, it disables the mutual nearest neighbor filtering on seed point selection.+ Expected a bool tensor with shape (num_keypoints_in_source_image,)+ im1shape: Shape of the source image. If None, it is inferred from keypoints max and min, at the cost of wasted runtime. So please provide it.+ Expected a tuple with (width, height) or (height, width) of source image+ im2shape: Shape of the destination image. If None, it is inferred from keypoints max and min, at the cost of wasted runtime. So please provide it.+ Expected a tuple with (width, height) or (height, width) of destination image+ o1/o2: keypoint orientations in degrees. They can be None if 'orientation_difference_threshold' in config is set to None.+ See documentation on 'orientation_difference_threshold' in the DEFAULT_CONFIG.+ Expected a float32 tensor with shape (num_keypoints_in_source/destination_image,)+ s1/s2: keypoint scales. They can be None if 'scale_rate_threshold' in config is set to None.+ See documentation on 'scale_rate_threshold' in the DEFAULT_CONFIG.+ Expected a float32 tensor with shape (num_keypoints_in_source/destination_image,)++ Returns:+ Filtered putative matches.+ A long tensor with shape (num_filtered_matches, 2) with indices of corresponding keypoints in k1 and k2.+ """ # noqa: E501+ with torch.no_grad():+ return adalam_core(+ k1,+ k2,+ fnn12=putative_matches,+ scores1=scores,+ mnn=mnn,+ im1shape=im1shape,+ im2shape=im2shape,+ o1=o1,+ o2=o2,+ s1=s1,+ s2=s2,+ config=self.config,+ )++ def match_and_filter(self, k1, k2, d1, d2, im1shape=None, im2shape=None, o1=None, o2=None, s1=None, s2=None):+ """Standard matching and filtering with AdaLAM. This function:++ - performs some elementary sanity check on the inputs;+ - wraps input arrays into torch tensors and loads to GPU if necessary;+ - extracts nearest neighbors;+ - finds mutual nearest neighbors if required;+ - finally calls AdaLAM filtering.++ Inputs:+ k1: keypoint locations in the source image, in pixel coordinates.+ Expected an array with shape (num_keypoints_in_source_image, 2).+ k2: keypoint locations in the destination image, in pixel coordinates.+ Expected an array with shape (num_keypoints_in_destination_image, 2).+ d1: descriptors in the source image.+ Expected an array with shape (num_keypoints_in_source_image, descriptor_size).+ d2: descriptors in the destination image.+ Expected an array with shape (num_keypoints_in_destination_image, descriptor_size).+ im1shape: Shape of the source image. If None, it is inferred from keypoints max and min, at the cost of wasted runtime. So please provide it.+ Expected a tuple with (width, height) or (height, width) of source image+ im2shape: Shape of the destination image. If None, it is inferred from keypoints max and min, at the cost of wasted runtime. So please provide it.+ Expected a tuple with (width, height) or (height, width) of destination image+ o1/o2: keypoint orientations in degrees. They can be None if 'orientation_difference_threshold' in config is set to None.+ See documentation on 'orientation_difference_threshold' in the DEFAULT_CONFIG.+ Expected an array with shape (num_keypoints_in_source/destination_image,)+ s1/s2: keypoint scales. They can be None if 'scale_rate_threshold' in config is set to None.+ See documentation on 'scale_rate_threshold' in the DEFAULT_CONFIG.+ Expected an array with shape (num_keypoints_in_source/destination_image,)++ Returns:+ Filtered putative matches.+ A long tensor with shape (num_filtered_matches, 2) with indices of corresponding keypoints in k1 and k2.+ """ # noqa: E501+ if s1 is None or s2 is None:+ if self.config['scale_rate_threshold'] is not None:+ raise AttributeError(+ "Current configuration considers keypoint scales for filtering, but scales have not been provided.\n" # noqa: E501+ "Please either provide scales or set 'scale_rate_threshold' to None to disable scale filtering"+ )+ if o1 is None or o2 is None:+ if self.config['orientation_difference_threshold'] is not None:+ raise AttributeError(+ "Current configuration considers keypoint orientations for filtering, but orientations have not been provided.\n" # noqa: E501+ "Please either provide orientations or set 'orientation_difference_threshold' to None to disable orientations filtering" # noqa: E501+ )+ k1, k2, d1, d2, o1, o2, s1, s2 = self.__to_torch(k1, k2, d1, d2, o1, o2, s1, s2)+ distmat = dist_matrix(d1, d2, is_normalized=False)+ dd12, nn12 = torch.topk(distmat, k=2, dim=1, largest=False) # (n1, 2)++ putative_matches = nn12[:, 0]+ scores = dd12[:, 0] / dd12[:, 1].clamp_min_(1e-3)+ if self.config['force_seed_mnn']:+ dd21, nn21 = torch.min(distmat, dim=0) # (n2,)+ mnn = nn21[putative_matches] == torch.arange(k1.shape[0], device=self.config['device'])+ else:+ mnn = None++ return self.filter_matches(k1, k2, putative_matches, scores, mnn, im1shape, im2shape, o1, o2, s1, s2)++ def __to_torch(self, *args):+ return (+ a if a is None or torch.is_tensor(a) else torch.tensor(a, device=self.config['device'], dtype=torch.float32)+ for a in args+ )diff --git a/kornia/feature/adalam/core.py b/kornia/feature/adalam/core.pynew file mode 100644index 000000000..0bb929d17--- /dev/null+++ b/kornia/feature/adalam/core.py@@ -0,0 +1,316 @@+import math+from typing import Optional, Tuple, Union++import torch+from torch import Tensor, tensor++from .ransac import ransac+from .utils import dist_matrix, orientation_diff+++def select_seeds(dist1: Tensor, R1: Union[float, Tensor], scores1: Tensor, fnn12: Tensor, mnn: Optional[Tensor]):+ """Select seed correspondences among the set of available matches.++ dist1: Precomputed distance matrix between keypoints in image I_1+ R1: Base radius of neighborhoods in image I_1+ scores1: Confidence scores on the putative_matches. Usually holds Lowe's ratio scores.+ fnn12: Matches between keypoints of I_1 and I_2.+ The i-th entry of fnn12 is j if and only if keypoint k_i in image I_1 is matched to keypoint k_j in image I_2+ mnn: A mask indicating which putative matches are also mutual nearest neighbors. See documentation on 'force_seed_mnn' in the DEFAULT_CONFIG.+ If None, it disables the mutual nearest neighbor filtering on seed point selection.+ Expected a bool tensor with shape (num_keypoints_in_source_image,)++ Returns:+ Indices of seed points.++ im1seeds: Keypoint index of chosen seeds in image I_1+ im2seeds: Keypoint index of chosen seeds in image I_2+ """ # noqa: E501+ im1neighmap = dist1 < R1**2 # (n1, n1)+ # find out who scores higher than whom+ im1scorescomp = scores1.unsqueeze(1) > scores1.unsqueeze(0) # (n1, n1)+ # find out who scores higher than all of its neighbors: seed points+ if mnn is not None:+ im1bs = (+ (~torch.any(im1neighmap & im1scorescomp & mnn.unsqueeze(0), dim=1)) & mnn & (scores1 < 0.8**2)+ ) # (n1,)+ else:+ im1bs = (~torch.any(im1neighmap & im1scorescomp, dim=1)) & (scores1 < 0.8**2)++ # collect all seeds in both images and the 1NN of the seeds of the other image+ im1seeds = torch.where(im1bs)[0] # (n1bs) index format+ im2seeds = fnn12[im1bs] # (n1bs) index format+ return im1seeds, im2seeds+++def extract_neighborhood_sets(+ o1: Optional[Tensor],+ o2: Optional[Tensor],+ s1: Optional[Tensor],+ s2: Optional[Tensor],+ dist1: Tensor,+ im1seeds: Tensor,+ im2seeds: Tensor,+ k1: Tensor,+ k2: Tensor,+ R1: Union[float, Tensor],+ R2: Union[float, Tensor],+ fnn12: Tensor,+ ORIENTATION_THR: float,+ SCALE_RATE_THR: float,+ SEARCH_EXP: float,+ MIN_INLIERS: float,+):+ """Assign keypoints to seed points. This checks both the distance and the agreement of the local transformation+ if available.++ o1: Orientations of keypoints in image I_1+ o2: Orientations of keypoints in image I_2+ s1: Scales of keypoints in image I_1+ s2: Scales of keypoints in image I_2+ dist1: Precomputed distance matrix between keypoints in image I_1+ im1seeds: Keypoint index of chosen seeds in image I_1+ im2seeds: Keypoint index of chosen seeds in image I_2+ k1: Keypoint locations in image I_1+ k2: Keypoint locations in image I_2+ R1: Base radius of neighborhoods in image I_1+ R2: Base radius of neighborhoods in image I_2+ fnn12: Matches between keypoints of I_1 and I_2.+ The i-th entry of fnn12 is j if and only if keypoint k_i in image I_1 is matched to keypoint k_j in image I_2+ ORIENTATION_THR: Maximum deviation of orientation with respect to seed S_i to keep a keypoint in i-th neighborhood+ SCALE_RATE_THR: Maximum deviation of scale with respect to seed S_i to keep a keypoint in i-th neighborhood+ SEARCH_EXP: Expansion rate for both radii R1 and R2 to consider inclusion of neighboring keypoints+ MIN_INLIERS: Minimum number of inliers to keep a seed point. This is used as an early filter here+ to remove already seeds with not enough samples to ever pass this threshold.++ Returns:+ Local neighborhoods assignments:++ local_neighs_mask: Boolean matrix of size (num_seeds, num_keypoints).+ Entry (i, j) is True iff keypoint j was assigned to seed i.+ rdims: Number of keypoints included in the neighborhood for each seed+ im1seeds: Keypoint index of chosen seeds in image I_1+ im2seeds: Keypoint index of chosen seeds in image I_2+ """+ dst1 = dist1[im1seeds, :]+ dst2 = dist_matrix(k2[fnn12[im1seeds]], k2[fnn12])++ # initial candidates are matches which are close to the same seed in both images+ local_neighs_mask = (dst1 < (SEARCH_EXP * R1) ** 2) & (dst2 < (SEARCH_EXP * R2) ** 2)++ # If requested, also their orientation delta should be compatible with that of the corresponding seed+ if ORIENTATION_THR is not None and ORIENTATION_THR < 180 and (o1 is not None) and (o2 is not None):+ relo = orientation_diff(o1, o2[fnn12])+ orientation_diffs = torch.abs(orientation_diff(relo.unsqueeze(0), relo[im1seeds].unsqueeze(1)))+ local_neighs_mask = local_neighs_mask & (orientation_diffs < ORIENTATION_THR)++ # If requested, also their scale delta should be compatible with that of the corresponding seed+ if SCALE_RATE_THR is not None and (SCALE_RATE_THR < 10) and (s1 is not None) and (s2 is not None):+ rels = s2[fnn12] / s1+ scale_rates = rels[im1seeds].unsqueeze(1) / rels.unsqueeze(0)+ local_neighs_mask = (+ local_neighs_mask & (scale_rates < SCALE_RATE_THR) & (scale_rates > 1 / SCALE_RATE_THR)+ ) # (ns, n1)++ # count how many keypoints ended up in each neighborhood+ numn1 = torch.sum(local_neighs_mask, dim=1)+ # and only keep the ones that have enough points+ valid_seeds = numn1 >= MIN_INLIERS++ local_neighs_mask = local_neighs_mask[valid_seeds, :]++ rdims = numn1[valid_seeds]++ return local_neighs_mask, rdims, im1seeds[valid_seeds], im2seeds[valid_seeds]+++def extract_local_patterns(+ fnn12: Tensor,+ fnn_to_seed_local_consistency_map_corr: Tensor,+ k1: Tensor,+ k2: Tensor,+ im1seeds: Tensor,+ im2seeds: Tensor,+ scores: Tensor,+):+ """Prepare local neighborhoods around each seed for the parallel RANSACs. This involves two steps: 1) Collect+ all selected keypoints and refer them with respect to their seed point 2) Sort keypoints by score for the+ progressive sampling to pick the best samples first.++ fnn12: Matches between keypoints of I_1 and I_2.+ The i-th entry of fnn12 is j if and only if keypoint k_i in image I_1 is matched to keypoint k_j in image I_2+ fnn_to_seed_local_consistency_map_corr: Boolean matrix of size (num_seeds, num_keypoints).+ Entry (i, j) is True iff keypoint j was assigned to seed i.+ k1: Keypoint locations in image I_1+ k2: Keypoint locations in image I_2+ im1seeds: Keypoint index of chosen seeds in image I_1+ im2seeds: Keypoint index of chosen seeds in image I_2+ scores: Scores to rank correspondences by confidence.+ Lower scores are assumed to be more confident, consistently with Lowe's ratio scores.+ Note: scores should be between 0 and 1 for this function to work as expected.++ Returns:+ All information required for running the parallel RANSACs.+ Data is formatted so that all inputs for different RANSACs are concatenated+ along the same dimension to support different input sizes.++ im1loc: Keypoint locations in image I_1 for each RANSAC sample.+ im2loc: Keypoint locations in image I_2 for each RANSAC sample.+ ransidx: Integer identifier of the RANSAC problem.+ This allows to distinguish inputs belonging to the same problem.+ tokp1: Index of the original keypoint in image I_1 for each RANSAC sample.+ tokp2: Index of the original keypoint in image I_2 for each RANSAC sample.+ """+ # first get an indexing representation of the assignments:+ # - ransidx holds the index of the seed for each assignment+ # - tokp1 holds the index of the keypoint in image I_1 for each assignment+ ransidx, tokp1 = torch.where(fnn_to_seed_local_consistency_map_corr)+ # - and of course tokp2 holds the index of the corresponding keypoint in image I_2+ tokp2 = fnn12[tokp1]++ # Now take the locations in the image of each considered keypoint ...+ im1abspattern = k1[tokp1]+ im2abspattern = k2[tokp2]++ # ... and subtract the location of its corresponding seed to get relative coordinates+ im1loc = im1abspattern - k1[im1seeds[ransidx]]+ im2loc = im2abspattern - k2[im2seeds[ransidx]]++ # Finally we need to sort keypoints by scores in a way that assignments to the same seed are close together+ # To achieve this we assume scores lie in (0, 1) and add the integer index of the corresponding seed+ expanded_local_scores = scores[tokp1] + ransidx.type(scores.dtype)++ sorting_perm = torch.argsort(expanded_local_scores)++ im1loc = im1loc[sorting_perm]+ im2loc = im2loc[sorting_perm]+ tokp1 = tokp1[sorting_perm]+ tokp2 = tokp2[sorting_perm]++ return im1loc, im2loc, ransidx, tokp1, tokp2+++def adalam_core(+ k1: Tensor,+ k2: Tensor,+ fnn12: Tensor,+ scores1: Tensor,+ config: dict,+ mnn: Optional[Tensor] = None,+ im1shape: Optional[Tuple] = None,+ im2shape: Optional[Tuple] = None,+ o1: Optional[Tensor] = None,+ o2: Optional[Tensor] = None,+ s1: Optional[Tensor] = None,+ s2: Optional[Tensor] = None,+):+ """Call the core functionality of AdaLAM, i.e. just outlier filtering. No sanity check is performed on the+ inputs.++ Inputs:+ k1: keypoint locations in the source image, in pixel coordinates.+ Expected a float32 tensor with shape (num_keypoints_in_source_image, 2).+ k2: keypoint locations in the destination image, in pixel coordinates.+ Expected a float32 tensor with shape (num_keypoints_in_destination_image, 2).+ fn12: Initial set of putative matches to be filtered.+ The current implementation assumes that these are unfiltered nearest neighbor matches,+ so it requires this to be a list of indices a_i such that the source keypoint i is associated to the destination keypoint a_i.+ For now to use AdaLAM on different inputs a workaround on the input format is required.+ Expected a long tensor with shape (num_keypoints_in_source_image,).+ scores1: Confidence scores on the putative_matches. Usually holds Lowe's ratio scores.+ mnn: A mask indicating which putative matches are also mutual nearest neighbors. See documentation on 'force_seed_mnn' in the DEFAULT_CONFIG.+ If None, it disables the mutual nearest neighbor filtering on seed point selection.+ Expected a bool tensor with shape (num_keypoints_in_source_image,)+ im1shape: Shape of the source image. If None, it is inferred from keypoints max and min, at the cost of wasted runtime. So please provide it.+ Expected a tuple with (width, height) or (height, width) of source image+ im2shape: Shape of the destination image. If None, it is inferred from keypoints max and min, at the cost of wasted runtime. So please provide it.+ Expected a tuple with (width, height) or (height, width) of destination image+ o1/o2: keypoint orientations in degrees. They can be None if 'orientation_difference_threshold' in config is set to None.+ See documentation on 'orientation_difference_threshold' in the DEFAULT_CONFIG.+ Expected a float32 tensor with shape (num_keypoints_in_source/destination_image,)+ s1/s2: keypoint scales. They can be None if 'scale_rate_threshold' in config is set to None.+ See documentation on 'scale_rate_threshold' in the DEFAULT_CONFIG.+ Expected a float32 tensor with shape (num_keypoints_in_source/destination_image,)++ Returns:+ Filtered putative matches.+ A long tensor with shape (num_filtered_matches, 2) with indices of corresponding keypoints in k1 and k2.+ """ # noqa: E501+ AREA_RATIO = config['area_ratio']+ SEARCH_EXP = config['search_expansion']+ RANSAC_ITERS = config['ransac_iters']+ MIN_INLIERS = config['min_inliers']+ MIN_CONF = config['min_confidence']+ ORIENTATION_THR = config['orientation_difference_threshold']+ SCALE_RATE_THR = config['scale_rate_threshold']+ REFIT = config['refit']++ if im1shape is None:+ k1mins, _ = torch.min(k1, dim=0)+ k1maxs, _ = torch.max(k1, dim=0)+ im1shape = k1maxs - k1mins+ if im2shape is None:+ k2mins, _ = torch.min(k2, dim=0)+ k2maxs, _ = torch.max(k2, dim=0)+ im2shape = k2maxs - k2mins++ # Compute seed selection radii to be invariant to image rescaling+ R1 = torch.sqrt(torch.prod(tensor(im1shape[:2])) / AREA_RATIO / math.pi)+ R2 = torch.sqrt(torch.prod(tensor(im2shape[:2])) / AREA_RATIO / math.pi)++ # Precompute the inner distances of keypoints in image I_1+ dist1 = dist_matrix(k1, k1)++ # Select seeds+ im1seeds, im2seeds = select_seeds(dist1, R1, scores1, fnn12, mnn)++ # Find the neighboring and coherent keyopints consistent with each seed+ local_neighs_mask, rdims, im1seeds, im2seeds = extract_neighborhood_sets(+ o1,+ o2,+ s1,+ s2,+ dist1,+ im1seeds,+ im2seeds,+ k1,+ k2,+ R1,+ R2,+ fnn12,+ ORIENTATION_THR,+ SCALE_RATE_THR,+ SEARCH_EXP,+ MIN_INLIERS,+ )++ if rdims.shape[0] == 0:+ # No seed point survived. Just output ratio-test matches. This should happen very rarely.+ absolute_im1idx = torch.where(scores1 < 0.8**2)[0]+ absolute_im2idx = fnn12[absolute_im1idx]+ return torch.stack([absolute_im1idx, absolute_im2idx], dim=1)++ # Format neighborhoods for parallel RANSACs+ im1loc, im2loc, ransidx, tokp1, tokp2 = extract_local_patterns(+ fnn12, local_neighs_mask, k1, k2, im1seeds, im2seeds, scores1+ )+ im1loc = im1loc / (R1 * SEARCH_EXP)+ im2loc = im2loc / (R2 * SEARCH_EXP)++ # Run the parallel confidence-based RANSACs to perform local affine verification+ inlier_idx, _, inl_confidence, inlier_counts = ransac(+ xsamples=im1loc, ysamples=im2loc, rdims=rdims, iters=RANSAC_ITERS, refit=REFIT, config=config+ )++ conf = inl_confidence[ransidx[inlier_idx]]+ cnt = inlier_counts[ransidx[inlier_idx]].float()+ passed_inliers_mask = (conf >= MIN_CONF) & (cnt * (1 - 1 / conf) >= MIN_INLIERS)+ accepted_inliers = inlier_idx[passed_inliers_mask]++ absolute_im1idx = tokp1[accepted_inliers]+ absolute_im2idx = tokp2[accepted_inliers]++ final_matches = torch.stack([absolute_im1idx, absolute_im2idx], dim=1)+ if final_matches.shape[0] > 1:+ return torch.unique(final_matches, dim=0)+ return final_matchesdiff --git a/kornia/feature/adalam/ransac.py b/kornia/feature/adalam/ransac.pynew file mode 100644index 000000000..9111dc445--- /dev/null+++ b/kornia/feature/adalam/ransac.py@@ -0,0 +1,155 @@+import torch++from .utils import arange_sequence, batch_2x2_ellipse, batch_2x2_inv, draw_first_k_couples, piecewise_arange+++def stable_sort_residuals(residuals, ransidx):+ logres = torch.log(residuals + 1e-10)+ minlogres = torch.min(logres)+ maxlogres = torch.max(logres)++ sorting_score = ransidx.unsqueeze(0).float() + 0.99 * (logres - minlogres) / (maxlogres - minlogres)++ sorting_idxes = torch.argsort(sorting_score, dim=-1) # (niters, numsamples)++ iters_range = torch.arange(residuals.shape[0], device=residuals.device)++ return residuals[iters_range.unsqueeze(-1), sorting_idxes], sorting_idxes+++def group_sum_and_cumsum(scores_mat, end_group_idx, group_idx=None):+ cumulative_scores = torch.cumsum(scores_mat, dim=1)+ ending_cumusums = cumulative_scores[:, end_group_idx]+ shifted_ending_cumusums = torch.cat(+ [+ torch.zeros(size=(ending_cumusums.shape[0], 1), dtype=ending_cumusums.dtype, device=scores_mat.device),+ ending_cumusums[:, :-1],+ ],+ dim=1,+ )+ grouped_sums = ending_cumusums - shifted_ending_cumusums++ if group_idx is not None:+ grouped_cumsums = cumulative_scores - shifted_ending_cumusums[:, group_idx]+ return grouped_sums, grouped_cumsums+ return grouped_sums, None+++def confidence_based_inlier_selection(residuals, ransidx, rdims, idxoffsets, dv, min_confidence):+ numransacs = rdims.shape[0]+ numiters = residuals.shape[0]++ sorted_res, sorting_idxes = stable_sort_residuals(residuals, ransidx)+ sorted_res_sqr = sorted_res**2++ too_perfect_fits = sorted_res_sqr <= 1e-8+ end_rans_indexing = torch.cumsum(rdims, dim=0) - 1++ _, inv_indices, res_dup_counts = torch.unique_consecutive(+ sorted_res_sqr.half().float(), dim=1, return_counts=True, return_inverse=True+ )++ duplicates_per_sample = res_dup_counts[inv_indices]+ inlier_weights = (1.0 / duplicates_per_sample).repeat(numiters, 1)+ inlier_weights[too_perfect_fits] = 0.0++ balanced_rdims, weights_cumsums = group_sum_and_cumsum(inlier_weights, end_rans_indexing, ransidx)+ progressive_inl_rates = weights_cumsums.float() / (balanced_rdims.repeat_interleave(rdims, dim=1)).float()++ good_inl_mask = (sorted_res_sqr * min_confidence <= progressive_inl_rates) | too_perfect_fits++ inlier_weights[~good_inl_mask] = 0.0+ inlier_counts_matrix, _ = group_sum_and_cumsum(inlier_weights, end_rans_indexing)++ inl_counts, inl_iters = torch.max(inlier_counts_matrix.long(), dim=0)++ relative_inl_idxes = arange_sequence(inl_counts)+ inl_ransidx = torch.arange(numransacs, device=dv).repeat_interleave(inl_counts)+ inl_sampleidx = sorting_idxes[inl_iters.repeat_interleave(inl_counts), idxoffsets[inl_ransidx] + relative_inl_idxes]+ highest_accepted_sqr_residuals = sorted_res_sqr[inl_iters, idxoffsets + inl_counts - 1]+ expected_extra_inl = (+ balanced_rdims[inl_iters, torch.arange(numransacs, device=dv)].float() * highest_accepted_sqr_residuals+ )+ return inl_ransidx, inl_sampleidx, inl_counts, inl_iters, inl_counts.float() / expected_extra_inl+++def sample_padded_inliers(xsamples, ysamples, inlier_counts, inl_ransidx, inl_sampleidx, numransacs, dv):+ maxinliers = torch.max(inlier_counts).item()+ dtype = xsamples.dtype+ padded_inlier_x = torch.zeros(size=(numransacs, maxinliers, 2), device=dv, dtype=dtype)+ padded_inlier_y = torch.zeros(size=(numransacs, maxinliers, 2), device=dv, dtype=dtype)++ padded_inlier_x[inl_ransidx, piecewise_arange(inl_ransidx)] = xsamples[inl_sampleidx]+ padded_inlier_y[inl_ransidx, piecewise_arange(inl_ransidx)] = ysamples[inl_sampleidx]++ return padded_inlier_x, padded_inlier_y+++def ransac(xsamples, ysamples, rdims, config, iters=128, refit=True):+ DET_THR = config['detected_scale_rate_threshold']+ MIN_CONFIDENCE = config['min_confidence']+ dv = config['device']++ numransacs = rdims.shape[0]+ ransidx = torch.arange(numransacs, device=dv).repeat_interleave(rdims)+ idxoffsets = torch.cat([torch.tensor([0], device=dv), torch.cumsum(rdims[:-1], dim=0)], dim=0)++ rand_samples_rel = draw_first_k_couples(iters, rdims, dv)+ rand_samples_abs = rand_samples_rel + idxoffsets+ sampled_x = torch.transpose(+ xsamples[rand_samples_abs], dim0=1, dim1=2+ ) # (niters, 2, numransacs, 2) -> (niters, numransacs, 2, 2)+ sampled_y = torch.transpose(ysamples[rand_samples_abs], dim0=1, dim1=2)++ # minimal fit for sampled_x @ A^T = sampled_y+ affinities_fit = torch.transpose(batch_2x2_inv(sampled_x, check_dets=True) @ sampled_y, -1, -2)+ if not refit:+ eigenvals, eigenvecs = batch_2x2_ellipse(affinities_fit)+ bad_ones = (eigenvals[..., 1] < 1 / DET_THR**2) | (eigenvals[..., 0] > DET_THR**2)+ affinities_fit[bad_ones] = torch.eye(2, device=dv)+ y_pred = (affinities_fit[:, ransidx] @ xsamples.unsqueeze(-1)).squeeze(-1)++ residuals = torch.norm(y_pred - ysamples, dim=-1) # (niters, numsamples)++ inl_ransidx, inl_sampleidx, inl_counts, inl_iters, inl_confidence = confidence_based_inlier_selection(+ residuals, ransidx, rdims, idxoffsets, dv=dv, min_confidence=MIN_CONFIDENCE+ )++ if len(inl_sampleidx) == 0:+ # If no inliers have been found, there is nothing to re-fit!+ refit = False++ if not refit:+ return (+ inl_sampleidx,+ affinities_fit[inl_iters, torch.arange(inl_iters.shape[0], device=dv)],+ inl_confidence,+ inl_counts,+ )++ # Organize inliers found into a matrix for efficient GPU re-fitting.+ # Cope with the irregular number of inliers per sample by padding with zeros+ padded_inlier_x, padded_inlier_y = sample_padded_inliers(+ xsamples, ysamples, inl_counts, inl_ransidx, inl_sampleidx, numransacs, dv+ )++ # A @ pad_x.T = pad_y.T+ # A = pad_y.T @ pad_x @ (pad_x.T @ pad_x)^-1+ refit_affinity = (+ padded_inlier_y.transpose(-2, -1)+ @ padded_inlier_x+ @ batch_2x2_inv(padded_inlier_x.transpose(-2, -1) @ padded_inlier_x, check_dets=True)+ )++ # Filter out degenerate affinities with large scale changes+ eigenvals, eigenvecs = batch_2x2_ellipse(refit_affinity)+ bad_ones = (eigenvals[..., 1] < 1 / DET_THR**2) | (eigenvals[..., 0] > DET_THR**2)+ refit_affinity[bad_ones] = torch.eye(2, device=dv, dtype=refit_affinity.dtype)+ y_pred = (refit_affinity[ransidx] @ xsamples.unsqueeze(-1)).squeeze(-1)++ residuals = torch.norm(y_pred - ysamples, dim=-1)++ inl_ransidx, inl_sampleidx, inl_counts, inl_iters, inl_confidence = confidence_based_inlier_selection(+ residuals.unsqueeze(0), ransidx, rdims, idxoffsets, dv=dv, min_confidence=MIN_CONFIDENCE+ )+ return inl_sampleidx, refit_affinity, inl_confidence, inl_countsdiff --git a/kornia/feature/adalam/utils.py b/kornia/feature/adalam/utils.pynew file mode 100644index 000000000..b30736ee9--- /dev/null+++ b/kornia/feature/adalam/utils.py@@ -0,0 +1,133 @@+import math++import torch+++def arange_sequence(ranges):+ """+ returns a sequence of the ranges specified by the argument.+ Example:+ [2, 5, 1, 2] -> [0, 1, 0, 1, 2, 3, 4, 0, 0, 1]+ """+ maxcnt = torch.max(ranges).item()+ numuni = ranges.shape[0]+ complete_ranges = torch.arange(maxcnt, device=ranges.device).unsqueeze(0).expand(numuni, -1)++ return complete_ranges[complete_ranges < ranges.unsqueeze(-1)]+++def dist_matrix(d1, d2, is_normalized=False):+ if is_normalized:+ return 2 - 2.0 * d1 @ d2.t()+ x_norm = (d1**2).sum(1).view(-1, 1)+ y_norm = (d2**2).sum(1).view(1, -1)+ # print(x_norm, y_norm)+ distmat = x_norm + y_norm - 2.0 * d1 @ d2.t()+ # distmat[torch.isnan(distmat)] = np.inf+ return distmat+++def orientation_diff(o1, o2):+ diff = o2 - o1+ diff[diff < -180] += 360+ diff[diff >= 180] -= 360+ return diff+++def piecewise_arange(piecewise_idxer):+ """+ count repeated indices+ Example:+ [0, 0, 0, 3, 3, 3, 3, 1, 1, 2] -> [0, 1, 2, 0, 1, 2, 3, 0, 1, 0]+ """+ dv = piecewise_idxer.device+ # print(piecewise_idxer)+ uni, counts = torch.unique_consecutive(piecewise_idxer, return_counts=True)+ # print(counts)+ maxcnt = torch.max(counts).item()+ numuni = uni.shape[0]+ tmp = torch.zeros(size=(numuni, maxcnt), device=dv).bool()+ ranges = torch.arange(maxcnt, device=dv).unsqueeze(0).expand(numuni, -1)+ tmp[ranges < counts.unsqueeze(-1)] = True+ return ranges[tmp]+++def batch_2x2_inv(m, check_dets=False):+ a = m[..., 0, 0]+ b = m[..., 0, 1]+ c = m[..., 1, 0]+ d = m[..., 1, 1]+ minv = torch.empty_like(m)+ det = a * d - b * c+ if check_dets:+ det[torch.abs(det) < 1e-10] = 1e-10+ minv[..., 0, 0] = d+ minv[..., 1, 1] = a+ minv[..., 0, 1] = -b+ minv[..., 1, 0] = -c+ return minv / det.unsqueeze(-1).unsqueeze(-1)+++def batch_2x2_Q(m):+ return batch_2x2_inv(batch_2x2_invQ(m), check_dets=True)+++def batch_2x2_invQ(m):+ return m @ m.transpose(-1, -2)+++def batch_2x2_det(m):+ a = m[..., 0, 0]+ b = m[..., 0, 1]+ c = m[..., 1, 0]+ d = m[..., 1, 1]+ return a * d - b * c+++def batch_2x2_ellipse(m):+ am = m[..., 0, 0]+ bm = m[..., 0, 1]+ cm = m[..., 1, 0]+ dm = m[..., 1, 1]++ a = am**2 + bm**2+ b = am * cm + bm * dm+ d = cm**2 + dm**2++ trh = (a + d) / 2+ # det = a * d - b * c+ sqrtdisc = torch.sqrt(((a - d) / 2) ** 2 + b**2)++ eigenvals = torch.stack([trh + sqrtdisc, trh - sqrtdisc], dim=-1).clamp(min=0)+ dens = eigenvals - a.unsqueeze(-1)+ dens[torch.abs(dens) < 1e-6] = 1e-6+ eigenvecs = torch.stack([b.unsqueeze(-1) / dens, torch.ones_like(dens)], dim=-2)+ eigenvecs = eigenvecs / torch.norm(eigenvecs, dim=-2, keepdim=True)++ # err = eigenvecs @ torch.diag_embed(eigenvals) @ eigenvecs.transpose(-2, -1) - q+ return eigenvals, eigenvecs+++def draw_first_k_couples(k: int, rdims: int, dv: torch.device):+ # exhaustive search over the first n samples:+ # n(n+1)/2 = n2/2 + n/2 couples+ # max n for which we can exhaustively sample with k couples:+ # n2/2 + n/2 = k+ # n = sqrt(1/4 + 2k)-1/2 = (sqrt(8k+1)-1)/2+ max_exhaustive_search = int(math.sqrt(2 * k + 0.25) - 0.5)+ residual_search = k - max_exhaustive_search * (max_exhaustive_search + 1) / 2+ repeats = torch.cat(+ [+ torch.arange(max_exhaustive_search, dtype=torch.long, device=dv) + 1,+ torch.tensor([residual_search], dtype=torch.long),+ ]+ )+ idx_sequence = torch.stack([repeats.repeat_interleave(repeats), arange_sequence(repeats)], dim=-1)+ return torch.remainder(idx_sequence.unsqueeze(-1), rdims)+++def random_samples_indices(iters, rdims, dv):+ rands = torch.rand(size=(iters, 2, rdims.shape[0]), device=dv)+ scaled_rands = rands * (rdims - 1e-8).float()+ rand_samples_rel = scaled_rands.long()+ return rand_samples_reldiff --git a/kornia/feature/affine_shape.py b/kornia/feature/affine_shape.pyindex 14d631e19..63e873717 100644--- a/kornia/feature/affine_shape.py+++ b/kornia/feature/affine_shape.py@@ -7,7 +7,7 @@ import torch.nn as nnfrom kornia.filters.kernels import get_gaussian_kernel2dfrom kornia.filters.sobel import SpatialGradient-from kornia.testing import KORNIA_CHECK_SHAPE+from kornia.testing import KORNIA_CHECK_LAF, KORNIA_CHECK_SHAPEfrom .laf import (ellipse_to_laf,@@ -15,7 +15,6 @@ from .laf import (get_laf_orientation,get_laf_scale,make_upright,- raise_error_if_laf_is_not_valid,scale_laf,set_laf_orientation,)@@ -129,7 +128,7 @@ class LAFAffineShapeEstimator(nn.Module):Returns:torch.Tensor: laf_out shape [BxNx2x3]"""- raise_error_if_laf_is_not_valid(laf)+ KORNIA_CHECK_LAF(laf)KORNIA_CHECK_SHAPE(img, ["B", "1", "H", "W"])B, N = laf.shape[:2]PS: int = self.patch_size@@ -222,7 +221,7 @@ class LAFAffNetShapeEstimator(nn.Module):Returns:laf_out shape [BxNx2x3]"""- raise_error_if_laf_is_not_valid(laf)+ KORNIA_CHECK_LAF(laf)KORNIA_CHECK_SHAPE(img, ["B", "1", "H", "W"])B, N = laf.shape[:2]PS: int = self.patch_sizediff --git a/kornia/feature/integrated.py b/kornia/feature/integrated.pyindex 0d38e1ce1..c20a02522 100644--- a/kornia/feature/integrated.py+++ b/kornia/feature/integrated.py@@ -7,11 +7,12 @@ import torch.nn as nnfrom kornia.color import rgb_to_grayscalefrom kornia.geometry.subpix import ConvQuadInterp3dfrom kornia.geometry.transform import ScalePyramid+from kornia.testing import KORNIA_CHECK_LAFfrom .affine_shape import LAFAffNetShapeEstimatorfrom .hardnet import HardNetfrom .keynet import KeyNetDetector-from .laf import extract_patches_from_pyramid, get_laf_center, raise_error_if_laf_is_not_valid, scale_laf+from .laf import extract_patches_from_pyramid, get_laf_center, scale_laffrom .orientation import LAFOrienter, OriNet, PassLAFfrom .responses import BlobDoG, CornerGFTTfrom .scale_space_detector import ScaleSpaceDetector@@ -38,7 +39,7 @@ def get_laf_descriptors(Returns:Local descriptors of shape :math:`(B,N,D)` where :math:`D` is descriptor size."""- raise_error_if_laf_is_not_valid(lafs)+ KORNIA_CHECK_LAF(lafs)patch_descriptor = patch_descriptor.to(img)patch_descriptor.eval()diff --git a/kornia/feature/laf.py b/kornia/feature/laf.pyindex f498c8f79..592110e78 100644--- a/kornia/feature/laf.py+++ b/kornia/feature/laf.py@@ -7,16 +7,7 @@ import torch.nn.functional as Ffrom kornia.geometry.conversions import angle_to_rotation_matrix, convert_points_from_homogeneous, rad2degfrom kornia.geometry.linalg import transform_pointsfrom kornia.geometry.transform import pyrdown-from kornia.testing import KORNIA_CHECK_SHAPE---def raise_error_if_laf_is_not_valid(laf: torch.Tensor) -> None:- """Auxiliary function, which verifies that input.-- Args:- laf: [BxNx2x3] shape.- """- KORNIA_CHECK_SHAPE(laf, ["B", "N", "2", "3"])+from kornia.testing import KORNIA_CHECK_LAF, KORNIA_CHECK_SHAPEdef get_laf_scale(LAF: torch.Tensor) -> torch.Tensor:@@ -36,7 +27,7 @@ def get_laf_scale(LAF: torch.Tensor) -> torch.Tensor:>>> input = torch.ones(1, 5, 2, 3) # BxNx2x3>>> output = get_laf_scale(input) # BxNx1x1"""- raise_error_if_laf_is_not_valid(LAF)+ KORNIA_CHECK_LAF(LAF)eps = 1e-10out = LAF[..., 0:1, 0:1] * LAF[..., 1:2, 1:2] - LAF[..., 1:2, 0:1] * LAF[..., 0:1, 1:2] + epsreturn out.abs().sqrt()@@ -59,7 +50,7 @@ def get_laf_center(LAF: torch.Tensor) -> torch.Tensor:>>> input = torch.ones(1, 5, 2, 3) # BxNx2x3>>> output = get_laf_center(input) # BxNx2"""- raise_error_if_laf_is_not_valid(LAF)+ KORNIA_CHECK_LAF(LAF)out: torch.Tensor = LAF[..., 2]return out@@ -81,7 +72,7 @@ def get_laf_orientation(LAF: torch.Tensor) -> torch.Tensor:>>> input = torch.ones(1, 5, 2, 3) # BxNx2x3>>> output = get_laf_orientation(input) # BxNx1"""- raise_error_if_laf_is_not_valid(LAF)+ KORNIA_CHECK_LAF(LAF)angle_rad: torch.Tensor = torch.atan2(LAF[..., 0, 1], LAF[..., 0, 0])return rad2deg(angle_rad).unsqueeze(-1)@@ -100,7 +91,7 @@ def set_laf_orientation(LAF: torch.Tensor, angles_degrees: torch.Tensor) -> torc- Input: :math: `(B, N, 2, 3)`, `(B, N, 1)`- Output: :math: `(B, N, 2, 3)`"""- raise_error_if_laf_is_not_valid(LAF)+ KORNIA_CHECK_LAF(LAF)B, N = LAF.shape[:2]rotmat: torch.Tensor = angle_to_rotation_matrix(angles_degrees).view(B * N, 2, 2)laf_out: torch.Tensor = torch.cat(@@ -161,7 +152,7 @@ def scale_laf(laf: torch.Tensor, scale_coef: Union[float, torch.Tensor]) -> torc"""if (type(scale_coef) is not float) and (type(scale_coef) is not torch.Tensor):raise TypeError("scale_coef should be float or torch.Tensor " "Got {}".format(type(scale_coef)))- raise_error_if_laf_is_not_valid(laf)+ KORNIA_CHECK_LAF(laf)centerless_laf: torch.Tensor = laf[:, :, :2, :2]return torch.cat([scale_coef * centerless_laf, laf[:, :, :, 2:]], dim=3)@@ -184,7 +175,7 @@ def make_upright(laf: torch.Tensor, eps: float = 1e-9) -> torch.Tensor:>>> input = torch.ones(1, 5, 2, 3) # BxNx2x3>>> output = make_upright(input) # BxNx2x3"""- raise_error_if_laf_is_not_valid(laf)+ KORNIA_CHECK_LAF(laf)det = get_laf_scale(laf)scale = det# The function is equivalent to doing 2x2 SVD and resetting rotation@@ -267,7 +258,7 @@ def laf_to_boundary_points(LAF: torch.Tensor, n_pts: int = 50) -> torch.Tensor:- Input: :math:`(B, N, 2, 3)`- Output: :math:`(B, N, n_pts, 2)`"""- raise_error_if_laf_is_not_valid(LAF)+ KORNIA_CHECK_LAF(LAF)B, N, _, _ = LAF.size()pts = torch.cat([@@ -308,7 +299,7 @@ def get_laf_pts_to_draw(LAF: torch.Tensor, img_idx: int = 0):plt.show()"""# TODO: Refactor doctest- raise_error_if_laf_is_not_valid(LAF)+ KORNIA_CHECK_LAF(LAF)pts = laf_to_boundary_points(LAF[img_idx : img_idx + 1])[0]pts_np = pts.detach().permute(1, 0, 2).cpu().numpy()return (pts_np[..., 0], pts_np[..., 1])@@ -336,7 +327,7 @@ def denormalize_laf(LAF: torch.Tensor, images: torch.Tensor) -> torch.Tensor:- Input: :math:`(B, N, 2, 3)`- Output: :math:`(B, N, 2, 3)`"""- raise_error_if_laf_is_not_valid(LAF)+ KORNIA_CHECK_LAF(LAF)_, _, h, w = images.size()wf = float(w)hf = float(h)@@ -368,7 +359,7 @@ def normalize_laf(LAF: torch.Tensor, images: torch.Tensor) -> torch.Tensor:- Input: :math:`(B, N, 2, 3)`- Output: :math:`(B, N, 2, 3)`"""- raise_error_if_laf_is_not_valid(LAF)+ KORNIA_CHECK_LAF(LAF)_, _, h, w = images.size()wf: float = float(w)hf: float = float(h)@@ -390,7 +381,7 @@ def generate_patch_grid_from_normalized_LAF(img: torch.Tensor, LAF: torch.TensorReturns:grid"""- raise_error_if_laf_is_not_valid(LAF)+ KORNIA_CHECK_LAF(LAF)B, N, _, _ = LAF.size()_, ch, h, w = img.size()@@ -420,7 +411,7 @@ def extract_patches_simple(Returns:patches with shape :math:`(B, N, CH, PS,PS)`."""- raise_error_if_laf_is_not_valid(laf)+ KORNIA_CHECK_LAF(laf)if normalize_lafs_before_extraction:nlaf: torch.Tensor = normalize_laf(laf, img)else:@@ -458,7 +449,7 @@ def extract_patches_from_pyramid(Returns:patches with shape :math:`(B, N, CH, PS,PS)`."""- raise_error_if_laf_is_not_valid(laf)+ KORNIA_CHECK_LAF(laf)if normalize_lafs_before_extraction:nlaf: torch.Tensor = normalize_laf(laf, img)else:@@ -504,7 +495,7 @@ def laf_is_inside_image(laf: torch.Tensor, images: torch.Tensor, border: int = 0Returns:mask with shape :math:`(B, N)`."""- raise_error_if_laf_is_not_valid(laf)+ KORNIA_CHECK_LAF(laf)_, _, h, w = images.size()pts: torch.Tensor = laf_to_boundary_points(laf, 12)good_lafs_mask: torch.Tensor = (@@ -524,7 +515,7 @@ def laf_to_three_points(laf: torch.Tensor):Returns:threepts :math:`(B, N, 2, 3)`."""- raise_error_if_laf_is_not_valid(laf)+ KORNIA_CHECK_LAF(laf)three_pts: torch.Tensor = torch.stack([laf[..., 2] + laf[..., 0], laf[..., 2] + laf[..., 1], laf[..., 2]], dim=-1)return three_pts@@ -589,7 +580,7 @@ def perspective_transform_lafs(trans_01: torch.Tensor, lafs_1: torch.Tensor) ->torch.Size([2, 3, 3])>>> lafs_0 = perspective_transform_lafs(trans_01, lafs_1) # BxNx2x3"""- raise_error_if_laf_is_not_valid(lafs_1)+ KORNIA_CHECK_LAF(lafs_1)if not torch.is_tensor(trans_01):raise TypeError("Input type is not a torch.Tensor")diff --git a/kornia/feature/matching.py b/kornia/feature/matching.pyindex f3940d386..fbf681317 100644--- a/kornia/feature/matching.py+++ b/kornia/feature/matching.py@@ -6,6 +6,8 @@ import torch.nn as nnfrom kornia.feature.laf import get_laf_centerfrom kornia.testing import KORNIA_CHECK_DM_DESC, KORNIA_CHECK_SHAPE, Tensor+from .adalam import get_adalam_default_config, match_adalam+def _get_default_fginn_params():config = {"th": 0.85, "mutual": False, "spatial_th": 10.0}@@ -328,7 +330,7 @@ class GeometryAwareDescriptorMatcher(nn.Module):th: threshold on distance ratio, or other quality measure."""- known_modes = ['fginn']+ known_modes = ['fginn', "adalam"]def __init__(self, match_mode: str = 'fginn', params: Dict = {}) -> None:super().__init__()@@ -355,6 +357,10 @@ class GeometryAwareDescriptorMatcher(nn.Module):params = _get_default_fginn_params()params.update(self.params)out = match_fginn(desc1, desc2, lafs1, lafs2, params['th'], params['spatial_th'], params['mutual'])+ elif self.match_mode == 'adalam':+ params = get_adalam_default_config()+ params.update(self.params)+ out = match_adalam(desc1, desc2, lafs1, lafs2, config=params)else:raise NotImplementedErrorreturn outdiff --git a/kornia/feature/orientation.py b/kornia/feature/orientation.pyindex b651043be..9d9eb0447 100644--- a/kornia/feature/orientation.py+++ b/kornia/feature/orientation.py@@ -8,9 +8,9 @@ import torch.nn.functional as Ffrom kornia.constants import pifrom kornia.filters import SpatialGradient, get_gaussian_kernel2dfrom kornia.geometry import rad2deg-from kornia.testing import KORNIA_CHECK_SHAPE+from kornia.testing import KORNIA_CHECK_LAF, KORNIA_CHECK_SHAPE-from .laf import extract_patches_from_pyramid, get_laf_orientation, raise_error_if_laf_is_not_valid, set_laf_orientation+from .laf import extract_patches_from_pyramid, get_laf_orientation, set_laf_orientationurls: Dict[str, str] = {}urls["orinet"] = "https://github.com/ducha-aiki/affnet/raw/master/pretrained/OriNet.pth"@@ -227,7 +227,7 @@ class LAFOrienter(nn.Module):Returns:laf_out, shape [BxNx2x3]"""- raise_error_if_laf_is_not_valid(laf)+ KORNIA_CHECK_LAF(laf)KORNIA_CHECK_SHAPE(img, ["B", "C", "H", "W"])if laf.size(0) != img.size(0):raise ValueError(f"Batch size of laf and img should be the same. Got {img.size(0)}, {laf.size(0)}")diff --git a/kornia/testing/__init__.py b/kornia/testing/__init__.pyindex 9b014aa1f..96a351b01 100644--- a/kornia/testing/__init__.py+++ b/kornia/testing/__init__.py@@ -276,3 +276,12 @@ def KORNIA_CHECK_DM_DESC(desc1: Tensor, desc2: Tensor, dm: Tensor):consistent with descriptors shape: desc1 {desc1.shape}desc2 {desc2.shape}"""raise TypeError(message)+++def KORNIA_CHECK_LAF(laf: Tensor) -> None:+ """Auxiliary function, which verifies that input.++ Args:+ laf: [BxNx2x3] shape.+ """+ KORNIA_CHECK_SHAPE(laf, ["B", "N", "2", "3"])diff --git a/test/feature/test_matching.py b/test/feature/test_matching.pyindex ed4929fbb..2f3a87186 100644--- a/test/feature/test_matching.py+++ b/test/feature/test_matching.py@@ -7,6 +7,7 @@ from kornia.feature.laf import laf_from_center_scale_orifrom kornia.feature.matching import (DescriptorMatcher,GeometryAwareDescriptorMatcher,+ match_adalam,match_fginn,match_mnn,match_nn,@@ -315,7 +316,40 @@ class TestMatchFGINN:center2 = torch.rand(1, 7, 2, device=device)lafs1 = laf_from_center_scale_ori(center1)lafs2 = laf_from_center_scale_ori(center2)- matcher = DescriptorMatcher('fginn', 0.8).to(device)- matcher_jit = torch.jit.script(DescriptorMatcher('fginn', 0.8).to(device))+ matcher = GeometryAwareDescriptorMatcher('fginn', 0.8).to(device)+ matcher_jit = torch.jit.script(GeometryAwareDescriptorMatcher('fginn', 0.8).to(device))assert_close(matcher(desc1, desc2)[0], matcher_jit(desc1, desc2, lafs1, lafs2)[0])assert_close(matcher(desc1, desc2)[1], matcher_jit(desc1, desc2, lafs1, lafs2)[1])+++class TestAdalam:+ @pytest.mark.parametrize("data", ["adalam_idxs"], indirect=True)+ def test_real(self, device, dtype, data):+ torch.random.manual_seed(0)+ # This is not unit test, but that is quite good integration test+ data_dev = utils.dict_to(data, device, dtype)+ with torch.no_grad():+ dists, idxs = match_adalam(data_dev['descs1'], data_dev['descs2'], data_dev['lafs1'], data_dev['lafs2'])+ assert idxs.shape[1] == 2+ assert dists.shape[1] == 1+ assert idxs.shape[0] == dists.shape[0]+ assert dists.shape[0] <= data_dev['descs1'].shape[0]+ assert dists.shape[0] <= data_dev['descs2'].shape[0]+ expected_idxs = data_dev['expected_idxs'].long()+ assert_close(idxs, expected_idxs, rtol=1e-4, atol=1e-4)++ @pytest.mark.parametrize("data", ["adalam_idxs"], indirect=True)+ def test_module(self, device, dtype, data):+ torch.random.manual_seed(0)+ # This is not unit test, but that is quite good integration test+ data_dev = utils.dict_to(data, device, dtype)+ matcher = GeometryAwareDescriptorMatcher('adalam').to(device, dtype)+ with torch.no_grad():+ dists, idxs = matcher(data_dev['descs1'], data_dev['descs2'], data_dev['lafs1'], data_dev['lafs2'])+ assert idxs.shape[1] == 2+ assert dists.shape[1] == 1+ assert idxs.shape[0] == dists.shape[0]+ assert dists.shape[0] <= data_dev['descs1'].shape[0]+ assert dists.shape[0] <= data_dev['descs2'].shape[0]+ expected_idxs = data_dev['expected_idxs'].long()+ assert_close(idxs, expected_idxs, rtol=1e-4, atol=1e-4)