Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

enable `disallow_any_generics` on mypy (#2092)

João Gustavo A. Amorim15bb4e62596a
diff --git a/kornia/augmentation/base.py b/kornia/augmentation/base.py
index 9eea719cb..625e66fdf 100644
--- a/kornia/augmentation/base.py
+++ b/kornia/augmentation/base.py
@@ -81,7 +81,7 @@ class _BasicAugmentationBase(Module):
"""Standardize input tensors."""
raise NotImplementedError
- def transform_output_tensor(self, output: Tensor, output_shape: Tuple) -> Tensor:
+ def transform_output_tensor(self, output: Tensor, output_shape: Tuple[int, ...]) -> Tensor:
"""Standardize output tensors."""
return _transform_output_shape(output, output_shape) if self.keepdim else output
diff --git a/kornia/augmentation/container/base.py b/kornia/augmentation/container/base.py
index fc445df46..9da40480a 100644
--- a/kornia/augmentation/container/base.py
+++ b/kornia/augmentation/container/base.py
@@ -14,7 +14,7 @@ __all__ = ["SequentialBase", "ParamItem"]
class ParamItem(NamedTuple):
name: str
# TODO: add type List['ParamItem'] when mypy > 0.991 be available (see python/mypy#14200)
- data: Optional[Union[Dict[str, Tensor], list]]
+ data: Optional[Union[Dict[str, Tensor], List]] # type: ignore [type-arg]
class SequentialBase(nn.Sequential):
@@ -149,7 +149,7 @@ class SequentialBase(nn.Sequential):
for name, _ in named_modules:
yield ParamItem(name, None)
- def contains_label_operations(self, params: List) -> bool:
+ def contains_label_operations(self, params: List[ParamItem]) -> bool:
raise NotImplementedError
def autofill_dim(self, input: Tensor, dim_range: Tuple[int, int] = (2, 4)) -> Tuple[torch.Size, torch.Size]:
diff --git a/kornia/augmentation/container/image.py b/kornia/augmentation/container/image.py
index a33ed22ba..cd1c6dbd7 100644
--- a/kornia/augmentation/container/image.py
+++ b/kornia/augmentation/container/image.py
@@ -211,7 +211,7 @@ class ImageSequential(SequentialBase):
named_modules: Iterator[Tuple[str, Module]] = self.get_forward_sequence()
params: List[ParamItem] = []
- mod_param: Union[dict, list]
+ mod_param: Union[Dict[str, Tensor], List[ParamItem]]
for name, module in named_modules:
if isinstance(module, RandomCrop):
mod_param = module.forward_parameters_precrop(batch_shape)
diff --git a/kornia/augmentation/container/utils.py b/kornia/augmentation/container/utils.py
index f20060cd2..d8b8d189f 100644
--- a/kornia/augmentation/container/utils.py
+++ b/kornia/augmentation/container/utils.py
@@ -18,7 +18,7 @@ from kornia.testing import KORNIA_UNWRAP
from kornia.utils.helpers import _torch_inverse_cast
-def _get_geometric_only_param(module: "kornia.augmentation.ImageSequential", param: List[ParamItem]) -> List[ParamItem]:
+def _get_geometric_only_param(module: 'kornia.augmentation.ImageSequential', param: List[ParamItem]) -> List[ParamItem]:
named_modules: Iterator[Tuple[str, Module]] = module.get_forward_sequence(param)
res: List[ParamItem] = []
@@ -66,7 +66,7 @@ class ApplyInverseInterface(metaclass=ABCMeta):
class ApplyInverseImpl(ApplyInverseInterface):
"""Standard matrix apply and inverse methods."""
- apply_func: Callable
+ apply_func: Callable[[Tensor, Tensor], Tensor]
@classmethod
def apply_trans(
@@ -207,23 +207,36 @@ class InputApplyInverse(ApplyInverseImpl):
param: the corresponding parameters to the module.
"""
if isinstance(module, GeometricAugmentationBase2D):
- input = module.inverse(
- input, params=None if param is None else cast(Dict, param.data), extra_args=extra_args
- )
+ if param is None:
+ _params_geo = None
+ elif isinstance(param, ParamItem) and isinstance(param.data, dict):
+ _params_geo = param.data
+ else:
+ raise TypeError(f'Expected param (ParamItem.data) be a dictionary. Gotcha {type(param.data)}')
+
+ input = module.inverse(input, params=_params_geo, extra_args=extra_args)
+
elif isinstance(module, kornia.augmentation.ImageSequential):
temp = module.apply_inverse_func
module.apply_inverse_func = InputApplyInverse
+ if param is None:
+ _params = None
+ elif isinstance(param, ParamItem) and isinstance(param.data, list):
+ _params = param.data
+ else:
+ raise TypeError(f'Expected param (ParamItem.data) be a list. Gotcha {type(param.data)}')
+
if isinstance(module, kornia.augmentation.AugmentationSequential):
- input = cast(
- Tensor,
- module.inverse(
- input, params=None if param is None else cast(List, param.data), data_keys=[cls.data_key]
- ),
- )
+ _ret = module.inverse(input, params=_params, data_keys=[cls.data_key])
+ if isinstance(_ret, Tensor):
+ input = _ret
+ else:
+ raise TypeError(
+ f'The return of the method inverse from {module} should be a Tensor. Gotcha {type(_ret)}'
+ )
else:
- input = module.inverse(
- input, params=None if param is None else cast(List, param.data), extra_args=extra_args
- )
+ input = module.inverse(input, params=_params, extra_args=extra_args)
+
module.apply_inverse_func = temp
return input
@@ -234,7 +247,7 @@ class MaskApplyInverse(ApplyInverseImpl):
data_key = DataKey.MASK
@classmethod
- def make_input_only_sequential(cls, module: "kornia.augmentation.ImageSequential") -> Callable:
+ def make_input_only_sequential(cls, module: 'kornia.augmentation.ImageSequential') -> Callable[..., torch.Tensor]:
"""Disable all other additional inputs (e.g. ) for ImageSequential."""
def f(*args, **kwargs):
@@ -264,23 +277,29 @@ class MaskApplyInverse(ApplyInverseImpl):
to apply transformations.
param: the corresponding parameters to the module.
"""
- if param is not None:
- _param = param.data
- else:
- _param = None
-
if isinstance(module, (GeometricAugmentationBase2D, RandomErasing)):
- _param = cast(Dict[str, Tensor], _param).copy()
- # TODO: Parametrize value to pad with across the board for different keys
- if 'values' in _param:
- _param['values'] = torch.zeros_like(_param['values']) # Always pad with zeros
+ if isinstance(param, ParamItem) and isinstance(param.data, dict):
+ _param = param.data.copy()
+ # TODO: Parametrize value to pad with across the board for different keys
+ if 'values' in _param:
+ _param['values'] = torch.zeros_like(_param['values']) # Always pad with zeros
+ elif param is None:
+ _param = None
+ else:
+ raise TypeError(f'Expected param be None or ParamItem.data as a dict. Gotcha {type(_param)}')
input = module(input, params=_param, **extra_args)
+
elif isinstance(module, kornia.augmentation.ImageSequential) and not module.is_intensity_only():
- _param = cast(List[ParamItem], _param)
+ if param is None:
+ geo_param = None
+ elif isinstance(param, ParamItem) and isinstance(param.data, list):
+ geo_param = _get_geometric_only_param(module, param.data)
+ else:
+ raise TypeError(f'Expected param be None or ParamItem.data as a list. Gotcha {type(geo_param)}')
+
temp = module.apply_inverse_func
module.apply_inverse_func = MaskApplyInverse
- geo_param: List[ParamItem] = _get_geometric_only_param(module, _param)
if isinstance(module, kornia.augmentation.AugmentationSequential):
input = cls.make_input_only_sequential(module)(
input, label=None, params=geo_param, data_keys=[cls.data_key]
@@ -308,21 +327,37 @@ class MaskApplyInverse(ApplyInverseImpl):
"""
if isinstance(module, GeometricAugmentationBase2D):
- input = module.inverse(input, params=None if param is None else cast(Dict, param.data), **extra_args)
+ if param is None:
+ _params_geo = None
+ elif isinstance(param, ParamItem) and isinstance(param.data, dict):
+ _params_geo = param.data
+ else:
+ raise TypeError(f'Expected param (ParamItem.data) be a dict. Gotcha {type(param.data)}')
+
+ input = module.inverse(input, params=_params_geo, **extra_args)
+
elif isinstance(module, kornia.augmentation.ImageSequential):
temp = module.apply_inverse_func
module.apply_inverse_func = MaskApplyInverse
+
+ if param is None:
+ _params = None
+ elif isinstance(param, ParamItem) and isinstance(param.data, list):
+ _params = param.data
+ else:
+ raise TypeError(f'Expected param (ParamItem.data) be a list. Gotcha {type(param.data)}')
+
if isinstance(module, kornia.augmentation.AugmentationSequential):
- input = cast(
- Tensor,
- module.inverse(
- input, params=None if param is None else cast(List, param.data), data_keys=[cls.data_key]
- ),
- )
+ _ret = module.inverse(input, params=_params, data_keys=[cls.data_key])
+ if isinstance(_ret, Tensor):
+ input = _ret
+ else:
+ raise TypeError(
+ f'The return of the method inverse from {module} should be a Tensor. Gotcha {type(_ret)}'
+ )
else:
- input = module.inverse(
- input, params=None if param is None else cast(List, param.data), extra_args=extra_args
- )
+ input = module.inverse(input, params=_params, extra_args=extra_args)
+
module.apply_inverse_func = temp
return input
diff --git a/kornia/augmentation/utils/helpers.py b/kornia/augmentation/utils/helpers.py
index 032a61657..54f358e45 100644
--- a/kornia/augmentation/utils/helpers.py
+++ b/kornia/augmentation/utils/helpers.py
@@ -8,7 +8,7 @@ from kornia.core import Tensor, as_tensor
from kornia.utils import _extract_device_dtype
-def _validate_input(f: Callable) -> Callable:
+def _validate_input(f: Callable[..., Any]) -> Callable[..., Any]:
r"""Validate the 2D input of the wrapped function.
Args:
@@ -31,7 +31,7 @@ def _validate_input(f: Callable) -> Callable:
return wrapper
-def _validate_input3d(f: Callable) -> Callable:
+def _validate_input3d(f: Callable[..., Any]) -> Callable[..., Any]:
r"""Validate the 3D input of the wrapped function.
Args:
@@ -128,7 +128,7 @@ def _transform_input3d(input: Tensor) -> Tensor:
return input
-def _validate_input_dtype(input: Tensor, accepted_dtypes: List) -> None:
+def _validate_input_dtype(input: Tensor, accepted_dtypes: List[torch.dtype]) -> None:
r"""Check if the dtype of the input tensor is in the range of accepted_dtypes
Args:
input: Tensor
@@ -138,7 +138,7 @@ def _validate_input_dtype(input: Tensor, accepted_dtypes: List) -> None:
raise TypeError(f"Expected input of {accepted_dtypes}. Got {input.dtype}")
-def _transform_output_shape(output: Tensor, shape: Tuple) -> Tensor:
+def _transform_output_shape(output: Tensor, shape: Tuple[int, ...]) -> Tensor:
r"""Collapse the broadcasted batch dimensions an input tensor to be the specified shape.
Args:
input: Tensor
@@ -157,7 +157,7 @@ def _transform_output_shape(output: Tensor, shape: Tuple) -> Tensor:
return out_tensor
-def _validate_shape(shape: Union[Tuple, torch.Size], required_shapes: Tuple[str, ...] = ("BCHW",)) -> None:
+def _validate_shape(shape: Union[Tuple[int, ...], torch.Size], required_shapes: Tuple[str, ...] = ("BCHW",)) -> None:
r"""Check if the dtype of the input tensor is in the range of accepted_dtypes
Args:
shape: tensor shape
@@ -189,7 +189,7 @@ def _validate_input_shape(input: Tensor, channel_index: int, number: int) -> boo
def _adapted_rsampling(
- shape: Union[Tuple, torch.Size], dist: torch.distributions.Distribution, same_on_batch=False
+ shape: Union[Tuple[int, ...], torch.Size], dist: torch.distributions.Distribution, same_on_batch=False
) -> Tensor:
r"""The uniform reparameterized sampling function that accepts 'same_on_batch'.
@@ -205,7 +205,7 @@ def _adapted_rsampling(
def _adapted_sampling(
- shape: Union[Tuple, torch.Size], dist: torch.distributions.Distribution, same_on_batch=False
+ shape: Union[Tuple[int, ...], torch.Size], dist: torch.distributions.Distribution, same_on_batch=False
) -> Tensor:
r"""The uniform sampling function that accepts 'same_on_batch'.
@@ -221,7 +221,7 @@ def _adapted_sampling(
def _adapted_uniform(
- shape: Union[Tuple, torch.Size],
+ shape: Union[Tuple[int, ...], torch.Size],
low: Union[float, int, Tensor],
high: Union[float, int, Tensor],
same_on_batch: bool = False,
@@ -246,7 +246,7 @@ def _adapted_uniform(
def _adapted_beta(
- shape: Union[Tuple, torch.Size],
+ shape: Union[Tuple[int, ...], torch.Size],
a: Union[float, int, Tensor],
b: Union[float, int, Tensor],
same_on_batch: bool = False,
@@ -266,7 +266,7 @@ def _adapted_beta(
return _adapted_rsampling(shape, dist, same_on_batch)
-def _shape_validation(param: Tensor, shape: Union[tuple, list], name: str) -> None:
+def _shape_validation(param: Tensor, shape: Union[Tuple[int, ...], List[int]], name: str) -> None:
if param.shape != torch.Size(shape):
raise AssertionError(f"Invalid shape for {name}. Expected {shape}. Got {param.shape}")
diff --git a/kornia/augmentation/utils/param_validation.py b/kornia/augmentation/utils/param_validation.py
index f89b93d8d..f0478c6de 100644
--- a/kornia/augmentation/utils/param_validation.py
+++ b/kornia/augmentation/utils/param_validation.py
@@ -1,4 +1,4 @@
-from typing import List, Optional, Tuple, Union
+from typing import Any, List, Optional, Tuple, Union
import torch
@@ -96,7 +96,7 @@ def _singular_range_check(
def _tuple_range_reader(
- input_range: Union[Tensor, float, tuple],
+ input_range: Union[Tensor, float, Tuple[Any, ...]],
target_size: int,
device: Optional[torch.device] = None,
dtype: Optional[torch.dtype] = None,
diff --git a/kornia/contrib/diamond_square.py b/kornia/contrib/diamond_square.py
index 7f0753823..29833ac24 100644
--- a/kornia/contrib/diamond_square.py
+++ b/kornia/contrib/diamond_square.py
@@ -3,8 +3,8 @@ import math
from typing import Callable, List, Optional, Tuple, Union
import torch
-from torch import Tensor
+from kornia.core import Tensor
from kornia.enhance import normalize_min_max
from kornia.filters import filter2d
from kornia.testing import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SHAPE
@@ -18,7 +18,7 @@ def _diamond_square_seed(
replicates: int,
width: int,
height: int,
- random_fn: Callable,
+ random_fn: Callable[..., Tensor],
device: Optional[torch.device] = None,
dtype: Optional[torch.dtype] = None,
) -> Tensor:
@@ -73,7 +73,7 @@ def _diamond_square_seed(
def _one_diamond_one_square(
img: Tensor,
random_scale: Union[float, Tensor],
- random_fn: Callable = torch.rand,
+ random_fn: Callable[..., Tensor] = torch.rand,
diamond_kernel: Optional[Tensor] = None,
square_kernel: Optional[Tensor] = None,
) -> Tensor:
@@ -141,7 +141,7 @@ def diamond_square(
output_size: Tuple[int, int, int, int],
roughness: Union[float, Tensor] = 0.5,
random_scale: Union[float, Tensor] = 1.0,
- random_fn: Callable = torch.rand,
+ random_fn: Callable[..., Tensor] = torch.rand,
normalize_range: Optional[Tuple[int, int]] = None,
device: Optional[torch.device] = None,
dtype: Optional[torch.dtype] = None,
diff --git a/kornia/contrib/face_detection.py b/kornia/contrib/face_detection.py
index 48fb2af33..fbb0c60a4 100644
--- a/kornia/contrib/face_detection.py
+++ b/kornia/contrib/face_detection.py
@@ -1,13 +1,14 @@
# based on: https://github.com/ShiqiYu/libfacedetection.train/blob/74f3aa77c63234dd954d21286e9a60703b8d0868/tasks/task1/yufacedetectnet.py # noqa
import math
from enum import Enum
-from typing import Callable, Dict, List, Optional, Tuple
+from typing import Dict, List, Optional, Tuple
import torch
import torch.nn as nn
import torch.nn.functional as F
from kornia.geometry.bbox import nms as nms_kornia
+from kornia.utils.helpers import map_location_to_cpu
__all__ = ["FaceDetector", "FaceDetectorResult", "FaceKeypoint"]
@@ -159,12 +160,12 @@ class FaceDetector(nn.Module):
'variance': [0.1, 0.2],
'clip': False,
}
- self.min_sizes: List[List[int]] = [[10, 16, 24], [32, 48], [64, 96], [128, 192, 256]]
- self.steps: List[int] = [8, 16, 32, 64]
- self.variance: List[float] = [0.1, 0.2]
- self.clip: bool = False
+ self.min_sizes = [[10, 16, 24], [32, 48], [64, 96], [128, 192, 256]]
+ self.steps = [8, 16, 32, 64]
+ self.variance = [0.1, 0.2]
+ self.clip = False
self.model = YuFaceDetectNet('test', pretrained=True)
- self.nms: Callable = nms_kornia
+ self.nms = nms_kornia
def preprocess(self, image: torch.Tensor) -> torch.Tensor:
return image
@@ -287,8 +288,7 @@ class YuFaceDetectNet(nn.Module):
# use torch.hub to load pretrained model
if pretrained:
- storage_fcn: Callable = lambda storage, loc: storage
- pretrained_dict = torch.hub.load_state_dict_from_url(url, map_location=storage_fcn)
+ pretrained_dict = torch.hub.load_state_dict_from_url(url, map_location=map_location_to_cpu)
self.load_state_dict(pretrained_dict, strict=True)
self.eval()
diff --git a/kornia/contrib/image_stitching.py b/kornia/contrib/image_stitching.py
index 3d8548f6f..6b21c1fe0 100644
--- a/kornia/contrib/image_stitching.py
+++ b/kornia/contrib/image_stitching.py
@@ -1,16 +1,16 @@
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 Module, Tensor, concatenate, where, zeros_like
from kornia.feature import LocalFeatureMatcher, LoFTR
from kornia.geometry.homography import find_homography_dlt_iterated
from kornia.geometry.ransac import RANSAC
from kornia.geometry.transform import warp_perspective
-class ImageStitcher(nn.Module):
+class ImageStitcher(Module):
"""Stitch two images with overlapping fields of view.
Args:
@@ -33,7 +33,7 @@ class ImageStitcher(nn.Module):
plt.imshow(K.tensor_to_image(out))
"""
- def __init__(self, matcher: nn.Module, estimator: str = 'ransac', blending_method: str = "naive") -> None:
+ def __init__(self, matcher: Module, estimator: str = 'ransac', blending_method: str = "naive") -> None:
super().__init__()
self.matcher = matcher
self.estimator = estimator
@@ -43,14 +43,14 @@ class ImageStitcher(nn.Module):
if estimator == "ransac":
self.ransac = RANSAC('homography')
- def _estimate_homography(self, keypoints1: torch.Tensor, keypoints2: torch.Tensor) -> torch.Tensor:
+ def _estimate_homography(self, keypoints1: Tensor, keypoints2: Tensor) -> Tensor:
"""Estimate homography by the matched keypoints.
Args:
keypoints1: matched keypoint set from an image, shaped as :math:`(N, 2)`.
keypoints2: matched keypoint set from the other image, shaped as :math:`(N, 2)`.
"""
- homo: torch.Tensor
+ homo: Tensor
if self.estimator == "vanilla":
homo = find_homography_dlt_iterated(
keypoints2[None], keypoints1[None], torch.ones_like(keypoints1[None, :, 0])
@@ -62,30 +62,30 @@ class ImageStitcher(nn.Module):
raise NotImplementedError(f"Unsupported estimator {self.estimator}. Use ‘ransac’ or ‘vanilla’ instead.")
return homo
- def estimate_transform(self, **kwargs) -> torch.Tensor:
+ def estimate_transform(self, **kwargs) -> Tensor:
"""Compute the corresponding homography."""
- homos: List[torch.Tensor] = []
+ homos: List[Tensor] = []
kp1, kp2, idx = kwargs['keypoints0'], kwargs['keypoints1'], kwargs['batch_indexes']
for i in range(len(idx.unique())):
homos.append(self._estimate_homography(kp1[idx == i], kp2[idx == i]))
if len(homos) == 0:
raise RuntimeError("Compute homography failed. No matched keypoints found.")
- return torch.cat(homos)
+ return concatenate(homos)
- def blend_image(self, src_img: torch.Tensor, dst_img: torch.Tensor, mask: torch.Tensor) -> torch.Tensor:
+ def blend_image(self, src_img: Tensor, dst_img: Tensor, mask: Tensor) -> Tensor:
"""Blend two images together."""
- out: torch.Tensor
+ out: Tensor
if self.blending_method == "naive":
- out = torch.where(mask == 1, src_img, dst_img)
+ out = where(mask == 1, src_img, dst_img)
else:
raise NotImplementedError(f"Unsupported blending method {self.blending_method}. Use ‘naive’.")
return out
- def preprocess(self, image_1: torch.Tensor, image_2: torch.Tensor) -> Dict[str, torch.Tensor]:
+ def preprocess(self, image_1: Tensor, image_2: Tensor) -> Dict[str, Tensor]:
"""Preprocess input to the required format."""
# TODO: probably perform histogram matching here.
if isinstance(self.matcher, LoFTR) or isinstance(self.matcher, LocalFeatureMatcher):
- input_dict: Dict[str, torch.Tensor] = { # LofTR works on grayscale images only
+ input_dict: Dict[str, Tensor] = { # LofTR works on grayscale images only
"image0": rgb_to_grayscale(image_1),
"image1": rgb_to_grayscale(image_2),
}
@@ -93,31 +93,31 @@ class ImageStitcher(nn.Module):
raise NotImplementedError(f"The preprocessor for {self.matcher} has not been implemented.")
return input_dict
- def postprocess(self, image: torch.Tensor, mask: torch.Tensor) -> torch.Tensor:
+ def postprocess(self, image: Tensor, mask: Tensor) -> Tensor:
# NOTE: assumes no batch mode. This method keeps all valid regions after stitching.
- mask_: torch.Tensor = mask.sum((0, 1))
- index: int = int(mask_.bool().any(0).long().argmin().item())
+ mask_ = mask.sum((0, 1))
+ index = int(mask_.bool().any(0).long().argmin().item())
if index == 0: # If no redundant space
return image
return image[..., :index]
- def on_matcher(self, data) -> dict:
+ def on_matcher(self, data) -> Dict[str, Tensor]:
return self.matcher(data)
def stitch_pair(
self,
- images_left: torch.Tensor,
- images_right: torch.Tensor,
- mask_left: Optional[torch.Tensor] = None,
- mask_right: Optional[torch.Tensor] = None,
- ) -> Tuple[torch.Tensor, torch.Tensor]:
+ images_left: Tensor,
+ images_right: Tensor,
+ mask_left: Optional[Tensor] = None,
+ mask_right: Optional[Tensor] = None,
+ ) -> Tuple[Tensor, Tensor]:
# Compute the transformed images
- input_dict: Dict[str, torch.Tensor] = self.preprocess(images_left, images_right)
- out_shape: Tuple[int, int] = (images_left.shape[-2], images_left.shape[-1] + images_right.shape[-1])
- correspondences: dict = self.on_matcher(input_dict)
- homo: torch.Tensor = self.estimate_transform(**correspondences)
+ input_dict = self.preprocess(images_left, images_right)
+ out_shape = (images_left.shape[-2], images_left.shape[-1] + images_right.shape[-1])
+ correspondences = self.on_matcher(input_dict)
+ homo: Tensor = self.estimate_transform(**correspondences)
src_img = warp_perspective(images_right, homo, out_shape)
- dst_img = torch.cat([images_left, torch.zeros_like(images_right)], dim=-1)
+ dst_img = concatenate([images_left, zeros_like(images_right)], -1)
# Compute the transformed masks
if mask_left is None:
@@ -126,10 +126,10 @@ class ImageStitcher(nn.Module):
mask_right = torch.ones_like(images_right)
# 'nearest' to ensure no floating points in the mask
src_mask = warp_perspective(mask_right, homo, out_shape, mode='nearest')
- dst_mask = torch.cat([mask_left, torch.zeros_like(mask_right)], dim=-1)
+ dst_mask = concatenate([mask_left, zeros_like(mask_right)], -1)
return self.blend_image(src_img, dst_img, src_mask), (dst_mask + src_mask).bool().to(src_mask.dtype)
- def forward(self, *imgs: torch.Tensor) -> torch.Tensor:
+ def forward(self, *imgs: Tensor) -> Tensor:
img_out = imgs[0]
mask_left = torch.ones_like(img_out)
for i in range(len(imgs) - 1):
diff --git a/kornia/contrib/lambda_module.py b/kornia/contrib/lambda_module.py
index 073ac531c..c14cb13cf 100644
--- a/kornia/contrib/lambda_module.py
+++ b/kornia/contrib/lambda_module.py
@@ -1,10 +1,9 @@
from typing import Callable
-import torch
-import torch.nn as nn
+from kornia.core import Module, Tensor
-class Lambda(nn.Module):
+class Lambda(Module):
"""Applies user-defined lambda as a transform.
Args:
@@ -21,12 +20,12 @@ class Lambda(nn.Module):
torch.Size([1, 1, 5, 5])
"""
- def __init__(self, func: Callable) -> None:
+ def __init__(self, func: Callable[..., Tensor]) -> None:
super().__init__()
if not callable(func):
raise TypeError(f"Argument lambd should be callable, got {repr(type(func).__name__)}")
self.func = func
- def forward(self, img: torch.Tensor, *args, **kwargs) -> torch.Tensor:
+ def forward(self, img: Tensor, *args, **kwargs) -> Tensor:
return self.func(img, *args, **kwargs)
diff --git a/kornia/feature/adalam/adalam.py b/kornia/feature/adalam/adalam.py
index 3e49e65cd..b2c6bb8ca 100644
--- a/kornia/feature/adalam/adalam.py
+++ b/kornia/feature/adalam/adalam.py
@@ -2,34 +2,32 @@
# https://github.com/cavalli1234/AdaLAM
# Copyright (c) 2020, Luca Cavalli
-from typing import Dict, Optional, Tuple, Union
+from typing import Optional, Tuple, Union
import torch
-from torch import Tensor
+from kornia.core 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 .core import _no_match, adalam_core
+from .core import AdalamConfig, _no_match, 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': torch.device('cpu'), # Device to be used for running AdaLAM. Use GPU if available.
- }
- return DEFAULT_CONFIG
+def get_adalam_default_config() -> AdalamConfig:
+ return AdalamConfig(
+ area_ratio=100,
+ search_expansion=4,
+ ransac_iters=128,
+ min_inliers=6,
+ min_confidence=200,
+ orientation_difference_threshold=30,
+ scale_rate_threshold=1.5,
+ detected_scale_rate_threshold=5,
+ refit=True,
+ force_seed_mnn=True,
+ device=torch.device('cpu'),
+ )
def match_adalam(
@@ -37,7 +35,7 @@ def match_adalam(
desc2: Tensor,
lafs1: Tensor,
lafs2: Tensor,
- config: Optional[Dict] = None,
+ config: Optional[AdalamConfig] = None,
hw1: Optional[Tensor] = None,
hw2: Optional[Tensor] = None,
dm: Optional[Tensor] = None,
@@ -88,40 +86,31 @@ def match_adalam(
class AdalamFilter:
- DEFAULT_CONFIG = get_adalam_default_config()
-
- def __init__(self, custom_config: Optional[dict] = None):
+ def __init__(self, custom_config: Optional[AdalamConfig] = 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(
- f"WARNING: custom configuration contains a key which is not recognized ({key}). "
- f"Known configurations are {list(self.config.keys())}."
- )
- continue
- self.config[key] = val
+ self.config = custom_config
+ else:
+ self.config = get_adalam_default_config()
def filter_matches(
self,
- k1: torch.Tensor,
- k2: torch.Tensor,
- putative_matches: torch.Tensor,
- scores: torch.Tensor,
- mnn: Optional[torch.Tensor] = None,
- im1shape: Optional[tuple] = None,
- im2shape: Optional[tuple] = None,
- o1: Optional[torch.Tensor] = None,
- o2: Optional[torch.Tensor] = None,
- s1: Optional[torch.Tensor] = None,
- s2: Optional[torch.Tensor] = None,
+ k1: Tensor,
+ k2: Tensor,
+ putative_matches: Tensor,
+ scores: Tensor,
+ mnn: Optional[Tensor] = None,
+ im1shape: Optional[Tuple[int, int]] = None,
+ im2shape: Optional[Tuple[int, int]] = None,
+ o1: Optional[Tensor] = None,
+ o2: Optional[Tensor] = None,
+ s1: Optional[Tensor] = None,
+ s2: Optional[Tensor] = None,
return_dist: bool = False,
) -> Union[Tuple[Tensor, Tensor], Tensor]:
"""Call the core functionality of AdaLAM, i.e. just outlier filtering. No sanity check is performed on the
@@ -134,19 +123,22 @@ class AdalamFilter:
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.
+ 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.
+ 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.
@@ -156,7 +148,7 @@ class AdalamFilter:
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,
diff --git a/kornia/feature/adalam/core.py b/kornia/feature/adalam/core.py
index 214c69228..3d710cccf 100644
--- a/kornia/feature/adalam/core.py
+++ b/kornia/feature/adalam/core.py
@@ -2,13 +2,51 @@ import math
from typing import Optional, Tuple, Union
import torch
+from typing_extensions import NotRequired, TypedDict
-from kornia.core import Tensor, concatenate, tensor, where
+from kornia.core import Device, Tensor, concatenate, tensor, where
from .ransac import ransac
from .utils import dist_matrix, orientation_diff
+class AdalamConfig(TypedDict):
+ """
+ area_ratio: Ratio between seed circle area and image area. Higher values produce more seeds with smaller
+ neighborhoods
+ search_expansion: Expansion factor of the seed circle radius for the purpose of collecting neighborhoods.
+ Increases neighborhood radius without changing seed distribution
+ ransac_iters: Fixed number of inner GPU-RANSAC iterations
+ min_inliers: Minimum number of inliers required to accept inliers coming from a neighborhood
+ min_confidence: Threshold used by the confidence-based GPU-RANSAC
+ orientation_difference_threshold: Maximum difference in orientations for a point to be accepted in a
+ neighborhood. Set to None to disable the use of keypoint orientations
+ scale_rate_threshold: Maximum difference (ratio) in scales for a point to be accepted in a neighborhood. Set
+ to None to disable the use of keypoint scales
+ detected_scale_rate_threshold: Prior on maximum possible scale change detectable in image couples. Affinities
+ with higher scale changes are regarded as outliers
+ refit: Whether to perform refitting at the end of the RANSACs. Generally improves accuracy at the cost of
+ runtime
+ force_seed_mnn: Whether to consider only MNN for the purpose of selecting seeds. Generally improves accuracy
+ at the cost of runtime
+ device: Device to be used for running AdaLAM. Use GPU if available.
+ mnn: Default None. You can provide a MNN mask in input to skip MNN computation and still get the improvement.
+ """
+
+ area_ratio: NotRequired[int]
+ search_expansion: NotRequired[int]
+ ransac_iters: NotRequired[int]
+ min_inliers: NotRequired[int]
+ min_confidence: NotRequired[int]
+ orientation_difference_threshold: NotRequired[int]
+ scale_rate_threshold: NotRequired[float]
+ detected_scale_rate_threshold: NotRequired[int]
+ refit: NotRequired[bool]
+ force_seed_mnn: NotRequired[bool]
+ device: NotRequired[Device]
+ mnn: NotRequired[Tensor]
+
+
def _no_match(dm: Tensor):
"""Helper function, which output empty tensors.
@@ -208,10 +246,10 @@ def adalam_core(
k2: Tensor,
fnn12: Tensor,
scores1: Tensor,
- config: dict,
+ config: AdalamConfig,
mnn: Optional[Tensor] = None,
- im1shape: Optional[Tuple] = None,
- im2shape: Optional[Tuple] = None,
+ im1shape: Optional[Tuple[int, int]] = None,
+ im2shape: Optional[Tuple[int, int]] = None,
o1: Optional[Tensor] = None,
o2: Optional[Tensor] = None,
s1: Optional[Tensor] = None,
diff --git a/kornia/feature/affine_shape.py b/kornia/feature/affine_shape.py
index 63e873717..3f1d8fbd3 100644
--- a/kornia/feature/affine_shape.py
+++ b/kornia/feature/affine_shape.py
@@ -1,6 +1,6 @@
import math
import warnings
-from typing import Callable, Dict, Optional
+from typing import Dict, Optional
import torch
import torch.nn as nn
@@ -8,6 +8,7 @@ import torch.nn as nn
from kornia.filters.kernels import get_gaussian_kernel2d
from kornia.filters.sobel import SpatialGradient
from kornia.testing import KORNIA_CHECK_LAF, KORNIA_CHECK_SHAPE
+from kornia.utils.helpers import map_location_to_cpu
from .laf import (
ellipse_to_laf,
@@ -189,8 +190,7 @@ class LAFAffNetShapeEstimator(nn.Module):
self.patch_size = 32
# use torch.hub to load pretrained model
if pretrained:
- storage_fcn: Callable = lambda storage, loc: storage
- pretrained_dict = torch.hub.load_state_dict_from_url(urls['affnet'], map_location=storage_fcn)
+ pretrained_dict = torch.hub.load_state_dict_from_url(urls['affnet'], map_location=map_location_to_cpu)
self.load_state_dict(pretrained_dict['state_dict'], strict=False)
self.preserve_orientation = preserve_orientation
if preserve_orientation:
diff --git a/kornia/feature/hardnet.py b/kornia/feature/hardnet.py
index 59b01aee8..df0311c62 100644
--- a/kornia/feature/hardnet.py
+++ b/kornia/feature/hardnet.py
@@ -1,17 +1,18 @@
-from typing import Callable, Dict
+from typing import Dict
import torch
import torch.nn as nn
import torch.nn.functional as F
from kornia.testing import KORNIA_CHECK_SHAPE, is_mps_tensor_safe
+from kornia.utils.helpers import map_location_to_cpu
urls: Dict[str, str] = {}
urls["hardnet++"] = "https://github.com/DagnyT/hardnet/raw/master/pretrained/pretrained_all_datasets/HardNet++.pth"
urls[
"liberty_aug"
-] = "https://github.com/DagnyT/hardnet/raw/master/pretrained/train_liberty_with_aug/checkpoint_liberty_with_aug.pth" # noqa pylint: disable
-urls["hardnet8v2"] = "http://cmp.felk.cvut.cz/~mishkdmy/hardnet8v2.pt" # pylint: disable
+] = "https://github.com/DagnyT/hardnet/raw/master/pretrained/train_liberty_with_aug/checkpoint_liberty_with_aug.pth"
+urls["hardnet8v2"] = "http://cmp.felk.cvut.cz/~mishkdmy/hardnet8v2.pt"
class HardNet(nn.Module):
@@ -65,8 +66,7 @@ class HardNet(nn.Module):
# use torch.hub to load pretrained model
if pretrained:
- storage_fcn: Callable = lambda storage, loc: storage
- pretrained_dict = torch.hub.load_state_dict_from_url(urls['liberty_aug'], map_location=storage_fcn)
+ pretrained_dict = torch.hub.load_state_dict_from_url(urls['liberty_aug'], map_location=map_location_to_cpu)
self.load_state_dict(pretrained_dict['state_dict'], strict=True)
self.eval()
@@ -148,8 +148,7 @@ class HardNet8(nn.Module):
# use torch.hub to load pretrained model
if pretrained:
- storage_fcn: Callable = lambda storage, loc: storage
- pretrained_dict = torch.hub.load_state_dict_from_url(urls['hardnet8v2'], map_location=storage_fcn)
+ pretrained_dict = torch.hub.load_state_dict_from_url(urls['hardnet8v2'], map_location=map_location_to_cpu)
self.load_state_dict(pretrained_dict, strict=True)
self.eval()
diff --git a/kornia/feature/hynet.py b/kornia/feature/hynet.py
index ca87baf5b..162c7a334 100644
--- a/kornia/feature/hynet.py
+++ b/kornia/feature/hynet.py
@@ -1,8 +1,11 @@
-from typing import Callable, Dict
+from typing import Dict
import torch
import torch.nn as nn
+from kornia.core import Module, Parameter, Tensor, tensor, zeros
+from kornia.utils.helpers import map_location_to_cpu
+
urls: Dict[str, str] = {}
urls[
"liberty"
@@ -15,7 +18,7 @@ urls[
] = "https://github.com/ducha-aiki/Key.Net-Pytorch/raw/main/model/HyNet/weights/HyNet_YOS.pth" # pylint: disable
-class FilterResponseNorm2d(nn.Module):
+class FilterResponseNorm2d(Module):
r"""Feature Response Normalization layer from 'Filter Response Normalization Layer: Eliminating Batch Dependence
in the Training of Deep Neural Networks', see :cite:`FRN2019` for more details.
@@ -56,12 +59,12 @@ class FilterResponseNorm2d(nn.Module):
self.is_bias = is_bias
self.is_scale = is_scale
- self.weight = nn.parameter.Parameter(torch.ones(1, num_features, 1, 1), requires_grad=True)
- self.bias = nn.parameter.Parameter(torch.zeros(1, num_features, 1, 1), requires_grad=True)
+ self.weight = Parameter(torch.ones(1, num_features, 1, 1), requires_grad=True)
+ self.bias = Parameter(zeros(1, num_features, 1, 1), requires_grad=True)
if is_eps_leanable:
- self.eps = nn.parameter.Parameter(torch.tensor(1), requires_grad=True)
+ self.eps = Parameter(tensor(1), requires_grad=True)
else:
- self.register_buffer('eps', torch.tensor([eps]))
+ self.register_buffer('eps', tensor([eps]))
self.reset_parameters()
def reset_parameters(self):
@@ -73,7 +76,7 @@ class FilterResponseNorm2d(nn.Module):
def extra_repr(self):
return 'num_features={num_features}, eps={init_eps}'.format(**self.__dict__)
- def forward(self, x: torch.Tensor) -> torch.Tensor:
+ def forward(self, x: Tensor) -> Tensor:
# Compute the mean norm of activations per channel.
nu2 = x.pow(2).mean(dim=[2, 3], keepdim=True)
@@ -88,7 +91,7 @@ class FilterResponseNorm2d(nn.Module):
return x
-class TLU(nn.Module):
+class TLU(Module):
r"""TLU layer from 'Filter Response Normalization Layer: Eliminating Batch Dependence in the Training of Deep
Neural Networks, see :cite:`FRN2019` for more details. :math:`{\tau}` is learnable per channel.
@@ -110,7 +113,7 @@ class TLU(nn.Module):
"""max(y, tau) = max(y - tau, 0) + tau = ReLU(y - tau) + tau"""
super().__init__()
self.num_features = num_features
- self.tau = nn.parameter.Parameter(-torch.ones(1, num_features, 1, 1), requires_grad=True)
+ self.tau = Parameter(-torch.ones(1, num_features, 1, 1), requires_grad=True)
self.reset_parameters()
def reset_parameters(self):
@@ -120,11 +123,11 @@ class TLU(nn.Module):
def extra_repr(self):
return 'num_features={num_features}'.format(**self.__dict__)
- def forward(self, x: torch.Tensor) -> torch.Tensor:
+ def forward(self, x: Tensor) -> Tensor:
return torch.max(x, self.tau)
-class HyNet(nn.Module):
+class HyNet(Module):
r"""Module, which computes HyNet descriptors of given grayscale patches of 32x32.
This is based on the original code from paper
@@ -212,13 +215,12 @@ class HyNet(nn.Module):
self.desc_norm = nn.LocalResponseNorm(2 * self.dim_desc, 2.0 * self.dim_desc, 0.5, 0.0)
# use torch.hub to load pretrained model
if pretrained:
- storage_fcn: Callable = lambda storage, loc: storage
- pretrained_dict = torch.hub.load_state_dict_from_url(urls['liberty'], map_location=storage_fcn)
+ pretrained_dict = torch.hub.load_state_dict_from_url(urls['liberty'], map_location=map_location_to_cpu)
self.load_state_dict(pretrained_dict, strict=True)
self.eval()
return
- def forward(self, x: torch.Tensor) -> torch.Tensor:
+ def forward(self, x: Tensor) -> Tensor:
x = self.layer1(x)
x = self.layer2(x)
x = self.layer3(x)
diff --git a/kornia/feature/integrated.py b/kornia/feature/integrated.py
index ed417a71c..b21971095 100644
--- a/kornia/feature/integrated.py
+++ b/kornia/feature/integrated.py
@@ -253,7 +253,7 @@ class LocalFeatureMatcher(Module):
lafs0, resps0, descs0 = self.local_feature(image, mask)
return {"lafs": lafs0, "responses": resps0, "descriptors": descs0}
- def no_match_output(self, device: Device, dtype: torch.dtype) -> dict:
+ def no_match_output(self, device: Device, dtype: torch.dtype) -> Dict[str, Tensor]:
return {
'keypoints0': torch.empty(0, 2, device=device, dtype=dtype),
'keypoints1': torch.empty(0, 2, device=device, dtype=dtype),
diff --git a/kornia/feature/keynet.py b/kornia/feature/keynet.py
index 56cd2406e..516a8e04a 100644
--- a/kornia/feature/keynet.py
+++ b/kornia/feature/keynet.py
@@ -1,35 +1,46 @@
import math
-from typing import Callable, Dict, List, Optional, Tuple
+from typing import List, Optional, Tuple
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.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
-keynet_config = {
- 'KeyNet_default_config': {
- # Key.Net Model
- 'num_filters': 8,
- '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,
- }
+
+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
+
+
+keynet_default_config: KeyNet_conf = {
+ # Key.Net Model
+ 'num_filters': 8,
+ '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,
}
-urls: Dict[str, str] = {}
-urls["keynet"] = "https://github.com/axelBarroso/Key.Net-Pytorch/raw/main/model/weights/keynet_pytorch.pth"
+KeyNet_URL = "https://github.com/axelBarroso/Key.Net-Pytorch/raw/main/model/weights/keynet_pytorch.pth"
class _FeatureExtractor(Module):
@@ -127,13 +138,13 @@ class KeyNet(Module):
- Output: :math:`(B, 1, H, W)`
"""
- def __init__(self, pretrained: bool = False, keynet_conf: Dict = keynet_config['KeyNet_default_config']):
+ def __init__(self, pretrained: bool = False, keynet_conf: KeyNet_conf = keynet_default_config):
super().__init__()
num_filters = keynet_conf['num_filters']
- self.num_levels: int = keynet_conf['num_levels']
- kernel_size: int = keynet_conf['kernel_size']
- padding: int = kernel_size // 2
+ self.num_levels = keynet_conf['num_levels']
+ kernel_size = keynet_conf['kernel_size']
+ padding = kernel_size // 2
self.feature_extractor = _FeatureExtractor()
self.last_conv = nn.Sequential(
@@ -144,8 +155,7 @@ class KeyNet(Module):
)
# use torch.hub to load pretrained model
if pretrained:
- storage_fcn: Callable = lambda storage, loc: storage
- pretrained_dict = torch.hub.load_state_dict_from_url(urls['keynet'], map_location=storage_fcn)
+ pretrained_dict = torch.hub.load_state_dict_from_url(KeyNet_URL, map_location=map_location_to_cpu)
self.load_state_dict(pretrained_dict['state_dict'], strict=True)
self.eval()
@@ -185,18 +195,18 @@ class KeyNetDetector(Module):
self,
pretrained: bool = False,
num_features: int = 2048,
- keynet_conf: Dict = keynet_config['KeyNet_default_config'],
+ keynet_conf: KeyNet_conf = keynet_default_config,
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: int = keynet_conf['pyramid_levels']
- self.num_upscale_levels: int = keynet_conf['up_levels']
- self.scale_factor_levels: float = keynet_conf['scale_factor_levels']
- self.mr_size: float = keynet_conf['s_mult']
- self.nms_size: int = keynet_conf['nms_size']
+ 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
diff --git a/kornia/feature/loftr/loftr.py b/kornia/feature/loftr/loftr.py
index 4078adfb3..52c771958 100644
--- a/kornia/feature/loftr/loftr.py
+++ b/kornia/feature/loftr/loftr.py
@@ -1,9 +1,10 @@
-from typing import Callable, Dict, Optional
+from typing import Any, Dict, Optional, Union
import torch
-import torch.nn as nn
+from kornia.core import Module, Tensor
from kornia.geometry import resize
+from kornia.utils.helpers import map_location_to_cpu
from .backbone import build_backbone
from .loftr_module import FinePreprocess, LocalFeatureTransformer
@@ -48,7 +49,7 @@ default_cfg = {
}
-class LoFTR(nn.Module):
+class LoFTR(Module):
r"""Module, which finds correspondences between two images.
This is based on the original code from paper "LoFTR: Detector-Free Local
@@ -73,7 +74,7 @@ class LoFTR(nn.Module):
>>> out = loftr(input)
"""
- def __init__(self, pretrained: Optional[str] = 'outdoor', config: Dict = default_cfg):
+ def __init__(self, pretrained: Optional[str] = 'outdoor', config: Dict[str, Any] = default_cfg):
super().__init__()
# Misc
self.config = config
@@ -93,12 +94,12 @@ class LoFTR(nn.Module):
if pretrained is not None:
if pretrained not in urls.keys():
raise ValueError(f"pretrained should be None or one of {urls.keys()}")
- storage_fcn: Callable = lambda storage, loc: storage
- pretrained_dict = torch.hub.load_state_dict_from_url(urls[pretrained], map_location=storage_fcn)
+
+ pretrained_dict = torch.hub.load_state_dict_from_url(urls[pretrained], map_location=map_location_to_cpu)
self.load_state_dict(pretrained_dict['state_dict'])
self.eval()
- def forward(self, data: dict) -> 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:
@@ -117,17 +118,19 @@ class LoFTR(nn.Module):
"""
# 1. Local Feature CNN
- data.update(
- {'bs': data['image0'].size(0), 'hw0_i': data['image0'].shape[2:], 'hw1_i': data['image1'].shape[2:]}
- )
+ _data: Dict[str, Union[Tensor, int, torch.Size]] = {
+ 'bs': data['image0'].size(0),
+ 'hw0_i': data['image0'].shape[2:],
+ 'hw1_i': data['image1'].shape[2:],
+ }
- if data['hw0_i'] == data['hw1_i']: # faster & better BN convergence
+ if _data['hw0_i'] == _data['hw1_i']: # faster & better BN convergence
feats_c, feats_f = self.backbone(torch.cat([data['image0'], data['image1']], dim=0))
- (feat_c0, feat_c1), (feat_f0, feat_f1) = feats_c.split(data['bs']), feats_f.split(data['bs'])
+ (feat_c0, feat_c1), (feat_f0, feat_f1) = feats_c.split(_data['bs']), feats_f.split(_data['bs'])
else: # handle different input shapes
(feat_c0, feat_f0), (feat_c1, feat_f1) = self.backbone(data['image0']), self.backbone(data['image1'])
- data.update(
+ _data.update(
{
'hw0_c': feat_c0.shape[2:],
'hw1_c': feat_c1.shape[2:],
@@ -150,22 +153,22 @@ class LoFTR(nn.Module):
feat_c1 = feat_c1.reshape(n1, -1, c1)
mask_c0 = mask_c1 = None # mask is useful in training
- if 'mask0' in data:
- mask_c0 = resize(data['mask0'], data['hw0_c'], interpolation='nearest').flatten(-2)
- if 'mask1' in data:
- mask_c1 = resize(data['mask1'], data['hw1_c'], interpolation='nearest').flatten(-2)
+ if 'mask0' in _data:
+ mask_c0 = resize(data['mask0'], _data['hw0_c'], interpolation='nearest').flatten(-2)
+ if 'mask1' in _data:
+ mask_c1 = resize(data['mask1'], _data['hw1_c'], interpolation='nearest').flatten(-2)
feat_c0, feat_c1 = self.loftr_coarse(feat_c0, feat_c1, mask_c0, mask_c1)
# 3. match coarse-level
- self.coarse_matching(feat_c0, feat_c1, data, mask_c0=mask_c0, mask_c1=mask_c1)
+ self.coarse_matching(feat_c0, feat_c1, _data, mask_c0=mask_c0, mask_c1=mask_c1)
# 4. fine-level refinement
- feat_f0_unfold, feat_f1_unfold = self.fine_preprocess(feat_f0, feat_f1, feat_c0, feat_c1, data)
+ feat_f0_unfold, feat_f1_unfold = self.fine_preprocess(feat_f0, feat_f1, feat_c0, feat_c1, _data)
if feat_f0_unfold.size(0) != 0: # at least one coarse level predicted
feat_f0_unfold, feat_f1_unfold = self.loftr_fine(feat_f0_unfold, feat_f1_unfold)
# 5. match fine-level
- self.fine_matching(feat_f0_unfold, feat_f1_unfold, data)
+ self.fine_matching(feat_f0_unfold, feat_f1_unfold, _data)
rename_keys: Dict[str, str] = {
"mkpts0_f": 'keypoints0',
@@ -173,9 +176,13 @@ class LoFTR(nn.Module):
"mconf": 'confidence',
"b_ids": 'batch_indexes',
}
- out = {}
+ out: Dict[str, Tensor] = {}
for k, v in rename_keys.items():
- out[v] = data[k]
+ _d = _data[k]
+ if isinstance(_d, Tensor):
+ out[v] = _d
+ else:
+ raise TypeError(f'Expected Tensor for item `{k}`. Gotcha {type(_d)}')
return out
def load_state_dict(self, state_dict, *args, **kwargs):
diff --git a/kornia/feature/matching.py b/kornia/feature/matching.py
index 83d73b256..430fc4712 100644
--- a/kornia/feature/matching.py
+++ b/kornia/feature/matching.py
@@ -346,7 +346,7 @@ class GeometryAwareDescriptorMatcher(nn.Module):
known_modes = ['fginn', "adalam"]
- def __init__(self, match_mode: str = 'fginn', params: Dict = {}) -> None:
+ def __init__(self, match_mode: str = 'fginn', params: Dict[str, Tensor] = {}) -> None:
super().__init__()
_match_mode: str = match_mode.lower()
if _match_mode not in self.known_modes:
diff --git a/kornia/feature/mkd.py b/kornia/feature/mkd.py
index 159ba8b94..8dd4626f2 100644
--- a/kornia/feature/mkd.py
+++ b/kornia/feature/mkd.py
@@ -1,13 +1,15 @@
-from typing import Callable, Dict, List, Tuple, Union
+from typing import Any, Dict, List, Tuple, Union
import torch
import torch.nn as nn
import torch.nn.functional as F
from kornia.constants import pi
+from kornia.core import Tensor, tensor, zeros
from kornia.filters import GaussianBlur2d, SpatialGradient
from kornia.geometry.conversions import cart2pol
from kornia.utils import create_meshgrid
+from kornia.utils.helpers import map_location_to_cpu
# Precomputed coefficients for Von Mises kernel, given N and K(appa).
sqrt2: float = 1.4142135623730951
@@ -22,7 +24,7 @@ urls: Dict[str, str] = {
}
-def get_grid_dict(patch_size: int = 32) -> Dict[str, torch.Tensor]:
+def get_grid_dict(patch_size: int = 32) -> Dict[str, Tensor]:
r"""Get cartesian and polar parametrizations of grid."""
kgrid = create_meshgrid(height=patch_size, width=patch_size, normalized_coordinates=True)
x = kgrid[0, :, :, 0]
@@ -32,9 +34,9 @@ def get_grid_dict(patch_size: int = 32) -> Dict[str, torch.Tensor]:
return grid_dict
-def get_kron_order(d1: int, d2: int) -> torch.Tensor:
+def get_kron_order(d1: int, d2: int) -> Tensor:
r"""Get order for doing kronecker product."""
- kron_order = torch.zeros([d1 * d2, 2], dtype=torch.int64)
+ kron_order = zeros([d1 * d2, 2], dtype=torch.int64)
for i in range(d1):
for j in range(d2):
kron_order[i * d2 + j, 0] = i
@@ -71,9 +73,9 @@ class MKDGradients(nn.Module):
self.grad = SpatialGradient(mode='diff', order=1, normalized=False)
- def forward(self, x: torch.Tensor) -> torch.Tensor:
- if not isinstance(x, torch.Tensor):
- raise TypeError(f"Input type is not a torch.Tensor. Got {type(x)}")
+ def forward(self, x: Tensor) -> Tensor:
+ if not isinstance(x, Tensor):
+ raise TypeError(f"Input type is not a Tensor. Got {type(x)}")
if not len(x.shape) == 4:
raise ValueError(f"Invalid input shape, we expect Bx1xHxW. Got: {x.shape}")
# Modify 'diff' gradient. Before we had lambda function, but it is not jittable
@@ -110,23 +112,23 @@ class VonMisesKernel(nn.Module):
>>> emb = vm(oris) # 23x7x32x32
"""
- def __init__(self, patch_size: int, coeffs: Union[list, tuple]) -> None:
+ def __init__(self, patch_size: int, coeffs: Union[List[Union[float, int]], Tuple[Union[float, int], ...]]) -> None:
super().__init__()
self.patch_size = patch_size
- b_coeffs: torch.Tensor = torch.tensor(coeffs)
+ b_coeffs = tensor(coeffs)
self.register_buffer('coeffs', b_coeffs)
# Compute parameters.
- n: int = len(coeffs) - 1
- self.n: int = n
- self.d: int = 2 * n + 1
+ n = len(coeffs) - 1
+ self.n = n
+ self.d = 2 * n + 1
# Precompute helper variables.
emb0 = torch.ones([1, 1, patch_size, patch_size])
frange = torch.arange(n) + 1
frange = frange.reshape(-1, 1, 1)
- weights = torch.zeros([2 * n + 1])
+ weights = zeros([2 * n + 1])
weights[: n + 1] = torch.sqrt(b_coeffs)
weights[n + 1 :] = torch.sqrt(b_coeffs[1:])
weights = weights.reshape(-1, 1, 1)
@@ -134,15 +136,15 @@ class VonMisesKernel(nn.Module):
self.register_buffer('frange', frange)
self.register_buffer('weights', weights)
- def forward(self, x: torch.Tensor) -> torch.Tensor:
- if not isinstance(x, torch.Tensor):
- raise TypeError(f"Input type is not a torch.Tensor. Got {type(x)}")
+ def forward(self, x: Tensor) -> Tensor:
+ if not isinstance(x, Tensor):
+ raise TypeError(f"Input type is not a Tensor. Got {type(x)}")
if not len(x.shape) == 4 or x.shape[1] != 1:
raise ValueError(f"Invalid input shape, we expect Bx1xHxW. Got: {x.shape}")
# TODO: unify the two lines below when pytorch 1.6 support is dropped
- emb0: torch.Tensor = torch.jit.annotate(torch.Tensor, self.emb0)
+ emb0: Tensor = torch.jit.annotate(Tensor, self.emb0)
emb0 = emb0.to(x).repeat(x.size(0), 1, 1, 1)
frange = self.frange.to(x) * x
emb1 = torch.cos(frange)
@@ -205,14 +207,14 @@ class EmbedGradients(nn.Module):
_, phi = cart2pol(kgrid[:, :, :, 0], kgrid[:, :, :, 1])
self.register_buffer('phi', phi)
- def emb_mags(self, mags: torch.Tensor) -> torch.Tensor:
+ def emb_mags(self, mags: Tensor) -> Tensor:
"""Embed square roots of magnitudes with eps for numerical reasons."""
mags = torch.sqrt(mags + self.eps)
return mags
- def forward(self, grads: torch.Tensor) -> torch.Tensor:
- if not isinstance(grads, torch.Tensor):
- raise TypeError(f"Input type is not a torch.Tensor. Got {type(grads)}")
+ def forward(self, grads: Tensor) -> Tensor:
+ if not isinstance(grads, Tensor):
+ raise TypeError(f"Input type is not a Tensor. Got {type(grads)}")
if not len(grads.shape) == 4:
raise ValueError(f"Invalid input shape, we expect Bx2xHxW. Got: {grads.shape}")
mags = grads[:, :1, :, :]
@@ -235,7 +237,7 @@ class EmbedGradients(nn.Module):
)
-def spatial_kernel_embedding(kernel_type, grids: dict) -> torch.Tensor:
+def spatial_kernel_embedding(kernel_type, grids: Dict[str, Tensor]) -> Tensor:
r"""Compute embeddings for cartesian and polar parametrizations."""
factors = {"phi": 1.0, "rho": pi / sqrt2, "x": pi / 2, "y": pi / 2}
if kernel_type == 'cart':
@@ -333,25 +335,25 @@ class ExplicitSpacialEncoding(nn.Module):
self.register_buffer('emb2', emb2)
self.register_buffer('idx1', idx1)
- def get_gmask(self, sigma: float) -> torch.Tensor:
+ def get_gmask(self, sigma: float) -> Tensor:
"""Compute Gaussian mask."""
norm_rho = self.grid['rho'] / self.grid['rho'].max()
gmask = torch.exp(-1 * norm_rho**2 / sigma**2)
return gmask
- def init_kron(self) -> Tuple[torch.Tensor, torch.Tensor]:
+ def init_kron(self) -> Tuple[Tensor, Tensor]:
"""Initialize helper variables to calculate kronecker."""
kron = get_kron_order(self.in_dims, self.d_emb)
- _emb = torch.jit.annotate(torch.Tensor, self.emb)
+ _emb = torch.jit.annotate(Tensor, self.emb)
emb2 = torch.index_select(_emb, 1, kron[:, 1])
return emb2, kron[:, 0]
- def forward(self, x: torch.Tensor) -> torch.Tensor:
- if not isinstance(x, torch.Tensor):
- raise TypeError(f"Input type is not a torch.Tensor. Got {type(x)}")
+ def forward(self, x: Tensor) -> Tensor:
+ if not isinstance(x, Tensor):
+ raise TypeError(f"Input type is not a Tensor. Got {type(x)}")
if not ((len(x.shape) == 4) | (x.shape[1] == self.in_dims)):
raise ValueError(f"Invalid input shape, we expect Bx{self.in_dims}xHxW. Got: {x.shape}")
- idx1 = torch.jit.annotate(torch.Tensor, self.idx1)
+ idx1 = torch.jit.annotate(Tensor, self.idx1)
emb1 = torch.index_select(x, 1, idx1)
output = emb1 * self.emb2
output = output.sum(dim=(2, 3))
@@ -392,7 +394,7 @@ class Whitening(nn.Module):
Args:
xform: Variant of whitening to use. None, 'lw', 'pca', 'pcaws', 'pcawt'.
- whitening_model: Dictionary with keys 'mean', 'eigvecs', 'eigvals' holding torch.Tensors.
+ whitening_model: Dictionary with keys 'mean', 'eigvecs', 'eigvals' holding Tensors.
in_dims: Dimensionality of input descriptors.
output_dims: (int) Dimensionality reduction.
keval: Shrinkage parameter.
@@ -422,7 +424,7 @@ class Whitening(nn.Module):
def __init__(
self,
xform: str,
- whitening_model: Union[Dict[str, Dict[str, torch.Tensor]], None],
+ whitening_model: Union[Dict[str, Dict[str, Tensor]], None],
in_dims: int,
output_dims: int = 128,
keval: int = 40,
@@ -441,14 +443,14 @@ class Whitening(nn.Module):
self.output_dims = output_dims
# Initialize identity transform.
- self.mean = nn.Parameter(torch.zeros(in_dims), requires_grad=True)
+ self.mean = nn.Parameter(zeros(in_dims), requires_grad=True)
self.evecs = nn.Parameter(torch.eye(in_dims)[:, :output_dims], requires_grad=True)
self.evals = nn.Parameter(torch.ones(in_dims)[:output_dims], requires_grad=True)
if whitening_model is not None:
self.load_whitening_parameters(whitening_model)
- def load_whitening_parameters(self, whitening_model: Dict[str, Dict[str, torch.Tensor]]) -> None:
+ def load_whitening_parameters(self, whitening_model: Dict[str, Dict[str, Tensor]]) -> None:
algo = 'lw' if self.xform == 'lw' else 'pca'
wh_model = whitening_model[algo]
self.mean.data = wh_model['mean']
@@ -483,9 +485,9 @@ class Whitening(nn.Module):
m = -0.5 * self.t
self.evecs.data = self.evecs @ torch.diag(torch.pow(self.evals, m))
- def forward(self, x: torch.Tensor) -> torch.Tensor:
- if not isinstance(x, torch.Tensor):
- raise TypeError(f"Input type is not a torch.Tensor. Got {type(x)}")
+ def forward(self, x: Tensor) -> Tensor:
+ if not isinstance(x, Tensor):
+ raise TypeError(f"Input type is not a Tensor. Got {type(x)}")
if not len(x.shape) == 2:
raise ValueError(f"Invalid input shape, we expect NxD. Got: {x.shape}")
x = x - self.mean # Center the data.
@@ -579,8 +581,9 @@ class MKDDescriptor(nn.Module):
# Load supervised(lw)/unsupervised(pca) model trained on training_set.
if self.whitening is not None:
- storage_fcn: Callable = lambda storage, loc: storage
- whitening_models = torch.hub.load_state_dict_from_url(urls[self.kernel_type], map_location=storage_fcn)
+ whitening_models = torch.hub.load_state_dict_from_url(
+ urls[self.kernel_type], map_location=map_location_to_cpu
+ )
whitening_model = whitening_models[training_set]
self.whitening_layer = Whitening(
whitening, whitening_model, in_dims=self.odims, output_dims=self.output_dims
@@ -588,9 +591,9 @@ class MKDDescriptor(nn.Module):
self.odims = self.output_dims
self.eval()
- def forward(self, patches: torch.Tensor) -> torch.Tensor:
- if not isinstance(patches, torch.Tensor):
- raise TypeError(f"Input type is not a torch.Tensor. Got {type(patches)}")
+ def forward(self, patches: Tensor) -> Tensor:
+ if not isinstance(patches, Tensor):
+ raise TypeError(f"Input type is not a Tensor. Got {type(patches)}")
if not len(patches.shape) == 4:
raise ValueError(f"Invalid input shape, we expect Bx1xHxW. Got: {patches.shape}")
# Extract gradients.
@@ -637,9 +640,8 @@ class MKDDescriptor(nn.Module):
)
-def load_whitening_model(kernel_type: str, training_set: str) -> Dict:
- storage_fcn: Callable = lambda storage, loc: storage
- whitening_models = torch.hub.load_state_dict_from_url(urls[kernel_type], map_location=storage_fcn)
+def load_whitening_model(kernel_type: str, training_set: str) -> Dict[str, Any]:
+ whitening_models = torch.hub.load_state_dict_from_url(urls[kernel_type], map_location=map_location_to_cpu)
whitening_model = whitening_models[training_set]
return whitening_model
@@ -671,5 +673,5 @@ class SimpleKD(nn.Module):
self.features = nn.Sequential(smoothing, gradients, ori, ese, wh)
- def forward(self, x: torch.Tensor) -> torch.Tensor:
+ def forward(self, x: Tensor) -> Tensor:
return self.features(x)
diff --git a/kornia/feature/orientation.py b/kornia/feature/orientation.py
index 9d9eb0447..2456feb23 100644
--- a/kornia/feature/orientation.py
+++ b/kornia/feature/orientation.py
@@ -1,5 +1,5 @@
import math
-from typing import Callable, Dict, Optional
+from typing import Dict, Optional
import torch
import torch.nn as nn
@@ -9,6 +9,7 @@ from kornia.constants import pi
from kornia.filters import SpatialGradient, get_gaussian_kernel2d
from kornia.geometry import rad2deg
from kornia.testing import KORNIA_CHECK_LAF, KORNIA_CHECK_SHAPE
+from kornia.utils.helpers import map_location_to_cpu
from .laf import extract_patches_from_pyramid, get_laf_orientation, set_laf_orientation
@@ -165,8 +166,7 @@ class OriNet(nn.Module):
self.eps = eps
# use torch.hub to load pretrained model
if pretrained:
- storage_fcn: Callable = lambda storage, loc: storage
- pretrained_dict = torch.hub.load_state_dict_from_url(urls['orinet'], map_location=storage_fcn)
+ pretrained_dict = torch.hub.load_state_dict_from_url(urls['orinet'], map_location=map_location_to_cpu)
self.load_state_dict(pretrained_dict['state_dict'], strict=False)
self.eval()
diff --git a/kornia/feature/siftdesc.py b/kornia/feature/siftdesc.py
index 27235472e..df88383fb 100644
--- a/kornia/feature/siftdesc.py
+++ b/kornia/feature/siftdesc.py
@@ -32,7 +32,7 @@ def get_sift_pooling_kernel(ksize: int = 25) -> Tensor:
return kernel
-def get_sift_bin_ksize_stride_pad(patch_size: int, num_spatial_bins: int) -> Tuple:
+def get_sift_bin_ksize_stride_pad(patch_size: int, num_spatial_bins: int) -> Tuple[int, int, int]:
r"""Return a tuple with SIFT parameters.
Args:
diff --git a/kornia/feature/sold2/backbones.py b/kornia/feature/sold2/backbones.py
index 782e50433..a0640ce05 100644
--- a/kornia/feature/sold2/backbones.py
+++ b/kornia/feature/sold2/backbones.py
@@ -1,5 +1,5 @@
"""Implements several backbone networks."""
-from typing import Dict, List, Optional, Tuple, Type, Union
+from typing import Any, Dict, List, Optional, Tuple, Type, Union
import torch
import torch.nn as nn
@@ -379,7 +379,7 @@ class SOLD2Net(Module):
descriptors: semi-dense descriptors.
"""
- def __init__(self, model_cfg: Dict):
+ def __init__(self, model_cfg: Dict[str, Any]):
super().__init__()
self.cfg = model_cfg
diff --git a/kornia/feature/sold2/sold2.py b/kornia/feature/sold2/sold2.py
index 09a6906ce..bb92e241f 100644
--- a/kornia/feature/sold2/sold2.py
+++ b/kornia/feature/sold2/sold2.py
@@ -1,4 +1,4 @@
-from typing import Dict, Optional, Tuple
+from typing import Any, Dict, Optional, Tuple
import torch
import torch.nn.functional as F
@@ -15,7 +15,7 @@ urls: Dict[str, str] = {}
urls["wireframe"] = "http://cmp.felk.cvut.cz/~mishkdmy/models/sold2_wireframe.pth"
-default_cfg: Dict = {
+default_cfg: Dict[str, Any] = {
'backbone_cfg': {'input_channel': 1, 'depth': 4, 'num_stacks': 2, 'num_blocks': 1, 'num_classes': 5},
'use_descriptor': True,
'grid_size': 8,
@@ -75,7 +75,7 @@ class SOLD2(Module):
>>> matches = sold2.match(line_seg1, line_seg2, desc1[None], desc2[None])
"""
- def __init__(self, pretrained: bool = True, config: Optional[Dict] = None):
+ def __init__(self, pretrained: bool = True, config: Optional[Dict[str, Any]] = None):
super().__init__()
# Initialize some parameters
self.config = default_cfg if config is None else config
@@ -98,7 +98,7 @@ class SOLD2(Module):
# Initialize the line matcher
self.line_matcher = WunschLineMatcher(**self.config["line_matcher_cfg"])
- def forward(self, img: Tensor) -> Dict:
+ def forward(self, img: Tensor) -> Dict[str, Any]:
"""
Args:
img: batched images with shape :math:`(B, 1, H, W)`.
@@ -225,7 +225,7 @@ class WunschLineMatcher(Module):
return matches
- def sample_line_points(self, line_seg: Tensor) -> Tuple:
+ def sample_line_points(self, line_seg: Tensor) -> Tuple[Tensor, Tensor]:
"""Regularly sample points along each line segments, with a minimal distance between each point.
Pad the remaining points.
@@ -329,7 +329,7 @@ class WunschLineMatcher(Module):
return nw_grid[:, -1, -1]
-def keypoints_to_grid(keypoints: Tensor, img_size: tuple) -> Tensor:
+def keypoints_to_grid(keypoints: Tensor, img_size: Tuple[int, int]) -> Tensor:
"""Convert a list of keypoints into a grid in [-1, 1]² that can be used in torch.nn.functional.interpolate.
Args:
diff --git a/kornia/feature/sold2/sold2_detector.py b/kornia/feature/sold2/sold2_detector.py
index 9b98dd842..c4a3bfd7d 100644
--- a/kornia/feature/sold2/sold2_detector.py
+++ b/kornia/feature/sold2/sold2_detector.py
@@ -1,5 +1,5 @@
import math
-from typing import Dict, Optional, Tuple
+from typing import Any, Dict, Optional, Tuple
import torch
@@ -61,7 +61,7 @@ class SOLD2_detector(Module):
>>> line_segments = sold2_detector(img)["line_segments"]
"""
- def __init__(self, pretrained: bool = True, config: Optional[Dict] = None):
+ def __init__(self, pretrained: bool = True, config: Optional[Dict[str, Any]] = None):
super().__init__()
# Initialize some parameters
self.config = default_detector_cfg if config is None else config
@@ -91,7 +91,7 @@ class SOLD2_detector(Module):
del state_dict["heatmap_decoder.conv_block_lst.2.bias"]
return state_dict
- def forward(self, img: Tensor) -> Dict:
+ def forward(self, img: Tensor) -> Dict[str, Any]:
"""
Args:
img: batched images with shape :math:`(B, 1, H, W)`.
@@ -190,7 +190,7 @@ class LineSegmentDetectionModule:
if self.use_junction_refinement and self.junction_refine_cfg is None:
raise ValueError("[Error] Missing junction refinement config.")
- def detect(self, junctions: Tensor, heatmap: Tensor) -> Tuple:
+ def detect(self, junctions: Tensor, heatmap: Tensor) -> Tuple[Tensor, Tensor, Tensor]:
"""Main function performing line segment detection."""
KORNIA_CHECK_SHAPE(heatmap, ["H", "W"])
H, W = heatmap.shape
@@ -390,7 +390,7 @@ class LineSegmentDetectionModule:
def refine_junction_perturb(
self, junctions: Tensor, line_map: Tensor, heatmap: Tensor, H: int, W: int, device: torch.device
- ) -> Tuple:
+ ) -> Tuple[Tensor, Tensor]:
"""Refine the line endpoints in a similar way as in LSD."""
# Fetch refinement parameters
num_perturbs = self.junction_refine_cfg["num_perturbs"]
diff --git a/kornia/feature/sosnet.py b/kornia/feature/sosnet.py
index 5fe8d86ca..0be734ecc 100644
--- a/kornia/feature/sosnet.py
+++ b/kornia/feature/sosnet.py
@@ -1,9 +1,10 @@
-from typing import Callable, Dict
+from typing import Dict
import torch
import torch.nn as nn
from kornia.testing import KORNIA_CHECK_SHAPE
+from kornia.utils.helpers import map_location_to_cpu
urls: Dict[str, str] = {}
urls["lib"] = "https://github.com/yuruntian/SOSNet/raw/master/sosnet-weights/sosnet_32x32_liberty.pth"
@@ -59,8 +60,7 @@ class SOSNet(nn.Module):
self.desc_norm = nn.Sequential(nn.LocalResponseNorm(256, alpha=256.0, beta=0.5, k=0.0))
# load pretrained model
if pretrained:
- storage_fcn: Callable = lambda storage, loc: storage
- pretrained_dict = torch.hub.load_state_dict_from_url(urls['lib'], map_location=storage_fcn)
+ pretrained_dict = torch.hub.load_state_dict_from_url(urls['lib'], map_location=map_location_to_cpu)
self.load_state_dict(pretrained_dict, strict=True)
self.eval()
return
diff --git a/kornia/feature/tfeat.py b/kornia/feature/tfeat.py
index d6aed9bad..42c938ec9 100644
--- a/kornia/feature/tfeat.py
+++ b/kornia/feature/tfeat.py
@@ -1,9 +1,10 @@
-from typing import Callable, Dict
+from typing import Dict
import torch
import torch.nn as nn
from kornia.testing import KORNIA_CHECK_SHAPE
+from kornia.utils.helpers import map_location_to_cpu
urls: Dict[str, str] = {}
urls["liberty"] = "https://github.com/vbalnt/tfeat/raw/master/pretrained-models/tfeat-liberty.params" # pylint: disable
@@ -52,8 +53,7 @@ class TFeat(nn.Module):
self.descr = nn.Sequential(nn.Linear(64 * 8 * 8, 128), nn.Tanh())
# use torch.hub to load pretrained model
if pretrained:
- storage_fcn: Callable = lambda storage, loc: storage
- pretrained_dict = torch.hub.load_state_dict_from_url(urls['liberty'], map_location=storage_fcn)
+ pretrained_dict = torch.hub.load_state_dict_from_url(urls['liberty'], map_location=map_location_to_cpu)
self.load_state_dict(pretrained_dict, strict=True)
self.eval()
diff --git a/kornia/geometry/transform/crop2d.py b/kornia/geometry/transform/crop2d.py
index 92ba3705c..751351e7b 100644
--- a/kornia/geometry/transform/crop2d.py
+++ b/kornia/geometry/transform/crop2d.py
@@ -287,7 +287,7 @@ def crop_by_transform_mat(
def crop_by_indices(
input_tensor: Tensor,
src_box: Tensor,
- size: Optional[Tuple] = None,
+ size: Optional[Tuple[int, int]] = None,
interpolation: str = 'bilinear',
align_corners: Optional[bool] = None,
antialias: bool = False,
diff --git a/kornia/geometry/transform/image_registrator.py b/kornia/geometry/transform/image_registrator.py
index 488050869..9e098e1c3 100644
--- a/kornia/geometry/transform/image_registrator.py
+++ b/kornia/geometry/transform/image_registrator.py
@@ -5,6 +5,7 @@ import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
+from kornia.core import Tensor
from kornia.geometry.conversions import angle_to_rotation_matrix, convert_affinematrix_to_homography
from .homography_warper import HomographyWarper
@@ -29,7 +30,7 @@ class Homography(nn.Module):
"""Initializes the model with identity transform."""
torch.nn.init.eye_(self.model)
- def forward(self) -> torch.Tensor:
+ def forward(self) -> Tensor:
r"""Single-batch homography".
Returns:
@@ -37,7 +38,7 @@ class Homography(nn.Module):
"""
return torch.unsqueeze(self.model / self.model[2, 2], dim=0) # 1x3x3
- def forward_inverse(self) -> torch.Tensor:
+ def forward_inverse(self) -> Tensor:
r"""Interted Single-batch homography".
Returns:
@@ -82,7 +83,7 @@ class Similarity(nn.Module):
torch.nn.init.zeros_(self.shift)
torch.nn.init.ones_(self.scale)
- def forward(self) -> torch.Tensor:
+ def forward(self) -> Tensor:
r"""Single-batch similarity transform".
Returns:
@@ -92,7 +93,7 @@ class Similarity(nn.Module):
out = convert_affinematrix_to_homography(torch.cat([rot, self.shift], dim=2))
return out
- def forward_inverse(self) -> torch.Tensor:
+ def forward_inverse(self) -> Tensor:
r"""Single-batch inverse similarity transform".
Returns:
@@ -128,7 +129,7 @@ class ImageRegistrator(nn.Module):
self,
model_type='homography',
optimizer=optim.Adam,
- loss_fn: Callable = F.l1_loss,
+ loss_fn: Callable[..., Tensor] = F.l1_loss,
pyramid_levels: int = 5,
lr: float = 1e-3,
num_iterations: int = 100,
@@ -168,9 +169,7 @@ class ImageRegistrator(nn.Module):
self.num_iterations = num_iterations
self.tolerance = tolerance
- def get_single_level_loss(
- self, img_src: torch.Tensor, img_dst: torch.Tensor, transform_model: torch.Tensor
- ) -> torch.Tensor:
+ def get_single_level_loss(self, img_src: Tensor, img_dst: Tensor, transform_model: Tensor) -> Tensor:
"""Warp img_src into img_dst with transform_model and returns loss."""
# ToDo: Make possible registration of images of different shape
if img_src.shape != img_dst.shape:
@@ -192,12 +191,8 @@ class ImageRegistrator(nn.Module):
self.model.reset_model()
def register(
- self,
- src_img: torch.Tensor,
- dst_img: torch.Tensor,
- verbose: bool = False,
- output_intermediate_models: bool = False,
- ) -> Union[torch.Tensor, Tuple[torch.Tensor, List[torch.Tensor]]]:
+ self, src_img: Tensor, dst_img: Tensor, verbose: bool = False, output_intermediate_models: bool = False
+ ) -> Union[Tensor, Tuple[Tensor, List[Tensor]]]:
r"""Estimate the tranformation' which warps src_img into dst_img by gradient descent. The shape of the
tensors is not checked, because it may depend on the model, e.g. volume registration.
@@ -243,14 +238,14 @@ class ImageRegistrator(nn.Module):
return self.model(), aux_models
return self.model()
- def warp_src_into_dst(self, src_img: torch.Tensor) -> torch.Tensor:
+ def warp_src_into_dst(self, src_img: Tensor) -> Tensor:
r"""Warp src_img with estimated model."""
_height, _width = src_img.shape[-2:]
warper = self.warper(_height, _width)
img_src_to_dst = warper(src_img, self.model())
return img_src_to_dst
- def warp_dst_inro_src(self, dst_img: torch.Tensor) -> torch.Tensor:
+ def warp_dst_inro_src(self, dst_img: Tensor) -> Tensor:
r"""Warp src_img with inverted estimated model."""
_height, _width = dst_img.shape[-2:]
warper = self.warper(_height, _width)
diff --git a/kornia/geometry/transform/pyramid.py b/kornia/geometry/transform/pyramid.py
index 86c54be26..1e41218ea 100644
--- a/kornia/geometry/transform/pyramid.py
+++ b/kornia/geometry/transform/pyramid.py
@@ -186,7 +186,7 @@ class ScalePyramid(Module):
cur_level = x
return cur_level, cur_sigma, pixel_distance
- def forward(self, x: Tensor) -> Tuple[List, List, List]:
+ def forward(self, x: Tensor) -> Tuple[List[Tensor], List[Tensor], List[Tensor]]:
bs, _, _, _ = x.size()
cur_level, cur_sigma, pixel_distance = self.get_first_level(x)
diff --git a/kornia/grad_estimator/ste.py b/kornia/grad_estimator/ste.py
index 1317420c9..cebc3d2e8 100644
--- a/kornia/grad_estimator/ste.py
+++ b/kornia/grad_estimator/ste.py
@@ -105,7 +105,7 @@ class StraightThroughEstimator(nn.Module):
[0.0422, 0.0566, 0.0626, 0.0422]]]])
"""
- def __init__(self, target_fn: nn.Module, grad_fn: Optional[Callable] = None):
+ def __init__(self, target_fn: nn.Module, grad_fn: Optional[Callable[..., Any]] = None):
super().__init__()
self.target_fn = target_fn
self.grad_fn = grad_fn
diff --git a/kornia/losses/hausdorff.py b/kornia/losses/hausdorff.py
index eb90fce1b..b62a1a835 100644
--- a/kornia/losses/hausdorff.py
+++ b/kornia/losses/hausdorff.py
@@ -25,8 +25,8 @@ class _HausdorffERLossBase(torch.jit.ScriptModule):
Estimated Hausdorff Loss.
"""
- conv: Callable
- max_pool: Callable
+ conv: Callable[..., Tensor]
+ max_pool: Callable[..., Tensor]
def __init__(self, alpha: float = 2.0, k: int = 10, reduction: str = 'mean') -> None:
super().__init__()
diff --git a/kornia/metrics/mean_average_precision.py b/kornia/metrics/mean_average_precision.py
index 7f31144a1..f0f06e2e6 100644
--- a/kornia/metrics/mean_average_precision.py
+++ b/kornia/metrics/mean_average_precision.py
@@ -1,19 +1,21 @@
-from typing import List, Tuple
+from typing import Dict, List, Tuple
import torch
+from kornia.core import Tensor, concatenate, tensor, zeros
+
from .mean_iou import mean_iou_bbox
def mean_average_precision(
- pred_boxes: List[torch.Tensor],
- pred_labels: List[torch.Tensor],
- pred_scores: List[torch.Tensor],
- gt_boxes: List[torch.Tensor],
- gt_labels: List[torch.Tensor],
+ pred_boxes: List[Tensor],
+ pred_labels: List[Tensor],
+ pred_scores: List[Tensor],
+ gt_boxes: List[Tensor],
+ gt_labels: List[Tensor],
n_classes: int,
threshold: float = 0.5,
-) -> Tuple[torch.Tensor, dict]:
+) -> Tuple[Tensor, Dict[int, float]]:
"""Calculate the Mean Average Precision (mAP) of detected objects.
Code altered from https://github.com/sgrvinod/a-PyTorch-Tutorial-to-Object-Detection/blob/master/utils.py#L271.
@@ -46,9 +48,9 @@ def mean_average_precision(
for i, labels in enumerate(gt_labels):
gt_images.extend([i] * labels.size(0))
# (n_objects), n_objects is the total no. of objects across all images
- _gt_boxes = torch.cat(gt_boxes, dim=0) # (n_objects, 4)
- _gt_labels = torch.cat(gt_labels, dim=0) # (n_objects)
- _gt_images = torch.tensor(gt_images, device=_gt_boxes.device, dtype=torch.long)
+ _gt_boxes = concatenate(gt_boxes, 0) # (n_objects, 4)
+ _gt_labels = concatenate(gt_labels, 0) # (n_objects)
+ _gt_images = tensor(gt_images, device=_gt_boxes.device, dtype=torch.long)
if not _gt_images.size(0) == _gt_boxes.size(0) == _gt_labels.size(0):
raise AssertionError
@@ -57,18 +59,16 @@ def mean_average_precision(
pred_images = []
for i, labels in enumerate(pred_labels):
pred_images.extend([i] * labels.size(0))
- _pred_boxes = torch.cat(pred_boxes, dim=0) # (n_detections, 4)
- _pred_labels = torch.cat(pred_labels, dim=0) # (n_detections)
- _pred_scores = torch.cat(pred_scores, dim=0) # (n_detections)
- _pred_images = torch.tensor(pred_images, device=_pred_boxes.device, dtype=torch.long) # (n_detections)
+ _pred_boxes = concatenate(pred_boxes, 0) # (n_detections, 4)
+ _pred_labels = concatenate(pred_labels, 0) # (n_detections)
+ _pred_scores = concatenate(pred_scores, 0) # (n_detections)
+ _pred_images = tensor(pred_images, device=_pred_boxes.device, dtype=torch.long) # (n_detections)
if not _pred_images.size(0) == _pred_boxes.size(0) == _pred_labels.size(0) == _pred_scores.size(0):
raise AssertionError
# Calculate APs for each class (except background)
- average_precisions = torch.zeros(
- (n_classes - 1), device=_pred_boxes.device, dtype=_pred_boxes.dtype
- ) # (n_classes - 1)
+ average_precisions = zeros((n_classes - 1), device=_pred_boxes.device, dtype=_pred_boxes.dtype) # (n_classes - 1)
for c in range(1, n_classes):
# Extract only objects with this class
gt_class_images = _gt_images[_gt_labels == c] # (n_class_objects)
@@ -76,9 +76,7 @@ def mean_average_precision(
# Keep track of which true objects with this class have already been 'detected'
# (n_class_objects)
- gt_class_boxes_detected = torch.zeros(
- (gt_class_images.size(0)), dtype=torch.uint8, device=gt_class_images.device
- )
+ gt_class_boxes_detected = zeros((gt_class_images.size(0)), dtype=torch.uint8, device=gt_class_images.device)
# Extract only detections with this class
pred_class_images = _pred_images[_pred_labels == c] # (n_class_detections)
@@ -94,10 +92,10 @@ def mean_average_precision(
pred_class_boxes = pred_class_boxes[sort_ind] # (n_class_detections, 4)
# In the order of decreasing scores, check if true or false positive
- gt_positives = torch.zeros(
+ gt_positives = zeros(
(n_class_detections,), dtype=pred_class_boxes.dtype, device=pred_class_boxes.device
) # (n_class_detections)
- false_positives = torch.zeros(
+ false_positives = zeros(
(n_class_detections,), dtype=pred_class_boxes.dtype, device=pred_class_boxes.device
) # (n_class_detections)
for d in range(n_class_detections):
@@ -117,7 +115,7 @@ def mean_average_precision(
# 'ind' is the index of the object in these image-level tensors 'object_boxes', 'object_difficulties'
# In the original class-level tensors 'gt_class_boxes', etc., 'ind' corresponds to object with index...
- original_ind = torch.tensor(
+ original_ind = tensor(
range(gt_class_boxes.size(0)), device=gt_class_boxes_detected.device, dtype=torch.long
)[gt_class_images == this_image][ind]
# We need 'original_ind' to update 'gt_class_boxes_detected'
@@ -145,7 +143,7 @@ def mean_average_precision(
# Find the mean of the maximum of the precisions corresponding to recalls above the threshold 't'
recall_thresholds = torch.arange(start=0, end=1.1, step=0.1).tolist() # (11)
- precisions = torch.zeros((len(recall_thresholds)), device=_gt_boxes.device, dtype=_gt_boxes.dtype) # (11)
+ precisions = zeros((len(recall_thresholds)), device=_gt_boxes.device, dtype=_gt_boxes.dtype) # (11)
for i, t in enumerate(recall_thresholds):
recalls_above_t = cumul_recall >= t
if recalls_above_t.any():
@@ -158,6 +156,6 @@ def mean_average_precision(
mean_ap = average_precisions.mean()
# Keep class-wise average precisions in a dictionary
- ap_dict = {c + 1: v for c, v in enumerate(average_precisions.tolist())}
+ ap_dict = {c + 1: float(v) for c, v in enumerate(average_precisions.tolist())}
return mean_ap, ap_dict
diff --git a/kornia/nerf/data_utils.py b/kornia/nerf/data_utils.py
index b326f34db..2d06a513b 100755
--- a/kornia/nerf/data_utils.py
+++ b/kornia/nerf/data_utils.py
@@ -21,7 +21,7 @@ def _is_list_of_tensors(lst: Sequence[object]) -> TypeGuard[List[Tensor]]:
return isinstance(lst, list) and all(isinstance(x, Tensor) for x in lst)
-class RayDataset(Dataset):
+class RayDataset(Dataset[RayGroup]):
r"""Class to represent a dataset of rays.
Args:
@@ -153,7 +153,7 @@ class RayDataset(Dataset):
return origins, directions, rgbs
-def instantiate_ray_dataloader(dataset: RayDataset, batch_size: int = 1, shuffle: bool = True) -> DataLoader:
+def instantiate_ray_dataloader(dataset: RayDataset, batch_size: int = 1, shuffle: bool = True) -> DataLoader[RayGroup]:
r"""Initializes a dataloader to manage a ray dataset.
Args:
diff --git a/kornia/testing/__init__.py b/kornia/testing/__init__.py
index 3f6536ca8..44f65cad5 100644
--- a/kornia/testing/__init__.py
+++ b/kornia/testing/__init__.py
@@ -4,7 +4,7 @@ import math
from abc import ABC, abstractmethod
from copy import deepcopy
from itertools import product
-from typing import Any, Dict, List, Optional, Tuple, cast
+from typing import Any, Dict, List, Optional, Tuple, TypeVar, cast
import torch
from torch.testing import assert_close as _assert_close
@@ -66,8 +66,11 @@ def tensor_to_gradcheck_var(tensor, dtype=torch.float64, requires_grad=True):
return tensor.requires_grad_(requires_grad).type(dtype)
-def dict_to(data: dict, device: torch.device, dtype: torch.dtype) -> dict:
- out: dict = {}
+T = TypeVar('T')
+
+
+def dict_to(data: Dict[T, Any], device: torch.device, dtype: torch.dtype) -> Dict[T, Any]:
+ out: Dict[T, Any] = {}
for key, val in data.items():
out[key] = val.to(device, dtype) if isinstance(val, Tensor) else val
return out
diff --git a/kornia/utils/image.py b/kornia/utils/image.py
index 39e504b04..4cc989b15 100644
--- a/kornia/utils/image.py
+++ b/kornia/utils/image.py
@@ -1,14 +1,16 @@
from functools import wraps
-from typing import TYPE_CHECKING, Callable, List
+from typing import TYPE_CHECKING, Any, Callable, List
import torch
import torch.nn as nn
+from kornia.core import Tensor
+
if TYPE_CHECKING:
- import numpy as np
+ import numpy.typing as npt
-def image_to_tensor(image: "np.ndarray", keepdim: bool = True) -> torch.Tensor:
+def image_to_tensor(image: "npt.NDArray[Any]", keepdim: bool = True) -> Tensor:
"""Convert a numpy image to a PyTorch 4d tensor image.
Args:
@@ -38,7 +40,7 @@ def image_to_tensor(image: "np.ndarray", keepdim: bool = True) -> torch.Tensor:
raise ValueError("Input size must be a two, three or four dimensional array")
input_shape = image.shape
- tensor: torch.Tensor = torch.from_numpy(image)
+ tensor: Tensor = torch.from_numpy(image)
if len(input_shape) == 2:
# (H, W) -> (1, H, W)
@@ -56,7 +58,7 @@ def image_to_tensor(image: "np.ndarray", keepdim: bool = True) -> torch.Tensor:
return tensor.unsqueeze(0) if not keepdim else tensor
-def image_list_to_tensor(images: List["np.ndarray"]) -> torch.Tensor:
+def image_list_to_tensor(images: List["npt.NDArray[Any]"]) -> Tensor:
"""Converts a list of numpy images to a PyTorch 4d tensor image.
Args:
@@ -76,14 +78,14 @@ def image_list_to_tensor(images: List["np.ndarray"]) -> torch.Tensor:
if len(images[0].shape) != 3:
raise ValueError("Input images must be three dimensional arrays")
- list_of_tensors: List[torch.Tensor] = []
+ list_of_tensors: List[Tensor] = []
for image in images:
list_of_tensors.append(image_to_tensor(image))
- tensor: torch.Tensor = torch.stack(list_of_tensors)
+ tensor: Tensor = torch.stack(list_of_tensors)
return tensor
-def _to_bchw(tensor: torch.Tensor) -> torch.Tensor:
+def _to_bchw(tensor: Tensor) -> Tensor:
"""Convert a PyTorch tensor image to BCHW format.
Args:
@@ -92,8 +94,8 @@ def _to_bchw(tensor: torch.Tensor) -> torch.Tensor:
Returns:
input tensor of the form :math:`(B, C, H, W)`.
"""
- if not isinstance(tensor, torch.Tensor):
- raise TypeError(f"Input type is not a torch.Tensor. Got {type(tensor)}")
+ if not isinstance(tensor, Tensor):
+ raise TypeError(f"Input type is not a Tensor. Got {type(tensor)}")
if len(tensor.shape) < 2:
raise ValueError(f"Input size must be a two, three or four dimensional tensor. Got {tensor.shape}")
@@ -110,7 +112,7 @@ def _to_bchw(tensor: torch.Tensor) -> torch.Tensor:
return tensor
-def _to_bcdhw(tensor: torch.Tensor) -> torch.Tensor:
+def _to_bcdhw(tensor: Tensor) -> Tensor:
"""Convert a PyTorch tensor image to BCDHW format.
Args:
@@ -119,8 +121,8 @@ def _to_bcdhw(tensor: torch.Tensor) -> torch.Tensor:
Returns:
input tensor of the form :math:`(B, C, D, H, W)`.
"""
- if not isinstance(tensor, torch.Tensor):
- raise TypeError(f"Input type is not a torch.Tensor. Got {type(tensor)}")
+ if not isinstance(tensor, Tensor):
+ raise TypeError(f"Input type is not a Tensor. Got {type(tensor)}")
if len(tensor.shape) < 3:
raise ValueError(f"Input size must be a three, four or five dimensional tensor. Got {tensor.shape}")
@@ -137,7 +139,7 @@ def _to_bcdhw(tensor: torch.Tensor) -> torch.Tensor:
return tensor
-def tensor_to_image(tensor: torch.Tensor, keepdim: bool = False) -> "np.ndarray":
+def tensor_to_image(tensor: Tensor, keepdim: bool = False) -> "npt.NDArray[Any]":
"""Converts a PyTorch tensor image to a numpy image.
In case the tensor is in the GPU, it will be copied back to CPU.
@@ -160,14 +162,14 @@ def tensor_to_image(tensor: torch.Tensor, keepdim: bool = False) -> "np.ndarray"
>>> tensor_to_image(img).shape
(4, 4, 3)
"""
- if not isinstance(tensor, torch.Tensor):
- raise TypeError(f"Input type is not a torch.Tensor. Got {type(tensor)}")
+ if not isinstance(tensor, Tensor):
+ raise TypeError(f"Input type is not a Tensor. Got {type(tensor)}")
if len(tensor.shape) > 4 or len(tensor.shape) < 2:
raise ValueError("Input size must be a two, three or four dimensional tensor")
input_shape = tensor.shape
- image: "np.ndarray" = tensor.cpu().detach().numpy()
+ image: "npt.NDArray[Any]" = tensor.cpu().detach().numpy()
if len(input_shape) == 2:
# (H, W) -> (H, W)
@@ -203,11 +205,11 @@ class ImageToTensor(nn.Module):
super().__init__()
self.keepdim = keepdim
- def forward(self, x: "np.ndarray") -> torch.Tensor:
+ def forward(self, x: "npt.NDArray[Any]") -> Tensor:
return image_to_tensor(x, keepdim=self.keepdim)
-def perform_keep_shape_image(f: Callable) -> Callable:
+def perform_keep_shape_image(f: Callable[..., Tensor]) -> Callable[..., Tensor]:
"""A decorator that enable `f` to be applied to an image of arbitrary leading dimensions `(*, C, H, W)`.
It works by first viewing the image as `(B, C, H, W)`, applying the function and re-viewing the image as original
@@ -215,16 +217,16 @@ def perform_keep_shape_image(f: Callable) -> Callable:
"""
@wraps(f)
- def _wrapper(input: torch.Tensor, *args, **kwargs):
- if not isinstance(input, torch.Tensor):
- raise TypeError(f"Input input type is not a torch.Tensor. Got {type(input)}")
+ def _wrapper(input: Tensor, *args, **kwargs) -> Tensor:
+ if not isinstance(input, Tensor):
+ raise TypeError(f"Input input type is not a Tensor. Got {type(input)}")
if input.numel() == 0:
raise ValueError("Invalid input tensor, it is empty.")
input_shape = input.shape
input = _to_bchw(input) # view input as (B, C, H, W)
- output: torch.Tensor = f(input, *args, **kwargs)
+ output = f(input, *args, **kwargs)
if len(input_shape) == 3:
output = output[0]
@@ -239,7 +241,7 @@ def perform_keep_shape_image(f: Callable) -> Callable:
return _wrapper
-def perform_keep_shape_video(f: Callable) -> Callable:
+def perform_keep_shape_video(f: Callable[..., Tensor]) -> Callable[..., Tensor]:
"""A decorator that enable `f` to be applied to an image of arbitrary leading dimensions `(*, C, D, H, W)`.
It works by first viewing the image as `(B, C, D, H, W)`, applying the function and re-viewing the image as original
@@ -247,16 +249,16 @@ def perform_keep_shape_video(f: Callable) -> Callable:
"""
@wraps(f)
- def _wrapper(input: torch.Tensor, *args, **kwargs):
- if not isinstance(input, torch.Tensor):
- raise TypeError(f"Input input type is not a torch.Tensor. Got {type(input)}")
+ def _wrapper(input: Tensor, *args, **kwargs) -> Tensor:
+ if not isinstance(input, Tensor):
+ raise TypeError(f"Input input type is not a Tensor. Got {type(input)}")
if input.numel() == 0:
raise ValueError("Invalid input tensor, it is empty.")
input_shape = input.shape
input = _to_bcdhw(input) # view input as (B, C, D, H, W)
- output: torch.Tensor = f(input, *args, **kwargs)
+ output = f(input, *args, **kwargs)
if len(input_shape) == 4:
output = output[0]
diff --git a/kornia/x/callbacks.py b/kornia/x/callbacks.py
index cd21f94f2..00182497f 100644
--- a/kornia/x/callbacks.py
+++ b/kornia/x/callbacks.py
@@ -84,7 +84,7 @@ class ModelCheckpoint:
)
"""
- def __init__(self, filepath: str, monitor: str, filename_fcn: Optional[Callable] = None) -> None:
+ def __init__(self, filepath: str, monitor: str, filename_fcn: Optional[Callable[..., str]] = None) -> None:
self.filepath = filepath
self.monitor = monitor
self._filename_fcn = filename_fcn or default_filename_fcn
diff --git a/kornia/x/trainer.py b/kornia/x/trainer.py
index d76fe3183..3626d94c3 100644
--- a/kornia/x/trainer.py
+++ b/kornia/x/trainer.py
@@ -1,10 +1,10 @@
import logging
-from typing import Callable, Dict, Optional
+from typing import Any, Callable, Dict, Optional
# the accelerator library is a requirement for the Trainer
# but it is optional for grousnd base user of kornia.
import torch
-import torch.nn as nn
+from torch.optim import Optimizer, lr_scheduler
from torch.utils.data import DataLoader
try:
@@ -12,6 +12,7 @@ try:
except ImportError:
Accelerator = None
+from kornia.core import Module, Tensor
from kornia.metrics import AverageMeter
from .utils import Configuration, StatsTracker, TrainerState
@@ -61,14 +62,14 @@ class Trainer:
def __init__(
self,
- model: nn.Module,
- train_dataloader: DataLoader,
- valid_dataloader: DataLoader,
- criterion: Optional[nn.Module],
- optimizer: torch.optim.Optimizer,
- scheduler: torch.optim.lr_scheduler.CosineAnnealingLR,
+ model: Module,
+ train_dataloader: DataLoader[Any],
+ valid_dataloader: DataLoader[Any],
+ criterion: Optional[Module],
+ optimizer: Optimizer,
+ scheduler: lr_scheduler.CosineAnnealingLR,
config: Configuration,
- callbacks: Dict[str, Callable] = {},
+ callbacks: Dict[str, Callable[..., None]] = {},
) -> None:
# setup the accelerator
if Accelerator is None:
@@ -101,7 +102,7 @@ class Trainer:
def device(self) -> torch.device:
return self.accelerator.device
- def backward(self, loss: torch.Tensor) -> None:
+ def backward(self, loss: Tensor) -> None:
self.accelerator.backward(loss)
def fit_epoch(self, epoch: int) -> None:
@@ -159,7 +160,7 @@ class Trainer:
# events stubs
@torch.no_grad()
- def evaluate(self) -> dict:
+ def evaluate(self) -> Dict[str, AverageMeter]:
self.model.eval()
stats = StatsTracker()
for sample_id, sample in enumerate(self.valid_dataloader):
@@ -187,28 +188,28 @@ class Trainer:
def on_epoch_start(self, *args, **kwargs):
...
- def preprocess(self, x: dict) -> dict:
+ def preprocess(self, x: Dict[str, Tensor]) -> Dict[str, Tensor]:
return x
- def augmentations(self, x: dict) -> dict:
+ def augmentations(self, x: Dict[str, Tensor]) -> Dict[str, Tensor]:
return x
- def compute_metrics(self, *args: torch.Tensor) -> Dict[str, float]:
+ def compute_metrics(self, *args: Tensor) -> Dict[str, float]:
"""Compute metrics during the evaluation."""
return {}
- def compute_loss(self, *args: torch.Tensor) -> torch.Tensor:
+ def compute_loss(self, *args: Tensor) -> Tensor:
if self.criterion is None:
raise RuntimeError("`criterion` should not be None.")
return self.criterion(*args)
- def on_before_model(self, x: dict) -> dict:
+ def on_before_model(self, x: Dict[str, Tensor]) -> Dict[str, Tensor]:
return x
- def on_model(self, model, sample: dict):
+ def on_model(self, model, sample: Dict[str, Tensor]):
return model(sample["input"])
- def on_after_model(self, output: torch.Tensor, sample: dict):
+ def on_after_model(self, output: Tensor, sample: Dict[str, Tensor]):
...
def on_checkpoint(self, *args, **kwargs):
diff --git a/kornia/x/trainers.py b/kornia/x/trainers.py
index d1f75ea22..d6991b94f 100644
--- a/kornia/x/trainers.py
+++ b/kornia/x/trainers.py
@@ -1,9 +1,9 @@
-from typing import Callable, Dict, Optional
+from typing import Any, Callable, Dict, Optional
-import torch
-import torch.nn as nn
+from torch.optim import Optimizer, lr_scheduler
from torch.utils.data import DataLoader
+from kornia.core import Module, Tensor, stack
from kornia.metrics import accuracy, mean_average_precision, mean_iou
from .trainer import Trainer
@@ -22,7 +22,7 @@ class ImageClassifierTrainer(Trainer):
`example <https://github.com/kornia/kornia/blob/master/examples/train/image_classifier/>`__.
"""
- def compute_metrics(self, *args: torch.Tensor) -> Dict[str, float]:
+ def compute_metrics(self, *args: Tensor) -> Dict[str, float]:
if len(args) != 2:
raise AssertionError
out, target = args
@@ -41,7 +41,7 @@ class SemanticSegmentationTrainer(Trainer):
`example <https://github.com/kornia/kornia/blob/master/examples/train/semantic_segmentation/>`__.
"""
- def compute_metrics(self, *args: torch.Tensor) -> Dict[str, float]:
+ def compute_metrics(self, *args: Tensor) -> Dict[str, float]:
if len(args) != 2:
raise AssertionError
out, target = args
@@ -62,15 +62,15 @@ class ObjectDetectionTrainer(Trainer):
def __init__(
self,
- model: nn.Module,
- train_dataloader: DataLoader,
- valid_dataloader: DataLoader,
- criterion: Optional[nn.Module],
- optimizer: torch.optim.Optimizer,
- scheduler: torch.optim.lr_scheduler.CosineAnnealingLR,
+ model: Module,
+ train_dataloader: DataLoader[Any],
+ valid_dataloader: DataLoader[Any],
+ criterion: Optional[Module],
+ optimizer: Optimizer,
+ scheduler: lr_scheduler.CosineAnnealingLR,
config: Configuration,
num_classes: int,
- callbacks: Optional[Dict[str, Callable]] = None,
+ callbacks: Optional[Dict[str, Callable[..., None]]] = None,
loss_computed_by_model: Optional[bool] = None,
) -> None:
if callbacks is None:
@@ -80,22 +80,22 @@ class ObjectDetectionTrainer(Trainer):
self.loss_computed_by_model = loss_computed_by_model
self.num_classes = num_classes
- def on_model(self, model: nn.Module, sample: dict):
+ def on_model(self, model: Module, sample: Dict[str, Tensor]):
if self.loss_computed_by_model and model.training:
return model(sample["input"], sample["target"])
return model(sample["input"])
- def compute_loss(self, *args: torch.Tensor) -> torch.Tensor:
+ def compute_loss(self, *args: Tensor) -> Tensor:
if self.loss_computed_by_model:
# Note: in case of dict losses obtained
if isinstance(args[0], dict):
- return torch.stack([v for _, v in args[0].items()]).mean()
- return torch.stack(list(args[0])).sum()
+ return stack([v for _, v in args[0].items()]).mean()
+ return stack(list(args[0])).sum()
if self.criterion is None:
raise RuntimeError("`criterion` should not be None if `loss_computed_by_model` is False.")
return self.criterion(*args)
- def compute_metrics(self, *args: torch.Tensor) -> Dict[str, float]:
+ def compute_metrics(self, *args: Tensor) -> Dict[str, float]:
if (
isinstance(args[0], dict)
and "boxes" in args[0]
diff --git a/kornia/x/utils.py b/kornia/x/utils.py
index 54d108555..ef00276ff 100644
--- a/kornia/x/utils.py
+++ b/kornia/x/utils.py
@@ -1,6 +1,6 @@
from dataclasses import dataclass, field
from enum import Enum
-from typing import Dict
+from typing import Dict, Tuple
from kornia.core import Module
from kornia.metrics.average_meter import AverageMeter
@@ -23,7 +23,7 @@ class Configuration:
num_epochs: int = field(default=1, metadata={"help": "The number of epochs to run the training."})
lr: float = field(default=1e-3, metadata={"help": "The learning rate to be used for the optimize."})
output_path: str = field(default="./output", metadata={"help": "The output data directory."})
- image_size: tuple = field(default=(224, 224), metadata={"help": "The input image size."})
+ image_size: Tuple[int, int] = field(default=(224, 224), metadata={"help": "The input image size."})
# TODO: possibly remove because hydra already do this
# def __init__(self, **entries):
diff --git a/setup.cfg b/setup.cfg
index 0069bec85..718f31e5e 100644
--- a/setup.cfg
+++ b/setup.cfg
@@ -120,6 +120,7 @@ ignore =
files = kornia/
pretty = True
check_untyped_defs = True
+disallow_any_generics = True
show_error_codes = True
ignore_missing_imports = True
no_implicit_optional = True