Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

Remove some `# type: ignore` from `kornia.feature` (#1995)

João Gustavo A. Amorimbffb6de5b587
diff --git a/kornia/feature/integrated.py b/kornia/feature/integrated.py
index c20a02522..ed417a71c 100644
--- a/kornia/feature/integrated.py
+++ b/kornia/feature/integrated.py
@@ -2,9 +2,9 @@ import warnings
from typing import Dict, List, Optional, Tuple
import torch
-import torch.nn as nn
from kornia.color import rgb_to_grayscale
+from kornia.core import Device, Module, Tensor, concatenate
from kornia.geometry.subpix import ConvQuadInterp3d
from kornia.geometry.transform import ScalePyramid
from kornia.testing import KORNIA_CHECK_LAF
@@ -20,12 +20,8 @@ from .siftdesc import SIFTDescriptor
def get_laf_descriptors(
- img: torch.Tensor,
- lafs: torch.Tensor,
- patch_descriptor: nn.Module,
- patch_size: int = 32,
- grayscale_descriptor: bool = True,
-) -> torch.Tensor:
+ img: Tensor, lafs: Tensor, patch_descriptor: Module, patch_size: int = 32, grayscale_descriptor: bool = True
+) -> Tensor:
r"""Function to get local descriptors, corresponding to LAFs (keypoints).
Args:
@@ -43,21 +39,21 @@ def get_laf_descriptors(
patch_descriptor = patch_descriptor.to(img)
patch_descriptor.eval()
- timg: torch.Tensor = img
+ timg: Tensor = img
if lafs.shape[1] == 0:
warnings.warn(f"LAF contains no keypoints {lafs.shape}, returning empty tensor")
return torch.empty(lafs.shape[0], lafs.shape[1], 128)
if grayscale_descriptor and img.size(1) == 3:
timg = rgb_to_grayscale(img)
- patches: torch.Tensor = extract_patches_from_pyramid(timg, lafs, patch_size)
+ patches: 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):
+class LAFDescriptor(Module):
r"""Module to get local descriptors, corresponding to LAFs (keypoints).
Internally uses :func:`~kornia.feature.get_laf_descriptors`.
@@ -70,10 +66,7 @@ class LAFDescriptor(nn.Module):
"""
def __init__(
- self,
- patch_descriptor_module: Optional[nn.Module] = None,
- patch_size: int = 32,
- grayscale_descriptor: bool = True,
+ self, patch_descriptor_module: Optional[Module] = None, patch_size: int = 32, grayscale_descriptor: bool = True
) -> None:
super().__init__()
if patch_descriptor_module is None:
@@ -97,7 +90,7 @@ class LAFDescriptor(nn.Module):
+ ')'
)
- def forward(self, img: torch.Tensor, lafs: torch.Tensor) -> torch.Tensor:
+ def forward(self, img: Tensor, lafs: Tensor) -> Tensor:
r"""Three stage local feature detection.
First the location and scale of interest points are determined by
@@ -113,7 +106,7 @@ class LAFDescriptor(nn.Module):
return get_laf_descriptors(img, lafs, self.descriptor, self.patch_size, self.grayscale_descriptor)
-class LocalFeature(nn.Module):
+class LocalFeature(Module):
"""Module, which combines local feature detector and descriptor.
Args:
@@ -122,7 +115,7 @@ class LocalFeature(nn.Module):
scaling_coef: multiplier for change default detector scale (e.g. it is too small for KeyNet by default)
"""
- def __init__(self, detector: nn.Module, descriptor: LAFDescriptor, scaling_coef: float = 1.0) -> None:
+ def __init__(self, detector: Module, descriptor: LAFDescriptor, scaling_coef: float = 1.0) -> None:
super().__init__()
self.detector = detector
self.descriptor = descriptor
@@ -130,9 +123,7 @@ class LocalFeature(nn.Module):
raise ValueError(f"Scaling coef should be >= 0, got {scaling_coef}")
self.scaling_coef = scaling_coef
- def forward(
- self, img: torch.Tensor, mask: Optional[torch.Tensor] = None
- ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: # type: ignore
+ def forward(self, img: Tensor, mask: Optional[Tensor] = None) -> Tuple[Tensor, Tensor, Tensor]:
"""
Args:
img: image to extract features with shape :math:`(B,C,H,W)`.
@@ -161,7 +152,7 @@ class SIFTFeature(LocalFeature):
num_features: int = 8000,
upright: bool = False,
rootsift: bool = True,
- device: torch.device = torch.device('cpu'),
+ device: Device = torch.device('cpu'),
):
patch_size: int = 41
detector = ScaleSpaceDetector(
@@ -183,7 +174,7 @@ 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: torch.device = torch.device('cpu')):
+ def __init__(self, num_features: int = 8000, upright: bool = False, device: Device = torch.device('cpu')):
detector = ScaleSpaceDetector(
num_features,
resp_module=CornerGFTT(),
@@ -204,7 +195,7 @@ class KeyNetHardNet(LocalFeature):
self,
num_features: int = 8000,
upright: bool = False,
- device: torch.device = torch.device('cpu'),
+ device: Device = torch.device('cpu'),
scale_laf: float = 1.0,
):
ori_module = PassLAF() if upright else LAFOrienter(angle_detector=OriNet(True))
@@ -220,7 +211,7 @@ class KeyNetAffNetHardNet(LocalFeature):
self,
num_features: int = 8000,
upright: bool = False,
- device: torch.device = torch.device('cpu'),
+ device: Device = torch.device('cpu'),
scale_laf: float = 1.0,
):
ori_module = PassLAF() if upright else LAFOrienter(angle_detector=OriNet(True))
@@ -231,7 +222,7 @@ class KeyNetAffNetHardNet(LocalFeature):
super().__init__(detector, descriptor, scale_laf)
-class LocalFeatureMatcher(nn.Module):
+class LocalFeatureMatcher(Module):
r"""Module, which finds correspondences between two images based on local features.
Args:
@@ -239,7 +230,7 @@ class LocalFeatureMatcher(nn.Module):
matcher: Descriptor matcher, see :class:`~kornia.feature.DescriptorMatcher`.
Returns:
- Dict[str, torch.Tensor]: Dictionary with image correspondences and confidence scores.
+ Dict[str, Tensor]: Dictionary with image correspondences and confidence scores.
Example:
>>> img1 = torch.rand(1, 1, 320, 200)
@@ -251,18 +242,18 @@ class LocalFeatureMatcher(nn.Module):
>>> out = gftt_hardnet_matcher(input)
"""
- def __init__(self, local_feature: nn.Module, matcher: nn.Module) -> None:
+ def __init__(self, local_feature: Module, matcher: 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]:
+ def extract_features(self, image: Tensor, mask: Optional[Tensor] = None) -> Dict[str, 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:
+ def no_match_output(self, device: Device, dtype: torch.dtype) -> dict:
return {
'keypoints0': torch.empty(0, 2, device=device, dtype=dtype),
'keypoints1': torch.empty(0, 2, device=device, dtype=dtype),
@@ -272,7 +263,7 @@ class LocalFeatureMatcher(nn.Module):
'batch_indexes': torch.empty(0, device=device, dtype=torch.long),
}
- def forward(self, data: Dict[str, torch.Tensor]) -> Dict[str, torch.Tensor]:
+ def forward(self, data: Dict[str, Tensor]) -> Dict[str, Tensor]:
"""
Args:
data: dictionary containing the input data in the following format:
@@ -295,26 +286,26 @@ class LocalFeatureMatcher(nn.Module):
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'])
+ feats_dict0: Dict[str, 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'])
+ feats_dict1: Dict[str, 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)
+ keypoints0: Tensor = get_laf_center(lafs0)
+ keypoints1: 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] = []
+ out_keypoints0: List[Tensor] = []
+ out_keypoints1: List[Tensor] = []
+ out_confidence: List[Tensor] = []
+ out_batch_indexes: List[Tensor] = []
+ out_lafs0: List[Tensor] = []
+ out_lafs1: List[Tensor] = []
for batch_idx in range(num_image_pairs):
dists, idxs = self.matcher(descs0[batch_idx], descs1[batch_idx])
@@ -338,10 +329,10 @@ class LocalFeatureMatcher(nn.Module):
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),
+ 'keypoints0': concatenate(out_keypoints0, dim=0).view(-1, 2),
+ 'keypoints1': concatenate(out_keypoints1, dim=0).view(-1, 2),
+ 'lafs0': concatenate(out_lafs0, dim=0).view(1, -1, 2, 3),
+ 'lafs1': concatenate(out_lafs1, dim=0).view(1, -1, 2, 3),
+ 'confidence': concatenate(out_confidence, dim=0).view(-1),
+ 'batch_indexes': concatenate(out_batch_indexes, dim=0).view(-1),
}
diff --git a/kornia/feature/keynet.py b/kornia/feature/keynet.py
index e32aa079a..56cd2406e 100644
--- a/kornia/feature/keynet.py
+++ b/kornia/feature/keynet.py
@@ -4,8 +4,8 @@ from typing import Callable, Dict, List, Optional, Tuple
import torch
import torch.nn as nn
import torch.nn.functional as F
-from torch import Tensor
+from kornia.core import Module, Tensor, concatenate, tensor, where, zeros
from kornia.filters import SpatialGradient
from kornia.geometry.subpix import NonMaximaSuppression2d
from kornia.geometry.transform import pyrdown
@@ -32,7 +32,7 @@ urls: Dict[str, str] = {}
urls["keynet"] = "https://github.com/axelBarroso/Key.Net-Pytorch/raw/main/model/weights/keynet_pytorch.pth"
-class _FeatureExtractor(nn.Module):
+class _FeatureExtractor(Module):
"""Helper class for KeyNet.
It loads both, the handcrafted and learnable blocks
@@ -50,7 +50,7 @@ class _FeatureExtractor(nn.Module):
return x_lb
-class _HandcraftedBlock(nn.Module):
+class _HandcraftedBlock(Module):
"""Helper class for KeyNet, it defines the handcrafted filters within the Key.Net handcrafted block."""
def __init__(self):
@@ -68,7 +68,7 @@ class _HandcraftedBlock(nn.Module):
sobel_dy = self.spatial_gradient(dy)
dyy = sobel_dy[:, :, 1, :, :]
- hc_feats = torch.cat([dx, dy, dx**2.0, dy**2.0, dx * dy, dxy, dxy**2.0, dxx, dyy, dxx * dyy], dim=1)
+ hc_feats = concatenate([dx, dy, dx**2.0, dy**2.0, dx * dy, dxy, dxy**2.0, dxx, dyy, dxx * dyy], 1)
return hc_feats
@@ -110,7 +110,7 @@ def _KeyNetConvBlock(
)
-class KeyNet(nn.Module):
+class KeyNet(Module):
"""Key.Net model definition -- local feature detector (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.
@@ -160,11 +160,11 @@ class KeyNet(nn.Module):
feats_i = self.feature_extractor(x)
feats_i = F.interpolate(feats_i, size=(shape_im[2], shape_im[3]), mode='bilinear')
feats.append(feats_i)
- scores = self.last_conv(torch.cat(feats, dim=1))
+ scores = self.last_conv(concatenate(feats, 1))
return scores
-class KeyNetDetector(nn.Module):
+class KeyNetDetector(Module):
"""Multi-scale feature detector based on KeyNet.
This is based on the original code from paper
@@ -186,8 +186,8 @@ class KeyNetDetector(nn.Module):
pretrained: bool = False,
num_features: int = 2048,
keynet_conf: Dict = keynet_config['KeyNet_default_config'],
- ori_module: nn.Module = PassLAF(),
- aff_module: nn.Module = PassLAF(),
+ ori_module: Optional[Module] = None,
+ aff_module: Optional[Module] = None,
):
super().__init__()
self.model = KeyNet(pretrained, keynet_conf)
@@ -199,8 +199,16 @@ class KeyNetDetector(nn.Module):
self.nms_size: int = keynet_conf['nms_size']
self.nms = NonMaximaSuppression2d((self.nms_size, self.nms_size))
self.num_features = num_features
- self.ori = ori_module
- self.aff = aff_module
+
+ 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."""
@@ -219,20 +227,16 @@ class KeyNetDetector(nn.Module):
scores_sorted, indices = torch.sort(scores, descending=True)
- indices = indices[torch.where(scores_sorted > 0.0)]
+ 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) * torch.tensor(factor, device=device, dtype=dtype)
+ 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, torch.zeros(1, current_kp_num, 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( # type: ignore
- self, img: Tensor, mask: Optional[Tensor] = None # type: ignore
- ) -> Tuple[Tensor, Tensor]:
+ 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
@@ -283,16 +287,14 @@ class KeyNetDetector(nn.Module):
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 = torch.cat(all_responses, dim=1)
- lafs: Tensor = torch.cat(all_lafs, dim=1)
+ 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( # type: ignore
- self, img: Tensor, mask: Optional[Tensor] = None # type: ignore
- ) -> Tuple[Tensor, Tensor]:
+ 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.
diff --git a/kornia/feature/laf.py b/kornia/feature/laf.py
index 592110e78..89f6e5467 100644
--- a/kornia/feature/laf.py
+++ b/kornia/feature/laf.py
@@ -4,13 +4,14 @@ from typing import Optional, Union
import torch
import torch.nn.functional as F
+from kornia.core import Tensor, concatenate, stack, tensor, zeros
from kornia.geometry.conversions import angle_to_rotation_matrix, convert_points_from_homogeneous, rad2deg
from kornia.geometry.linalg import transform_points
from kornia.geometry.transform import pyrdown
from kornia.testing import KORNIA_CHECK_LAF, KORNIA_CHECK_SHAPE
-def get_laf_scale(LAF: torch.Tensor) -> torch.Tensor:
+def get_laf_scale(LAF: Tensor) -> Tensor:
"""Return a scale of the LAFs.
Args:
@@ -33,7 +34,7 @@ def get_laf_scale(LAF: torch.Tensor) -> torch.Tensor:
return out.abs().sqrt()
-def get_laf_center(LAF: torch.Tensor) -> torch.Tensor:
+def get_laf_center(LAF: Tensor) -> Tensor:
"""Return a center (keypoint) of the LAFs.
Args:
@@ -51,18 +52,18 @@ def get_laf_center(LAF: torch.Tensor) -> torch.Tensor:
>>> output = get_laf_center(input) # BxNx2
"""
KORNIA_CHECK_LAF(LAF)
- out: torch.Tensor = LAF[..., 2]
+ out = LAF[..., 2]
return out
-def get_laf_orientation(LAF: torch.Tensor) -> torch.Tensor:
+def get_laf_orientation(LAF: Tensor) -> Tensor:
"""Return orientation of the LAFs, in degrees.
Args:
- LAF: (torch.Tensor): tensor [BxNx2x3].
+ LAF: (Tensor): tensor [BxNx2x3].
Returns:
- torch.Tensor: tensor BxNx1 .
+ Tensor: tensor BxNx1 .
Shape:
- Input: :math: `(B, N, 2, 3)`
@@ -73,11 +74,11 @@ def get_laf_orientation(LAF: torch.Tensor) -> torch.Tensor:
>>> output = get_laf_orientation(input) # BxNx1
"""
KORNIA_CHECK_LAF(LAF)
- angle_rad: torch.Tensor = torch.atan2(LAF[..., 0, 1], LAF[..., 0, 0])
+ angle_rad = torch.atan2(LAF[..., 0, 1], LAF[..., 0, 0])
return rad2deg(angle_rad).unsqueeze(-1)
-def set_laf_orientation(LAF: torch.Tensor, angles_degrees: torch.Tensor) -> torch.Tensor:
+def set_laf_orientation(LAF: Tensor, angles_degrees: Tensor) -> Tensor:
"""Change the orientation of the LAFs.
Args:
@@ -93,16 +94,14 @@ def set_laf_orientation(LAF: torch.Tensor, angles_degrees: torch.Tensor) -> torc
"""
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(
+ rotmat = angle_to_rotation_matrix(angles_degrees).view(B * N, 2, 2)
+ laf_out = concatenate(
[torch.bmm(make_upright(LAF).view(B * N, 2, 3)[:, :2, :2], rotmat), LAF.view(B * N, 2, 3)[:, :2, 2:]], dim=2
).view(B, N, 2, 3)
return laf_out
-def laf_from_center_scale_ori(
- xy: torch.Tensor, scale: Optional[torch.Tensor] = None, ori: Optional[torch.Tensor] = None
-) -> torch.Tensor:
+def laf_from_center_scale_ori(xy: Tensor, scale: Optional[Tensor] = None, ori: Optional[Tensor] = None) -> Tensor:
"""Return orientation of the LAFs, in radians. Useful to create kornia LAFs from OpenCV keypoints.
Args:
@@ -120,15 +119,15 @@ def laf_from_center_scale_ori(
if scale is None:
scale = torch.ones(B, N, 1, 1, device=device, dtype=dtype)
if ori is None:
- ori = torch.zeros(B, N, 1, device=device, dtype=dtype)
+ ori = zeros(B, N, 1, device=device, dtype=dtype)
KORNIA_CHECK_SHAPE(scale, ["B", "N", "1", "1"])
KORNIA_CHECK_SHAPE(ori, ["B", "N", "1"])
- unscaled_laf: torch.Tensor = torch.cat([angle_to_rotation_matrix(ori.squeeze(-1)), xy.unsqueeze(-1)], dim=-1)
- laf: torch.Tensor = scale_laf(unscaled_laf, scale)
+ unscaled_laf = concatenate([angle_to_rotation_matrix(ori.squeeze(-1)), xy.unsqueeze(-1)], dim=-1)
+ laf = scale_laf(unscaled_laf, scale)
return laf
-def scale_laf(laf: torch.Tensor, scale_coef: Union[float, torch.Tensor]) -> torch.Tensor:
+def scale_laf(laf: Tensor, scale_coef: Union[float, Tensor]) -> Tensor:
"""Multiplies region part of LAF ([:, :, :2, :2]) by a scale_coefficient.
So the center, shape and orientation of the local feature stays the same, but the region area changes.
@@ -150,14 +149,14 @@ def scale_laf(laf: torch.Tensor, scale_coef: Union[float, torch.Tensor]) -> torc
>>> scale = 0.5
>>> output = scale_laf(input, scale) # BxNx2x3
"""
- 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)))
+ if (type(scale_coef) is not float) and (type(scale_coef) is not Tensor):
+ raise TypeError("scale_coef should be float or Tensor " "Got {}".format(type(scale_coef)))
KORNIA_CHECK_LAF(laf)
- centerless_laf: torch.Tensor = laf[:, :, :2, :2]
- return torch.cat([scale_coef * centerless_laf, laf[:, :, :, 2:]], dim=3)
+ centerless_laf = laf[:, :, :2, :2]
+ return concatenate([scale_coef * centerless_laf, laf[:, :, :, 2:]], dim=3)
-def make_upright(laf: torch.Tensor, eps: float = 1e-9) -> torch.Tensor:
+def make_upright(laf: Tensor, eps: float = 1e-9) -> Tensor:
"""Rectify the affine matrix, so that it becomes upright.
Args:
@@ -181,19 +180,19 @@ def make_upright(laf: torch.Tensor, eps: float = 1e-9) -> torch.Tensor:
# The function is equivalent to doing 2x2 SVD and resetting rotation
# matrix to an identity: U, S, V = svd(LAF); LAF_upright = U * S.
b2a2 = torch.sqrt(laf[..., 0:1, 1:2] ** 2 + laf[..., 0:1, 0:1] ** 2) + eps
- laf1_ell = torch.cat([(b2a2 / det).contiguous(), torch.zeros_like(det)], dim=3)
- laf2_ell = torch.cat( # type: ignore
+ laf1_ell = concatenate([(b2a2 / det).contiguous(), torch.zeros_like(det)], dim=3)
+ laf2_ell = concatenate(
[
((laf[..., 1:2, 1:2] * laf[..., 0:1, 1:2] + laf[..., 1:2, 0:1] * laf[..., 0:1, 0:1]) / (b2a2 * det)),
(det / b2a2).contiguous(),
],
dim=3,
)
- laf_unit_scale = torch.cat([torch.cat([laf1_ell, laf2_ell], dim=2), laf[..., :, 2:3]], dim=3)
+ laf_unit_scale = concatenate([concatenate([laf1_ell, laf2_ell], dim=2), laf[..., :, 2:3]], dim=3)
return scale_laf(laf_unit_scale, scale)
-def ellipse_to_laf(ells: torch.Tensor) -> torch.Tensor:
+def ellipse_to_laf(ells: Tensor) -> Tensor:
"""Convert ellipse regions to LAF format.
Ellipse (a, b, c) and upright covariance matrix [a11 a12; 0 a22] are connected
@@ -222,8 +221,8 @@ def ellipse_to_laf(ells: torch.Tensor) -> torch.Tensor:
if dim != 5:
raise TypeError("ellipse shape should be must be [BxNx5]. " "Got {}".format(ells.size()))
# Previous implementation was incorrectly using Cholesky decomp as matrix sqrt
- # ell_shape = torch.cat([torch.cat([ells[..., 2:3], ells[..., 3:4]], dim=2).unsqueeze(2),
- # torch.cat([ells[..., 3:4], ells[..., 4:5]], dim=2).unsqueeze(2)], dim=2).view(-1, 2, 2)
+ # ell_shape = concatenate([concatenate([ells[..., 2:3], ells[..., 3:4]], dim=2).unsqueeze(2),
+ # concatenate([ells[..., 3:4], ells[..., 4:5]], dim=2).unsqueeze(2)], dim=2).view(-1, 2, 2)
# out = torch.matrix_power(torch.cholesky(ell_shape, False), -1).view(B, N, 2, 2)
# We will calculate 2x2 matrix square root via special case formula
@@ -237,12 +236,12 @@ def ellipse_to_laf(ells: torch.Tensor) -> torch.Tensor:
a12 = torch.zeros_like(a11)
a22 = ells[..., 4:5].abs().sqrt()
a21 = ells[..., 3:4] / (a11 + a22).clamp(1e-9)
- A = torch.stack([a11, a12, a21, a22], dim=-1).view(B, N, 2, 2).inverse()
- out = torch.cat([A, ells[..., :2].view(B, N, 2, 1)], dim=3)
+ A = stack([a11, a12, a21, a22], dim=-1).view(B, N, 2, 2).inverse()
+ out = concatenate([A, ells[..., :2].view(B, N, 2, 1)], dim=3)
return out
-def laf_to_boundary_points(LAF: torch.Tensor, n_pts: int = 50) -> torch.Tensor:
+def laf_to_boundary_points(LAF: Tensor, n_pts: int = 50) -> Tensor:
"""Convert LAFs to boundary points of the regions + center.
Used for local features visualization, see visualize_laf function.
@@ -260,7 +259,7 @@ def laf_to_boundary_points(LAF: torch.Tensor, n_pts: int = 50) -> torch.Tensor:
"""
KORNIA_CHECK_LAF(LAF)
B, N, _, _ = LAF.size()
- pts = torch.cat(
+ pts = concatenate(
[
torch.sin(torch.linspace(0, 2 * math.pi, n_pts - 1)).unsqueeze(-1),
torch.cos(torch.linspace(0, 2 * math.pi, n_pts - 1)).unsqueeze(-1),
@@ -269,15 +268,15 @@ def laf_to_boundary_points(LAF: torch.Tensor, n_pts: int = 50) -> torch.Tensor:
dim=1,
)
# Add origin to draw also the orientation
- pts = torch.cat([torch.tensor([0.0, 0.0, 1.0]).view(1, 3), pts], dim=0).unsqueeze(0).expand(B * N, n_pts, 3)
+ pts = concatenate([tensor([0.0, 0.0, 1.0]).view(1, 3), pts], dim=0).unsqueeze(0).expand(B * N, n_pts, 3)
pts = pts.to(LAF.device).to(LAF.dtype)
- aux = torch.tensor([0.0, 0.0, 1.0]).view(1, 1, 3).expand(B * N, 1, 3)
- HLAF = torch.cat([LAF.view(-1, 2, 3), aux.to(LAF.device).to(LAF.dtype)], dim=1)
+ aux = tensor([0.0, 0.0, 1.0]).view(1, 1, 3).expand(B * N, 1, 3)
+ HLAF = concatenate([LAF.view(-1, 2, 3), aux.to(LAF.device).to(LAF.dtype)], dim=1)
pts_h = torch.bmm(HLAF, pts.permute(0, 2, 1)).permute(0, 2, 1)
return convert_points_from_homogeneous(pts_h.view(B, N, n_pts, 3))
-def get_laf_pts_to_draw(LAF: torch.Tensor, img_idx: int = 0):
+def get_laf_pts_to_draw(LAF: Tensor, img_idx: int = 0):
"""Return numpy array for drawing LAFs (local features).
Args:
@@ -305,7 +304,7 @@ def get_laf_pts_to_draw(LAF: torch.Tensor, img_idx: int = 0):
return (pts_np[..., 0], pts_np[..., 1])
-def denormalize_laf(LAF: torch.Tensor, images: torch.Tensor) -> torch.Tensor:
+def denormalize_laf(LAF: Tensor, images: Tensor) -> Tensor:
"""De-normalize LAFs from scale to image scale.
B,N,H,W = images.size()
@@ -338,7 +337,7 @@ def denormalize_laf(LAF: torch.Tensor, images: torch.Tensor) -> torch.Tensor:
return coef.expand_as(LAF) * LAF
-def normalize_laf(LAF: torch.Tensor, images: torch.Tensor) -> torch.Tensor:
+def normalize_laf(LAF: Tensor, images: Tensor) -> Tensor:
"""Normalize LAFs to [0,1] scale from pixel scale. See below:
B,N,H,W = images.size()
MIN_SIZE = min(H,W)
@@ -349,11 +348,11 @@ def normalize_laf(LAF: torch.Tensor, images: torch.Tensor) -> torch.Tensor:
[a21/MIN_SIZE a22/MIN_SIZE y/H]
Args:
- LAF: (torch.Tensor).
- images: (torch.Tensor) images, LAFs are detected in
+ LAF: (Tensor).
+ images: (Tensor) images, LAFs are detected in
Returns:
- LAF: (torch.Tensor).
+ LAF: (Tensor).
Shape:
- Input: :math:`(B, N, 2, 3)`
@@ -361,8 +360,8 @@ def normalize_laf(LAF: torch.Tensor, images: torch.Tensor) -> torch.Tensor:
"""
KORNIA_CHECK_LAF(LAF)
_, _, h, w = images.size()
- wf: float = float(w)
- hf: float = float(h)
+ wf = float(w)
+ hf = float(h)
min_size = min(hf, wf)
coef = torch.ones(1, 1, 2, 3).to(LAF.dtype).to(LAF.device) / min_size
coef[0, 0, 0, 2] = 1.0 / wf
@@ -370,7 +369,7 @@ def normalize_laf(LAF: torch.Tensor, images: torch.Tensor) -> torch.Tensor:
return coef.expand_as(LAF) * LAF
-def generate_patch_grid_from_normalized_LAF(img: torch.Tensor, LAF: torch.Tensor, PS: int = 32) -> torch.Tensor:
+def generate_patch_grid_from_normalized_LAF(img: Tensor, LAF: Tensor, PS: int = 32) -> Tensor:
"""Helper function for affine grid generation.
Args:
@@ -389,15 +388,15 @@ def generate_patch_grid_from_normalized_LAF(img: torch.Tensor, LAF: torch.Tensor
# and extraction at arbitrary other
LAF_renorm = denormalize_laf(LAF, img)
- grid = F.affine_grid(LAF_renorm.view(B * N, 2, 3), [B * N, ch, PS, PS], align_corners=False) # type: ignore
+ grid = F.affine_grid(LAF_renorm.view(B * N, 2, 3), [B * N, ch, PS, PS], align_corners=False)
grid[..., :, 0] = 2.0 * grid[..., :, 0].clone() / float(w) - 1.0
grid[..., :, 1] = 2.0 * grid[..., :, 1].clone() / float(h) - 1.0
return grid
def extract_patches_simple(
- img: torch.Tensor, laf: torch.Tensor, PS: int = 32, normalize_lafs_before_extraction: bool = True
-) -> torch.Tensor:
+ img: Tensor, laf: Tensor, PS: int = 32, normalize_lafs_before_extraction: bool = True
+) -> Tensor:
"""Extract patches defined by LAFs from image tensor.
No smoothing applied, huge aliasing (better use extract_patches_from_pyramid).
@@ -413,7 +412,7 @@ def extract_patches_simple(
"""
KORNIA_CHECK_LAF(laf)
if normalize_lafs_before_extraction:
- nlaf: torch.Tensor = normalize_laf(laf, img)
+ nlaf = normalize_laf(laf, img)
else:
nlaf = laf
_, ch, h, w = img.size()
@@ -424,18 +423,15 @@ def extract_patches_simple(
grid = generate_patch_grid_from_normalized_LAF(img[i : i + 1], nlaf[i : i + 1], PS).to(img.device)
out.append(
F.grid_sample(
- img[i : i + 1].expand(grid.size(0), ch, h, w),
- grid, # type: ignore
- padding_mode="border",
- align_corners=False,
+ img[i : i + 1].expand(grid.size(0), ch, h, w), grid, padding_mode="border", align_corners=False
)
)
- return torch.cat(out, dim=0).view(B, N, ch, PS, PS)
+ return concatenate(out, dim=0).view(B, N, ch, PS, PS)
def extract_patches_from_pyramid(
- img: torch.Tensor, laf: torch.Tensor, PS: int = 32, normalize_lafs_before_extraction: bool = True
-) -> torch.Tensor:
+ img: Tensor, laf: Tensor, PS: int = 32, normalize_lafs_before_extraction: bool = True
+) -> Tensor:
"""Extract patches defined by LAFs from image tensor.
Patches are extracted from appropriate pyramid level.
@@ -451,7 +447,7 @@ def extract_patches_from_pyramid(
"""
KORNIA_CHECK_LAF(laf)
if normalize_lafs_before_extraction:
- nlaf: torch.Tensor = normalize_laf(laf, img)
+ nlaf = normalize_laf(laf, img)
else:
nlaf = laf
B, N, _, _ = laf.size()
@@ -460,7 +456,7 @@ def extract_patches_from_pyramid(
pyr_idx = scale.log2().relu().long()
cur_img = img
cur_pyr_level = 0
- out = torch.zeros(B, N, ch, PS, PS).to(nlaf.dtype).to(nlaf.device)
+ out = zeros(B, N, ch, PS, PS).to(nlaf.dtype).to(nlaf.device)
while min(cur_img.size(2), cur_img.size(3)) >= PS:
_, ch, h, w = cur_img.size()
# for loop temporarily, to be refactored
@@ -471,10 +467,7 @@ def extract_patches_from_pyramid(
scale_mask = (scale_mask > 0).view(-1)
grid = generate_patch_grid_from_normalized_LAF(cur_img[i : i + 1], nlaf[i : i + 1, scale_mask, :, :], PS)
patches = F.grid_sample(
- cur_img[i : i + 1].expand(grid.size(0), ch, h, w),
- grid, # type: ignore
- padding_mode="border",
- align_corners=False,
+ cur_img[i : i + 1].expand(grid.size(0), ch, h, w), grid, padding_mode="border", align_corners=False
)
out[i].masked_scatter_(scale_mask.view(-1, 1, 1, 1), patches)
cur_img = pyrdown(cur_img)
@@ -482,7 +475,7 @@ def extract_patches_from_pyramid(
return out
-def laf_is_inside_image(laf: torch.Tensor, images: torch.Tensor, border: int = 0) -> torch.Tensor:
+def laf_is_inside_image(laf: Tensor, images: Tensor, border: int = 0) -> Tensor:
"""Check if the LAF is touching or partly outside the image boundary.
Returns the mask of LAFs, which are fully inside the image, i.e. valid.
@@ -497,15 +490,15 @@ def laf_is_inside_image(laf: torch.Tensor, images: torch.Tensor, border: int = 0
"""
KORNIA_CHECK_LAF(laf)
_, _, h, w = images.size()
- pts: torch.Tensor = laf_to_boundary_points(laf, 12)
- good_lafs_mask: torch.Tensor = (
+ pts = laf_to_boundary_points(laf, 12)
+ good_lafs_mask = (
(pts[..., 0] >= border) * (pts[..., 0] <= w - border) * (pts[..., 1] >= border) * (pts[..., 1] <= h - border)
)
good_lafs_mask = good_lafs_mask.min(dim=2)[0]
return good_lafs_mask
-def laf_to_three_points(laf: torch.Tensor):
+def laf_to_three_points(laf: Tensor):
"""Convert local affine frame(LAF) to alternative representation: coordinates of LAF center, LAF-x unit vector,
LAF-y unit vector.
@@ -516,11 +509,11 @@ def laf_to_three_points(laf: torch.Tensor):
threepts :math:`(B, N, 2, 3)`.
"""
KORNIA_CHECK_LAF(laf)
- three_pts: torch.Tensor = torch.stack([laf[..., 2] + laf[..., 0], laf[..., 2] + laf[..., 1], laf[..., 2]], dim=-1)
+ three_pts = stack([laf[..., 2] + laf[..., 0], laf[..., 2] + laf[..., 1], laf[..., 2]], dim=-1)
return three_pts
-def laf_from_three_points(threepts: torch.Tensor):
+def laf_from_three_points(threepts: Tensor):
"""Convert three points to local affine frame.
Order is (0,0), (0, 1), (1, 0).
@@ -531,13 +524,11 @@ def laf_from_three_points(threepts: torch.Tensor):
Returns:
laf :math:`(B, N, 2, 3)`.
"""
- laf: torch.Tensor = torch.stack(
- [threepts[..., 0] - threepts[..., 2], threepts[..., 1] - threepts[..., 2], threepts[..., 2]], dim=-1
- )
+ laf = stack([threepts[..., 0] - threepts[..., 2], threepts[..., 1] - threepts[..., 2], threepts[..., 2]], dim=-1)
return laf
-def perspective_transform_lafs(trans_01: torch.Tensor, lafs_1: torch.Tensor) -> torch.Tensor:
+def perspective_transform_lafs(trans_01: Tensor, lafs_1: Tensor) -> Tensor:
r"""Function that applies perspective transformations to a set of local affine frames (LAFs).
Args:
@@ -582,7 +573,7 @@ def perspective_transform_lafs(trans_01: torch.Tensor, lafs_1: torch.Tensor) ->
"""
KORNIA_CHECK_LAF(lafs_1)
if not torch.is_tensor(trans_01):
- raise TypeError("Input type is not a torch.Tensor")
+ raise TypeError("Input type is not a Tensor")
if not trans_01.device == lafs_1.device:
raise TypeError("Tensor must be in the same device")
diff --git a/kornia/feature/responses.py b/kornia/feature/responses.py
index 3d961910e..2078ea2e4 100644
--- a/kornia/feature/responses.py
+++ b/kornia/feature/responses.py
@@ -1,18 +1,15 @@
from typing import Optional, Union
import torch
-import torch.nn as nn
+from kornia.core import Module, Tensor, tensor
from kornia.filters import gaussian_blur2d, spatial_gradient
from kornia.testing import KORNIA_CHECK_SHAPE
def harris_response(
- input: torch.Tensor,
- k: Union[torch.Tensor, float] = 0.04,
- grads_mode: str = 'sobel',
- sigmas: Optional[torch.Tensor] = None,
-) -> torch.Tensor:
+ input: Tensor, k: Union[Tensor, float] = 0.04, grads_mode: str = 'sobel', sigmas: Optional[Tensor] = None
+) -> Tensor:
r"""Compute the Harris cornerness function.
Function does not do any normalization or nms. The response map is computed according the following formulation:
@@ -67,26 +64,26 @@ def harris_response(
KORNIA_CHECK_SHAPE(input, ["B", "C", "H", "W"])
if sigmas is not None:
- if not isinstance(sigmas, torch.Tensor):
- raise TypeError(f"sigmas type is not a torch.Tensor. Got {type(sigmas)}")
+ if not isinstance(sigmas, Tensor):
+ raise TypeError(f"sigmas type is not a Tensor. Got {type(sigmas)}")
if (not len(sigmas.shape) == 1) or (sigmas.size(0) != input.size(0)):
raise ValueError(f"Invalid sigmas shape, we expect B == input.size(0). Got: {sigmas.shape}")
- gradients: torch.Tensor = spatial_gradient(input, grads_mode)
- dx: torch.Tensor = gradients[:, :, 0]
- dy: torch.Tensor = gradients[:, :, 1]
+ gradients: Tensor = spatial_gradient(input, grads_mode)
+ dx: Tensor = gradients[:, :, 0]
+ dy: Tensor = gradients[:, :, 1]
# compute the structure tensor M elements
- dx2: torch.Tensor = gaussian_blur2d(dx**2, (7, 7), (1.0, 1.0))
- dy2: torch.Tensor = gaussian_blur2d(dy**2, (7, 7), (1.0, 1.0))
- dxy: torch.Tensor = gaussian_blur2d(dx * dy, (7, 7), (1.0, 1.0))
+ dx2: Tensor = gaussian_blur2d(dx**2, (7, 7), (1.0, 1.0))
+ dy2: Tensor = gaussian_blur2d(dy**2, (7, 7), (1.0, 1.0))
+ dxy: Tensor = gaussian_blur2d(dx * dy, (7, 7), (1.0, 1.0))
- det_m: torch.Tensor = dx2 * dy2 - dxy * dxy
- trace_m: torch.Tensor = dx2 + dy2
+ det_m: Tensor = dx2 * dy2 - dxy * dxy
+ trace_m: Tensor = dx2 + dy2
# compute the response map
- scores: torch.Tensor = det_m - k * (trace_m**2)
+ scores: Tensor = det_m - k * (trace_m**2)
if sigmas is not None:
scores = scores * sigmas.pow(4).view(-1, 1, 1, 1)
@@ -94,9 +91,7 @@ def harris_response(
return scores
-def gftt_response(
- input: torch.Tensor, grads_mode: str = 'sobel', sigmas: Optional[torch.Tensor] = None
-) -> torch.Tensor:
+def gftt_response(input: Tensor, grads_mode: str = 'sobel', sigmas: Optional[Tensor] = None) -> Tensor:
r"""Compute the Shi-Tomasi cornerness function.
Function does not do any normalization or nms. The response map is computed according the following formulation:
@@ -146,21 +141,21 @@ def gftt_response(
# TODO: Recompute doctest
KORNIA_CHECK_SHAPE(input, ["B", "C", "H", "W"])
- gradients: torch.Tensor = spatial_gradient(input, grads_mode)
- dx: torch.Tensor = gradients[:, :, 0]
- dy: torch.Tensor = gradients[:, :, 1]
+ gradients: Tensor = spatial_gradient(input, grads_mode)
+ dx: Tensor = gradients[:, :, 0]
+ dy: Tensor = gradients[:, :, 1]
- dx2: torch.Tensor = gaussian_blur2d(dx**2, (7, 7), (1.0, 1.0))
- dy2: torch.Tensor = gaussian_blur2d(dy**2, (7, 7), (1.0, 1.0))
- dxy: torch.Tensor = gaussian_blur2d(dx * dy, (7, 7), (1.0, 1.0))
+ dx2: Tensor = gaussian_blur2d(dx**2, (7, 7), (1.0, 1.0))
+ dy2: Tensor = gaussian_blur2d(dy**2, (7, 7), (1.0, 1.0))
+ dxy: Tensor = gaussian_blur2d(dx * dy, (7, 7), (1.0, 1.0))
- det_m: torch.Tensor = dx2 * dy2 - dxy * dxy
- trace_m: torch.Tensor = dx2 + dy2
+ det_m: Tensor = dx2 * dy2 - dxy * dxy
+ trace_m: Tensor = dx2 + dy2
- e1: torch.Tensor = 0.5 * (trace_m + torch.sqrt((trace_m**2 - 4 * det_m).abs()))
- e2: torch.Tensor = 0.5 * (trace_m - torch.sqrt((trace_m**2 - 4 * det_m).abs()))
+ e1: Tensor = 0.5 * (trace_m + torch.sqrt((trace_m**2 - 4 * det_m).abs()))
+ e2: Tensor = 0.5 * (trace_m - torch.sqrt((trace_m**2 - 4 * det_m).abs()))
- scores: torch.Tensor = torch.min(e1, e2)
+ scores: Tensor = torch.min(e1, e2)
if sigmas is not None:
scores = scores * sigmas.pow(4).view(-1, 1, 1, 1)
@@ -168,9 +163,7 @@ def gftt_response(
return scores
-def hessian_response(
- input: torch.Tensor, grads_mode: str = 'sobel', sigmas: Optional[torch.Tensor] = None
-) -> torch.Tensor:
+def hessian_response(input: Tensor, grads_mode: str = 'sobel', sigmas: Optional[Tensor] = None) -> Tensor:
r"""Compute the absolute of determinant of the Hessian matrix.
Function does not do any normalization or nms. The response map is computed according the following formulation:
@@ -225,18 +218,18 @@ def hessian_response(
KORNIA_CHECK_SHAPE(input, ["B", "C", "H", "W"])
if sigmas is not None:
- if not isinstance(sigmas, torch.Tensor):
- raise TypeError(f"sigmas type is not a torch.Tensor. Got {type(sigmas)}")
+ if not isinstance(sigmas, Tensor):
+ raise TypeError(f"sigmas type is not a Tensor. Got {type(sigmas)}")
if (not len(sigmas.shape) == 1) or (sigmas.size(0) != input.size(0)):
raise ValueError(f"Invalid sigmas shape, we expect B == input.size(0). Got: {sigmas.shape}")
- gradients: torch.Tensor = spatial_gradient(input, grads_mode, 2)
- dxx: torch.Tensor = gradients[:, :, 0]
- dxy: torch.Tensor = gradients[:, :, 1]
- dyy: torch.Tensor = gradients[:, :, 2]
+ gradients: Tensor = spatial_gradient(input, grads_mode, 2)
+ dxx: Tensor = gradients[:, :, 0]
+ dxy: Tensor = gradients[:, :, 1]
+ dyy: Tensor = gradients[:, :, 2]
- scores: torch.Tensor = dxx * dyy - dxy**2
+ scores: Tensor = dxx * dyy - dxy**2
if sigmas is not None:
scores = scores * sigmas.pow(4).view(-1, 1, 1, 1)
@@ -244,7 +237,7 @@ def hessian_response(
return scores
-def dog_response(input: torch.Tensor) -> torch.Tensor:
+def dog_response(input: Tensor) -> Tensor:
r"""Compute the Difference-of-Gaussian response.
Args:
@@ -258,7 +251,7 @@ def dog_response(input: torch.Tensor) -> torch.Tensor:
return input[:, :, 1:] - input[:, :, :-1]
-class BlobDoG(nn.Module):
+class BlobDoG(Module):
r"""Module that calculates Difference-of-Gaussians blobs.
See :func:`~kornia.feature.dog_response` for details.
@@ -271,33 +264,34 @@ class BlobDoG(nn.Module):
def __repr__(self) -> str:
return self.__class__.__name__
- def forward(self, input: torch.Tensor, sigmas: Optional[torch.Tensor] = None) -> torch.Tensor: # type: ignore
- return dog_response(input) # type: ignore
+ def forward(self, input: Tensor, sigmas: Optional[Tensor] = None) -> Tensor:
+ return dog_response(input)
-class CornerHarris(nn.Module):
+class CornerHarris(Module):
r"""Module that calculates Harris corners.
See :func:`~kornia.feature.harris_response` for details.
"""
+ k: Tensor
- def __init__(self, k: Union[float, torch.Tensor], grads_mode='sobel') -> None:
+ def __init__(self, k: Union[float, Tensor], grads_mode='sobel') -> None:
super().__init__()
- if type(k) is float:
- self.register_buffer('k', torch.tensor(k))
+ if isinstance(k, float):
+ self.register_buffer('k', tensor(k))
else:
- self.register_buffer('k', k) # type: ignore
+ self.register_buffer('k', k)
self.grads_mode: str = grads_mode
return
def __repr__(self) -> str:
return self.__class__.__name__ + '(k=' + str(self.k) + ', ' + 'grads_mode=' + self.grads_mode + ')'
- def forward(self, input: torch.Tensor, sigmas: Optional[torch.Tensor] = None) -> torch.Tensor: # type: ignore
- return harris_response(input, self.k, self.grads_mode, sigmas) # type: ignore
+ def forward(self, input: Tensor, sigmas: Optional[Tensor] = None) -> Tensor:
+ return harris_response(input, self.k, self.grads_mode, sigmas)
-class CornerGFTT(nn.Module):
+class CornerGFTT(Module):
r"""Module that calculates Shi-Tomasi corners.
See :func:`~kornia.feature.gfft_response` for details.
@@ -311,11 +305,11 @@ class CornerGFTT(nn.Module):
def __repr__(self) -> str:
return self.__class__.__name__ + 'grads_mode=' + self.grads_mode + ')'
- def forward(self, input: torch.Tensor, sigmas: Optional[torch.Tensor] = None) -> torch.Tensor: # type: ignore
+ def forward(self, input: Tensor, sigmas: Optional[Tensor] = None) -> Tensor:
return gftt_response(input, self.grads_mode, sigmas)
-class BlobHessian(nn.Module):
+class BlobHessian(Module):
r"""Module that calculates Hessian blobs.
See :func:`~kornia.feature.hessian_response` for details.
@@ -329,5 +323,5 @@ class BlobHessian(nn.Module):
def __repr__(self) -> str:
return self.__class__.__name__ + 'grads_mode=' + self.grads_mode + ')'
- def forward(self, input: torch.Tensor, sigmas: Optional[torch.Tensor] = None) -> torch.Tensor: # type: ignore
+ def forward(self, input: Tensor, sigmas: Optional[Tensor] = None) -> Tensor:
return hessian_response(input, self.grads_mode, sigmas)