Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

ScaleSpaceDetector -> Fast ScaleSpaceDetector (#2154)

Dmytro Mishkind66be9bf5a9c
diff --git a/docs/source/feature.rst b/docs/source/feature.rst
index f68037258..45d96e81f 100644
--- a/docs/source/feature.rst
+++ b/docs/source/feature.rst
@@ -10,6 +10,7 @@ Detectors
.. autofunction:: harris_response
.. autofunction:: hessian_response
.. autofunction:: dog_response
+.. autofunction:: dog_response_single
.. autoclass:: SOLD2_detector
:members: forward
@@ -56,14 +57,20 @@ Matching
.. autoclass:: SIFTFeature
:members: forward
+.. autoclass:: SIFTFeatureScaleSpace
+ :members: forward
+
.. autoclass:: GFTTAffNetHardNet
:members: forward
+.. autoclass::HesAffNetHardNet
+ :members: forward
+
.. autoclass:: KeyNetAffNetHardNet
- :members: forward
+ :members: forward
.. autoclass:: KeyNetHardNet
- :members: forward
+ :members: forward
.. autoclass:: LocalFeatureMatcher
:members: forward
@@ -100,13 +107,21 @@ Module
.. autoclass:: CornerGFTT
.. autoclass:: CornerHarris
.. autoclass:: BlobDoG
+.. autoclass:: BlobDoGSingle
.. autoclass:: KeyNet
.. autoclass:: FilterResponseNorm2d
.. autoclass:: TLU
-.. autoclass:: ScaleSpaceDetector
+.. autoclass:: MultiResolutionDetector
:members: forward
+ :members: remove_borders
+ :members: detect_features_on_single_level
+ :members: detect
+
+
+.. autoclass:: ScaleSpaceDetector
+ :members: forward
.. autoclass:: KeyNetDetector
:members: forward
diff --git a/kornia/feature/__init__.py b/kornia/feature/__init__.py
index 62fcf1c34..f27e3a361 100644
--- a/kornia/feature/__init__.py
+++ b/kornia/feature/__init__.py
@@ -4,12 +4,14 @@ from .hardnet import HardNet, HardNet8
from .hynet import TLU, FilterResponseNorm2d, HyNet
from .integrated import (
GFTTAffNetHardNet,
+ HesAffNetHardNet,
KeyNetAffNetHardNet,
KeyNetHardNet,
LAFDescriptor,
LocalFeature,
LocalFeatureMatcher,
SIFTFeature,
+ SIFTFeatureScaleSpace,
get_laf_descriptors,
)
from .keynet import KeyNet, KeyNetDetector
@@ -48,15 +50,17 @@ from .mkd import MKDDescriptor
from .orientation import LAFOrienter, OriNet, PatchDominantGradientOrientation
from .responses import (
BlobDoG,
+ BlobDoGSingle,
BlobHessian,
CornerGFTT,
CornerHarris,
dog_response,
+ dog_response_single,
gftt_response,
harris_response,
hessian_response,
)
-from .scale_space_detector import PassLAF, ScaleSpaceDetector
+from .scale_space_detector import MultiResolutionDetector, PassLAF, ScaleSpaceDetector
from .siftdesc import DenseSIFTDescriptor, SIFTDescriptor
from .sold2 import SOLD2, SOLD2_detector
from .sosnet import SOSNet
@@ -74,8 +78,11 @@ __all__ = [
"get_laf_descriptors",
"LAFDescriptor",
"LocalFeature",
+ "MultiResolutionDetector",
"SIFTFeature",
+ "SIFTFeatureScaleSpace",
"GFTTAffNetHardNet",
+ "HesAffNetHardNet",
"LocalFeatureMatcher",
"SOSNet",
"KeyNet",
@@ -83,10 +90,12 @@ __all__ = [
"gftt_response",
"hessian_response",
"dog_response",
+ "dog_response_single",
"CornerHarris",
"CornerGFTT",
"BlobHessian",
"BlobDoG",
+ "BlobDoGSingle",
"extract_patches_from_pyramid",
"extract_patches_simple",
"normalize_laf",
diff --git a/kornia/feature/integrated.py b/kornia/feature/integrated.py
index b21971095..3ea67722e 100644
--- a/kornia/feature/integrated.py
+++ b/kornia/feature/integrated.py
@@ -14,8 +14,13 @@ from .hardnet import HardNet
from .keynet import KeyNetDetector
from .laf import extract_patches_from_pyramid, get_laf_center, scale_laf
from .orientation import LAFOrienter, OriNet, PassLAF
-from .responses import BlobDoG, CornerGFTT
-from .scale_space_detector import ScaleSpaceDetector
+from .responses import BlobDoG, BlobDoGSingle, BlobHessian, CornerGFTT
+from .scale_space_detector import (
+ Detector_config,
+ MultiResolutionDetector,
+ ScaleSpaceDetector,
+ get_default_detector_config,
+)
from .siftdesc import SIFTDescriptor
@@ -144,6 +149,36 @@ class LocalFeature(Module):
class SIFTFeature(LocalFeature):
"""Convenience module, which implements DoG detector + (Root)SIFT descriptor.
+ Using `kornia.feature.MultiResolutionDetector` without blur pyramid 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: Device = torch.device('cpu'),
+ config: Detector_config = get_default_detector_config(),
+ ):
+ patch_size: int = 41
+ detector = MultiResolutionDetector(
+ BlobDoGSingle(1.0, 1.6),
+ num_features,
+ config,
+ ori_module=PassLAF() if upright else LAFOrienter(19),
+ aff_module=PassLAF(),
+ ).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 SIFTFeatureScaleSpace(LocalFeature):
+ """Convenience module, which implements DoG detector + (Root)SIFT descriptor. Using
+ `kornia.feature.ScaleSpaceDetector` with blur pyramid.
+
Still not as good as OpenCV/VLFeat because of https://github.com/kornia/kornia/pull/884, but we are working on it
"""
@@ -174,15 +209,40 @@ class SIFTFeature(LocalFeature):
class GFTTAffNetHardNet(LocalFeature):
"""Convenience module, which implements GFTT detector + AffNet-HardNet descriptor."""
- def __init__(self, num_features: int = 8000, upright: bool = False, device: Device = torch.device('cpu')):
- detector = ScaleSpaceDetector(
+ def __init__(
+ self,
+ num_features: int = 8000,
+ upright: bool = False,
+ device: Device = torch.device('cpu'),
+ config: Detector_config = get_default_detector_config(),
+ ):
+ detector = MultiResolutionDetector(
+ CornerGFTT(),
num_features,
- resp_module=CornerGFTT(),
- nms_module=ConvQuadInterp3d(10, 1e-5),
- scale_pyr_module=ScalePyramid(3, 1.6, 32, double_image=False),
+ config,
+ ori_module=PassLAF() if upright else LAFOrienter(19),
+ aff_module=LAFAffNetShapeEstimator(True).eval(),
+ ).to(device)
+ descriptor = LAFDescriptor(None, patch_size=32, grayscale_descriptor=True).to(device)
+ super().__init__(detector, descriptor)
+
+
+class HesAffNetHardNet(LocalFeature):
+ """Convenience module, which implements GFTT detector + AffNet-HardNet descriptor."""
+
+ def __init__(
+ self,
+ num_features: int = 2048,
+ upright: bool = False,
+ device: Device = torch.device('cpu'),
+ config: Detector_config = get_default_detector_config(),
+ ):
+ detector = MultiResolutionDetector(
+ BlobHessian(),
+ num_features,
+ config,
ori_module=PassLAF() if upright else LAFOrienter(19),
aff_module=LAFAffNetShapeEstimator(True).eval(),
- mr_size=6.0,
).to(device)
descriptor = LAFDescriptor(None, patch_size=32, grayscale_descriptor=True).to(device)
super().__init__(detector, descriptor)
diff --git a/kornia/feature/keynet.py b/kornia/feature/keynet.py
index e92f5b4bd..bd19c64b5 100644
--- a/kornia/feature/keynet.py
+++ b/kornia/feature/keynet.py
@@ -1,30 +1,23 @@
-import math
-from typing import List, Optional, Tuple
+from typing import List, Optional
import torch
import torch.nn as nn
import torch.nn.functional as F
from typing_extensions import TypedDict
-from kornia.core import Module, Tensor, concatenate, tensor, where, zeros
+from kornia.core import Module, Tensor, concatenate
from kornia.filters import SpatialGradient
-from kornia.geometry.subpix import NonMaximaSuppression2d
from kornia.geometry.transform import pyrdown
from kornia.utils.helpers import map_location_to_cpu
-from .laf import laf_from_center_scale_ori
-from .orientation import PassLAF
+from .scale_space_detector import Detector_config, MultiResolutionDetector, get_default_detector_config
class KeyNet_conf(TypedDict):
num_filters: int
num_levels: int
kernel_size: int
- nms_size: int
- pyramid_levels: int
- up_levels: int
- scale_factor_levels: float
- s_mult: float
+ Detector_conf: Detector_config
keynet_default_config: KeyNet_conf = {
@@ -33,11 +26,7 @@ keynet_default_config: KeyNet_conf = {
'num_levels': 3,
'kernel_size': 5,
# Extraction Parameters
- 'nms_size': 15,
- 'pyramid_levels': 4,
- 'up_levels': 1,
- 'scale_factor_levels': math.sqrt(2),
- 's_mult': 22.0,
+ 'Detector_conf': get_default_detector_config(),
}
KeyNet_URL = "https://github.com/axelBarroso/Key.Net-Pytorch/raw/main/model/weights/keynet_pytorch.pth"
@@ -173,7 +162,7 @@ class KeyNet(Module):
return scores
-class KeyNetDetector(Module):
+class KeyNetDetector(MultiResolutionDetector):
"""Multi-scale feature detector based on KeyNet.
This is based on the original code from paper
@@ -198,128 +187,5 @@ class KeyNetDetector(Module):
ori_module: Optional[Module] = None,
aff_module: Optional[Module] = None,
):
- super().__init__()
- self.model = KeyNet(pretrained, keynet_conf)
- # Load extraction configuration
- self.num_pyramid_levels = keynet_conf['pyramid_levels']
- self.num_upscale_levels = keynet_conf['up_levels']
- self.scale_factor_levels = keynet_conf['scale_factor_levels']
- self.mr_size = keynet_conf['s_mult']
- self.nms_size = keynet_conf['nms_size']
- self.nms = NonMaximaSuppression2d((self.nms_size, self.nms_size))
- self.num_features = num_features
-
- if ori_module is None:
- self.ori: Module = PassLAF()
- else:
- self.ori = ori_module
-
- if aff_module is None:
- self.aff: Module = PassLAF()
- else:
- self.aff = aff_module
-
- def remove_borders(self, score_map, borders: int = 15):
- """It removes the borders of the image to avoid detections on the corners."""
- mask = torch.zeros_like(score_map)
- mask[:, :, borders:-borders, borders:-borders] = 1
- return mask * score_map
-
- def detect_features_on_single_level(
- self, level_img: Tensor, num_kp: int, factor: Tuple[float, float]
- ) -> Tuple[Tensor, Tensor]:
- det_map = self.nms(self.remove_borders(self.model(level_img)))
- device = level_img.device
- dtype = level_img.dtype
- yx = det_map.nonzero()[:, 2:].t()
- scores = det_map[0, 0, yx[0], yx[1]] # keynet supports only non-batched images
-
- scores_sorted, indices = torch.sort(scores, descending=True)
-
- indices = indices[where(scores_sorted > 0.0)]
- yx = yx[:, indices[:num_kp]].t()
- current_kp_num = len(yx)
- xy_projected = yx.view(1, current_kp_num, 2).flip(2) * tensor(factor, device=device, dtype=dtype)
- scale_factor = 0.5 * (factor[0] + factor[1])
- scale = scale_factor * self.mr_size * torch.ones(1, current_kp_num, 1, 1, device=device, dtype=dtype)
- lafs = laf_from_center_scale_ori(xy_projected, scale, zeros(1, current_kp_num, 1, device=device, dtype=dtype))
- return scores_sorted[:num_kp], lafs
-
- def detect(self, img: Tensor, mask: Optional[Tensor] = None) -> Tuple[Tensor, Tensor]:
- # Compute points per level
- num_features_per_level: List[float] = []
- tmp = 0.0
- factor_points = self.scale_factor_levels**2
- levels = self.num_pyramid_levels + self.num_upscale_levels + 1
- for idx_level in range(levels):
- tmp += factor_points ** (-1 * (idx_level - self.num_upscale_levels))
- nf = self.num_features * factor_points ** (-1 * (idx_level - self.num_upscale_levels))
- num_features_per_level.append(nf)
- num_features_per_level = list(map(lambda x: int(x / tmp), num_features_per_level))
-
- _, _, h, w = img.shape
- img_up = img
- cur_img = img
- all_responses: List[Tensor] = []
- all_lafs: List[Tensor] = []
- # Extract features from the upper levels
- for idx_level in range(self.num_upscale_levels):
- nf = num_features_per_level[len(num_features_per_level) - self.num_pyramid_levels - 1 - (idx_level + 1)]
- num_points_level = int(nf)
-
- # Resize input image
- up_factor = self.scale_factor_levels ** (1 + idx_level)
- nh, nw = int(h * up_factor), int(w * up_factor)
- up_factor_kpts = (float(w) / float(nw), float(h) / float(nh))
- img_up = F.interpolate(img_up, (nh, nw), mode='bilinear', align_corners=False)
-
- cur_scores, cur_lafs = self.detect_features_on_single_level(img_up, num_points_level, up_factor_kpts)
-
- all_responses.append(cur_scores.view(1, -1))
- all_lafs.append(cur_lafs)
-
- # Extract features from the downsampling pyramid
- for idx_level in range(self.num_pyramid_levels + 1):
- if idx_level > 0:
- cur_img = pyrdown(cur_img, factor=self.scale_factor_levels)
- _, _, nh, nw = cur_img.shape
- factor = (float(w) / float(nw), float(h) / float(nh))
- else:
- factor = (1.0, 1.0)
-
- num_points_level = int(num_features_per_level[idx_level])
- if idx_level > 0 or (self.num_upscale_levels > 0):
- nf2 = [num_features_per_level[a] for a in range(0, idx_level + 1 + self.num_upscale_levels)]
- res_points = Tensor(nf2).sum().item()
- num_points_level = int(res_points)
-
- cur_scores, cur_lafs = self.detect_features_on_single_level(cur_img, num_points_level, factor)
- all_responses.append(cur_scores.view(1, -1))
- all_lafs.append(cur_lafs)
- responses: Tensor = concatenate(all_responses, 1)
- lafs: Tensor = concatenate(all_lafs, 1)
- if lafs.shape[1] > self.num_features:
- responses, idxs = torch.topk(responses, k=self.num_features, dim=1)
- lafs = torch.gather(lafs, 1, idxs.unsqueeze(-1).unsqueeze(-1).repeat(1, 1, 2, 3))
- return responses, lafs
-
- def forward(self, img: Tensor, mask: Optional[Tensor] = None) -> Tuple[Tensor, Tensor]:
- """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 to extract features with shape [1xCxHxW]. KeyNetDetector does not support batch processing,
- because the number of detections is different on each image.
- mask: a mask with weights where to apply the response function. The shape must be the same as
- the input image.
-
- Returns:
- lafs: shape [1xNx2x3]. Detected local affine frames.
- responses: shape [1xNx1]. Response function values for corresponding lafs
- """
- if img.shape[0] != 1:
- raise ValueError("KeyNet supports only single-image input")
- responses, lafs = self.detect(img, mask)
- lafs = self.aff(lafs, img)
- lafs = self.ori(lafs, img)
- return lafs, responses
+ model = KeyNet(pretrained, keynet_conf)
+ super().__init__(model, num_features, keynet_conf['Detector_conf'], ori_module, aff_module)
diff --git a/kornia/feature/responses.py b/kornia/feature/responses.py
index 2078ea2e4..a474176db 100644
--- a/kornia/feature/responses.py
+++ b/kornia/feature/responses.py
@@ -7,6 +7,18 @@ from kornia.filters import gaussian_blur2d, spatial_gradient
from kornia.testing import KORNIA_CHECK_SHAPE
+def _get_kernel_size(sigma: float):
+ ksize = int(2.0 * 4.0 * sigma + 1.0)
+
+ # matches OpenCV, but may cause padding problem for small images
+ # PyTorch does not allow to pad more than original size.
+ # Therefore there is a hack in forward function
+
+ if ksize % 2 == 0:
+ ksize += 1
+ return ksize
+
+
def harris_response(
input: Tensor, k: Union[Tensor, float] = 0.04, grads_mode: str = 'sobel', sigmas: Optional[Tensor] = None
) -> Tensor:
@@ -251,6 +263,25 @@ def dog_response(input: Tensor) -> Tensor:
return input[:, :, 1:] - input[:, :, :-1]
+def dog_response_single(input: Tensor, sigma1: float = 1.0, sigma2: float = 1.6) -> Tensor:
+ r"""Compute the Difference-of-Gaussian response.
+
+ Args:
+ input: a given the gaussian 4d tensor :math:`(B, C, H, W)`.
+ sigma1: lower gaussian sigma
+ sigma2: bigger gaussian sigma
+
+ Return:
+ the response map per channel with shape :math:`(B, C, H, W)`.
+ """
+ KORNIA_CHECK_SHAPE(input, ["B", "C", "H", "W"])
+ ks1 = _get_kernel_size(sigma1)
+ ks2 = _get_kernel_size(sigma1)
+ g1 = gaussian_blur2d(input, (ks1, ks1), (sigma1, sigma1))
+ g2 = gaussian_blur2d(input, (ks2, ks2), (sigma2, sigma2))
+ return g2 - g1
+
+
class BlobDoG(Module):
r"""Module that calculates Difference-of-Gaussians blobs.
@@ -268,6 +299,24 @@ class BlobDoG(Module):
return dog_response(input)
+class BlobDoGSingle(Module):
+ r"""Module that calculates Difference-of-Gaussians blobs.
+
+ See :func:`~kornia.feature.dog_response_single` for details.
+ """
+
+ def __init__(self, sigma1: float = 1.0, sigma2: float = 1.6) -> None:
+ super().__init__()
+ self.sigma1 = sigma1
+ self.sigma2 = sigma2
+
+ def __repr__(self) -> str:
+ return f'{self.__class__.__name__}, sigma1={self.sigma1}, sigma2={self.sigma2})'
+
+ def forward(self, input: Tensor, sigmas: Optional[Tensor] = None) -> Tensor:
+ return dog_response_single(input, self.sigma1, self.sigma2)
+
+
class CornerHarris(Module):
r"""Module that calculates Harris corners.
diff --git a/kornia/feature/scale_space_detector.py b/kornia/feature/scale_space_detector.py
index 9e9dc0f86..2e78ac26e 100644
--- a/kornia/feature/scale_space_detector.py
+++ b/kornia/feature/scale_space_detector.py
@@ -1,13 +1,16 @@
+import math
from typing import List, Optional, Tuple
import torch
import torch.nn.functional as F
+from typing_extensions import TypedDict
-from kornia.core import Device, Module, Tensor, concatenate, eye
-from kornia.geometry.subpix import ConvSoftArgmax3d
-from kornia.geometry.transform import ScalePyramid
+from kornia.core import Device, Module, Tensor, concatenate, eye, tensor, where, zeros
+from kornia.geometry.subpix import ConvSoftArgmax3d, NonMaximaSuppression2d
+from kornia.geometry.transform import ScalePyramid, pyrdown, resize
+from kornia.testing import KORNIA_CHECK_SHAPE
-from .laf import laf_is_inside_image
+from .laf import laf_from_center_scale_ori, laf_is_inside_image
from .orientation import PassLAF
from .responses import BlobHessian
@@ -234,3 +237,173 @@ class ScaleSpaceDetector(Module):
lafs = self.aff(lafs, img)
lafs = self.ori(lafs, img)
return lafs, responses
+
+
+class Detector_config(TypedDict):
+ nms_size: int
+ pyramid_levels: int
+ up_levels: int
+ scale_factor_levels: float
+ s_mult: float
+
+
+def get_default_detector_config() -> Detector_config:
+ return {
+ # Extraction Parameters
+ 'nms_size': 15,
+ 'pyramid_levels': 4,
+ 'up_levels': 1,
+ 'scale_factor_levels': math.sqrt(2),
+ 's_mult': 22.0,
+ }
+
+
+class MultiResolutionDetector(Module):
+ """Multi-scale feature detector, based on code from KeyNet. Can be used with any response function.
+
+ This is based on the original code from paper
+ "Key.Net: Keypoint Detection by Handcrafted and Learned CNN Filters".
+ See :cite:`KeyNet2019` for more details.
+
+ Args:
+ model: response function, such as KeyNet or BlobHessian
+ num_features: Number of features to detect.
+ conf: Dict with initiliazation parameters. Do not pass it, unless you know what you are doing`.
+ ori_module: for local feature orientation estimation. Default: :class:`~kornia.feature.PassLAF`,
+ which does nothing. See :class:`~kornia.feature.LAFOrienter` for details.
+ aff_module: for local feature affine shape estimation. Default: :class:`~kornia.feature.PassLAF`,
+ which does nothing. See :class:`~kornia.feature.LAFAffineShapeEstimator` for details.
+ """
+
+ def __init__(
+ self,
+ model: Module,
+ num_features: int = 2048,
+ config: Detector_config = get_default_detector_config(),
+ ori_module: Optional[Module] = None,
+ aff_module: Optional[Module] = None,
+ ):
+ super().__init__()
+ self.model = model
+ # Load extraction configuration
+ self.num_pyramid_levels = config['pyramid_levels']
+ self.num_upscale_levels = config['up_levels']
+ self.scale_factor_levels = config['scale_factor_levels']
+ self.mr_size = config['s_mult']
+ self.nms_size = config['nms_size']
+ self.nms = NonMaximaSuppression2d((self.nms_size, self.nms_size))
+ self.num_features = num_features
+
+ if ori_module is None:
+ self.ori: Module = PassLAF()
+ else:
+ self.ori = ori_module
+
+ if aff_module is None:
+ self.aff: Module = PassLAF()
+ else:
+ self.aff = aff_module
+
+ def remove_borders(self, score_map: Tensor, borders: int = 15) -> Tensor:
+ """It removes the borders of the image to avoid detections on the corners."""
+ mask = torch.zeros_like(score_map)
+ mask[:, :, borders:-borders, borders:-borders] = 1
+ return mask * score_map
+
+ def detect_features_on_single_level(
+ self, level_img: Tensor, num_kp: int, factor: Tuple[float, float]
+ ) -> Tuple[Tensor, Tensor]:
+ det_map = self.nms(self.remove_borders(self.model(level_img)))
+ device = level_img.device
+ dtype = level_img.dtype
+ yx = det_map.nonzero()[:, 2:].t()
+ scores = det_map[0, 0, yx[0], yx[1]] # keynet supports only non-batched images
+
+ scores_sorted, indices = torch.sort(scores, descending=True)
+
+ indices = indices[where(scores_sorted > 0.0)]
+ yx = yx[:, indices[:num_kp]].t()
+ current_kp_num = len(yx)
+ xy_projected = yx.view(1, current_kp_num, 2).flip(2) * tensor(factor, device=device, dtype=dtype)
+ scale_factor = 0.5 * (factor[0] + factor[1])
+ scale = scale_factor * self.mr_size * torch.ones(1, current_kp_num, 1, 1, device=device, dtype=dtype)
+ lafs = laf_from_center_scale_ori(xy_projected, scale, zeros(1, current_kp_num, 1, device=device, dtype=dtype))
+ return scores_sorted[:num_kp], lafs
+
+ def detect(self, img: Tensor, mask: Optional[Tensor] = None) -> Tuple[Tensor, Tensor]:
+ # Compute points per level
+ num_features_per_level: List[float] = []
+ tmp = 0.0
+ factor_points = self.scale_factor_levels**2
+ levels = self.num_pyramid_levels + self.num_upscale_levels + 1
+ for idx_level in range(levels):
+ tmp += factor_points ** (-1 * (idx_level - self.num_upscale_levels))
+ nf = self.num_features * factor_points ** (-1 * (idx_level - self.num_upscale_levels))
+ num_features_per_level.append(nf)
+ num_features_per_level = [int(x / tmp) for x in num_features_per_level]
+
+ _, _, h, w = img.shape
+ img_up = img
+ cur_img = img
+ all_responses: List[Tensor] = []
+ all_lafs: List[Tensor] = []
+ # Extract features from the upper levels
+ for idx_level in range(self.num_upscale_levels):
+ nf = num_features_per_level[len(num_features_per_level) - self.num_pyramid_levels - 1 - (idx_level + 1)]
+ num_points_level = int(nf)
+
+ # Resize input image
+ up_factor = self.scale_factor_levels ** (1 + idx_level)
+ nh, nw = int(h * up_factor), int(w * up_factor)
+ up_factor_kpts = (float(w) / float(nw), float(h) / float(nh))
+ img_up = resize(img_up, (nh, nw), interpolation='bilinear', align_corners=False)
+
+ cur_scores, cur_lafs = self.detect_features_on_single_level(img_up, num_points_level, up_factor_kpts)
+
+ all_responses.append(cur_scores.view(1, -1))
+ all_lafs.append(cur_lafs)
+
+ # Extract features from the downsampling pyramid
+ for idx_level in range(self.num_pyramid_levels + 1):
+ if idx_level > 0:
+ cur_img = pyrdown(cur_img, factor=self.scale_factor_levels)
+ _, _, nh, nw = cur_img.shape
+ factor = (float(w) / float(nw), float(h) / float(nh))
+ else:
+ factor = (1.0, 1.0)
+
+ num_points_level = int(num_features_per_level[idx_level])
+ if idx_level > 0 or (self.num_upscale_levels > 0):
+ nf2 = [num_features_per_level[a] for a in range(0, idx_level + 1 + self.num_upscale_levels)]
+ res_points = tensor(nf2).sum().item()
+ num_points_level = int(res_points)
+
+ cur_scores, cur_lafs = self.detect_features_on_single_level(cur_img, num_points_level, factor)
+ all_responses.append(cur_scores.view(1, -1))
+ all_lafs.append(cur_lafs)
+ responses = concatenate(all_responses, 1)
+ lafs = concatenate(all_lafs, 1)
+ if lafs.shape[1] > self.num_features:
+ responses, idxs = torch.topk(responses, k=self.num_features, dim=1)
+ lafs = torch.gather(lafs, 1, idxs[..., None, None].expand(-1, -1, 2, 3))
+ return responses, lafs
+
+ def forward(self, img: Tensor, mask: Optional[Tensor] = None) -> Tuple[Tensor, Tensor]:
+ """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 to extract features with shape [1xCxHxW]. KeyNetDetector does not support batch processing,
+ because the number of detections is different on each image.
+ mask: a mask with weights where to apply the response function. The shape must be the same as
+ the input image.
+
+ Returns:
+ lafs: shape [1xNx2x3]. Detected local affine frames.
+ responses: shape [1xNx1]. Response function values for corresponding lafs
+ """
+ KORNIA_CHECK_SHAPE(img, ["1", "C", "H", "W"])
+ responses, lafs = self.detect(img, mask)
+ lafs = self.aff(lafs, img)
+ lafs = self.ori(lafs, img)
+ return lafs, responses
diff --git a/kornia/geometry/subpix/nms.py b/kornia/geometry/subpix/nms.py
index 6897a653a..dde2241b2 100644
--- a/kornia/geometry/subpix/nms.py
+++ b/kornia/geometry/subpix/nms.py
@@ -25,7 +25,10 @@ def _get_nms_kernel3d(kd: int, ky: int, kx: int) -> Tensor:
class NonMaximaSuppression2d(Module):
- r"""Apply non maxima suppression to filter."""
+ r"""Apply non maxima suppression to filter.
+
+ Flag `minima_are_also_good` is useful, when you want to detect both maxima and minima, e.g. for DoG
+ """
kernel: Tensor
def __init__(self, kernel_size: Tuple[int, int]):
@@ -55,11 +58,10 @@ class NonMaximaSuppression2d(Module):
x_padded = pad(x, list(self.padding)[::-1], mode='replicate')
B, CH, HP, WP = x_padded.size()
- max_non_center = (
- F.conv2d(x_padded.view(B * CH, 1, HP, WP), self.kernel.to(x.device, x.dtype), stride=1)
- .view(B, CH, -1, H, W)
- .max(dim=2)[0]
+ neighborhood = F.conv2d(x_padded.view(B * CH, 1, HP, WP), self.kernel.to(x.device, x.dtype), stride=1).view(
+ B, CH, -1, H, W
)
+ max_non_center = neighborhood.max(dim=2)[0]
mask = x > max_non_center
if mask_only:
return mask
diff --git a/test/feature/test_integrated.py b/test/feature/test_integrated.py
index 87f339237..09b402936 100644
--- a/test/feature/test_integrated.py
+++ b/test/feature/test_integrated.py
@@ -25,6 +25,7 @@ from kornia.feature import (
from kornia.feature.integrated import LocalFeatureMatcher
from kornia.geometry import RANSAC, resize, transform_points
from kornia.testing import assert_close
+from kornia.utils._compat import torch_version_le
# TODO: add kornia.testing.BaseTester
@@ -256,6 +257,7 @@ class TestLocalFeatureMatcher:
assert gradcheck(proxy_forward, (patches, patches05), eps=1e-4, atol=1e-4, raise_exception=True, fast_mode=True)
+ @pytest.mark.skipif(torch_version_le(1, 9, 1), reason="Fails for bached torch.linalg.solve")
@pytest.mark.parametrize("data", ["loftr_homo"], indirect=True)
def test_real_sift(self, device, dtype, data):
torch.random.manual_seed(0)
@@ -272,11 +274,12 @@ class TestLocalFeatureMatcher:
# 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.skipif(torch_version_le(1, 9, 1), reason="Fails for bached torch.linalg.solve")
@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(1000)
+ feat = SIFTFeature(1000).to(device, dtype)
matcher = LocalFeatureMatcher(feat, DescriptorMatcher('snn', 0.8)).to(device)
ransac = RANSAC('homography', 1.0, 1024, 5).to(device, dtype)
data_dev = utils.dict_to(data, device, dtype)
@@ -298,6 +301,7 @@ class TestLocalFeatureMatcher:
# 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.skipif(torch_version_le(1, 9, 1), reason="Fails for bached torch.linalg.solve")
@pytest.mark.skipif(sys.platform == "win32", reason="this test takes so much memory in the CI with Windows")
@pytest.mark.parametrize("data", ["loftr_homo"], indirect=True)
def test_real_gftt(self, device, dtype, data):
@@ -315,6 +319,7 @@ class TestLocalFeatureMatcher:
# 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.skipif(torch_version_le(1, 9, 1), reason="Fails for bached torch.linalg.solve")
@pytest.mark.skipif(sys.platform == "win32", reason="this test takes so much memory in the CI with Windows")
@pytest.mark.parametrize("data", ["loftr_homo"], indirect=True)
def test_real_keynet(self, device, dtype, data):
diff --git a/test/feature/test_responces_local_features.py b/test/feature/test_responces_local_features.py
index f4ce89511..566617d8f 100644
--- a/test/feature/test_responces_local_features.py
+++ b/test/feature/test_responces_local_features.py
@@ -18,7 +18,7 @@ class TestCornerHarris:
harris = kornia.feature.CornerHarris(k=0.04).to(device)
assert harris(inp).shape == (2, 6, 4, 4)
- def test_corners(self, device):
+ def test_corners(self, device, dtype):
inp = torch.tensor(
[
[
@@ -34,6 +34,7 @@ class TestCornerHarris:
]
],
device=device,
+ dtype=dtype,
).float()
expected = torch.tensor(
@@ -51,12 +52,13 @@ class TestCornerHarris:
]
],
device=device,
+ dtype=dtype,
).float()
harris = kornia.feature.CornerHarris(k=0.04).to(device)
scores = harris(inp)
assert_close(scores, expected, atol=1e-4, rtol=1e-3)
- def test_corners_batch(self, device):
+ def test_corners_batch(self, device, dtype):
inp = torch.tensor(
[
[
@@ -79,6 +81,7 @@ class TestCornerHarris:
],
],
device=device,
+ dtype=dtype,
).repeat(2, 1, 1, 1)
expected = (
torch.tensor(
@@ -103,6 +106,7 @@ class TestCornerHarris:
],
],
device=device,
+ dtype=dtype,
).repeat(2, 1, 1, 1)
/ 10.0
)
@@ -142,7 +146,7 @@ class TestCornerGFTT:
shi_tomasi = kornia.feature.CornerGFTT().to(device)
assert shi_tomasi(inp).shape == (2, 6, 4, 4)
- def test_corners(self, device):
+ def test_corners(self, device, dtype):
inp = torch.tensor(
[
[
@@ -158,6 +162,7 @@ class TestCornerGFTT:
]
],
device=device,
+ dtype=dtype,
).float()
expected = torch.tensor(
@@ -175,12 +180,13 @@ class TestCornerGFTT:
]
],
device=device,
+ dtype=dtype,
).float()
shi_tomasi = kornia.feature.CornerGFTT().to(device)
scores = shi_tomasi(inp)
assert_close(scores, expected, atol=1e-4, rtol=1e-3)
- def test_corners_batch(self, device):
+ def test_corners_batch(self, device, dtype):
inp = torch.tensor(
[
[
@@ -203,6 +209,7 @@ class TestCornerGFTT:
],
],
device=device,
+ dtype=dtype,
).repeat(2, 1, 1, 1)
expected = torch.tensor(
[
@@ -226,6 +233,7 @@ class TestCornerGFTT:
],
],
device=device,
+ dtype=dtype,
).repeat(2, 1, 1, 1)
shi_tomasi = kornia.feature.CornerGFTT().to(device)
scores = shi_tomasi(inp)
@@ -260,7 +268,7 @@ class TestBlobHessian:
shi_tomasi = kornia.feature.BlobHessian().to(device)
assert shi_tomasi(inp).shape == (2, 6, 4, 4)
- def test_blobs_batch(self, device):
+ def test_blobs_batch(self, device, dtype):
inp = torch.tensor(
[
[
@@ -283,6 +291,7 @@ class TestBlobHessian:
],
],
device=device,
+ dtype=dtype,
).repeat(2, 1, 1, 1)
expected = torch.tensor(
[
@@ -306,6 +315,7 @@ class TestBlobHessian:
],
],
device=device,
+ dtype=dtype,
).repeat(2, 1, 1, 1)
shi_tomasi = kornia.feature.BlobHessian().to(device)
scores = shi_tomasi(inp)
@@ -327,3 +337,89 @@ class TestBlobHessian:
actual = op_script(img)
expected = kornia.feature.hessian_response(img)
assert_close(actual, expected)
+
+
+class TestBlobDoGSingle:
+ def test_shape(self, device):
+ inp = torch.ones(1, 3, 9, 9, device=device)
+ shi_tomasi = kornia.feature.BlobDoGSingle().to(device)
+ assert shi_tomasi(inp).shape == (1, 3, 9, 9)
+
+ def test_shape_batch(self, device):
+ inp = torch.zeros(2, 6, 9, 9, device=device)
+ shi_tomasi = kornia.feature.BlobHessian().to(device)
+ assert shi_tomasi(inp).shape == (2, 6, 9, 9)
+
+ def test_blobs_batch(self, device, dtype):
+ inp = torch.tensor(
+ [
+ [
+ [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
+ [0.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0],
+ [0.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0],
+ [0.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0],
+ [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
+ [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
+ [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
+ ],
+ [
+ [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
+ [0.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0],
+ [0.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0],
+ [0.0, 0.0, 0.0, 1.0, 1.0, 0.0, 0.0],
+ [0.0, 0.0, 0.0, 1.0, 1.0, 0.0, 0.0],
+ [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
+ [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0],
+ ],
+ ],
+ device=device,
+ dtype=dtype,
+ ).expand(2, 2, 7, 7)
+ expected = torch.tensor(
+ [
+ [
+ [
+ [0.1684, 0.0856, -0.0118, 0.0059, 0.0842, 0.0956, 0.0734],
+ [0.0856, -0.0203, -0.1385, -0.0931, 0.0428, 0.0888, 0.0733],
+ [-0.0118, -0.1385, -0.2741, -0.1998, -0.0059, 0.0768, 0.0695],
+ [0.0059, -0.0931, -0.1998, -0.1443, 0.0030, 0.0639, 0.0567],
+ [0.0842, 0.0428, -0.0059, 0.0030, 0.0421, 0.0478, 0.0367],
+ [0.0956, 0.0888, 0.0768, 0.0639, 0.0478, 0.0289, 0.0189],
+ [0.0734, 0.0733, 0.0695, 0.0567, 0.0367, 0.0189, 0.0117],
+ ],
+ [
+ [0.0725, -0.0023, -0.0226, 0.0810, 0.1114, 0.0699, 0.0471],
+ [-0.0023, -0.0868, -0.1010, 0.0361, 0.0974, 0.0758, 0.0598],
+ [-0.0226, -0.1010, -0.1408, -0.0652, 0.0030, 0.0559, 0.0777],
+ [0.0810, 0.0361, -0.0652, -0.1802, -0.1625, -0.0049, 0.0764],
+ [0.1114, 0.0974, 0.0030, -0.1625, -0.1710, -0.0092, 0.0761],
+ [0.0699, 0.0758, 0.0559, -0.0049, -0.0092, 0.0531, 0.0844],
+ [0.0471, 0.0598, 0.0777, 0.0764, 0.0761, 0.0844, 0.0865],
+ ],
+ ]
+ ],
+ device=device,
+ dtype=dtype,
+ ).expand(2, 2, 7, 7)
+ det = kornia.feature.BlobDoGSingle(1.0, 1.6).to(device)
+ scores = det(inp)
+ assert_close(scores, expected, atol=1e-4, rtol=1e-4)
+
+ def test_gradcheck(self, device):
+ batch_size, channels, height, width = 1, 2, 9, 11
+ img = torch.rand(batch_size, channels, height, width, device=device)
+ img = utils.tensor_to_gradcheck_var(img) # to var
+ assert gradcheck(
+ kornia.feature.dog_response_single, (img), raise_exception=True, nondet_tol=1e-4, fast_mode=True
+ )
+
+ @pytest.mark.jit
+ def test_jit(self, device):
+ @torch.jit.script
+ def op_script(input):
+ return kornia.feature.dog_response_single(input)
+
+ img = torch.rand(2, 3, 9, 9, device=device)
+ actual = op_script(img)
+ expected = kornia.feature.dog_response_single(img)
+ assert_close(actual, expected)
diff --git a/test/tracking/test_planar_tracking.py b/test/tracking/test_planar_tracking.py
index fcda1e282..33fe7d8f2 100644
--- a/test/tracking/test_planar_tracking.py
+++ b/test/tracking/test_planar_tracking.py
@@ -5,6 +5,7 @@ from kornia.feature import DescriptorMatcher, GFTTAffNetHardNet, LocalFeatureMat
from kornia.geometry import rescale, transform_points
from kornia.testing import assert_close
from kornia.tracking import HomographyTracker
+from kornia.utils._compat import torch_version_le
@pytest.fixture
@@ -30,6 +31,7 @@ class TestHomographyTracker:
_, success = tracker(torch.zeros_like(data["image0"]))
assert not success
+ @pytest.mark.skipif(torch_version_le(1, 9, 1), reason="Fails for bached torch.linalg.solve")
def test_real(self, device, dtype, data):
# This is not unit test, but that is quite good integration test
for k in data.keys():