Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

Enable `disallow_untyped_defs` on mypy (#2252)

João Gustavo A. Amorim41ecb64f760c
diff --git a/kornia/augmentation/_2d/intensity/random_rain.py b/kornia/augmentation/_2d/intensity/random_rain.py
index d3573868f..a849ced03 100644
--- a/kornia/augmentation/_2d/intensity/random_rain.py
+++ b/kornia/augmentation/_2d/intensity/random_rain.py
@@ -42,7 +42,7 @@ class RandomRain(IntensityAugmentationBase2D):
number_of_drops: tuple[int, int] = (1000, 2000),
drop_height: tuple[int, int] = (5, 20),
drop_width: tuple[int, int] = (-5, 5),
- ):
+ ) -> None:
super().__init__(p=p, same_on_batch=same_on_batch, p_batch=1.0, keepdim=keepdim)
self._param_generator = RainGenerator(number_of_drops, drop_height, drop_width)
diff --git a/kornia/augmentation/_2d/mix/base.py b/kornia/augmentation/_2d/mix/base.py
index 467f87a21..c6b4933af 100644
--- a/kornia/augmentation/_2d/mix/base.py
+++ b/kornia/augmentation/_2d/mix/base.py
@@ -187,9 +187,9 @@ class MixAugmentationBaseV2(_BasicAugmentationBase):
return outputs
@torch.jit.ignore
- def inverse(self, **kwargs):
+ def inverse(self, **kwargs: Any) -> Optional[Tensor]:
raise RuntimeError(f"Inverse for {self.__class__.__name__} is not supported.")
@property
- def transform_matrix(self):
+ def transform_matrix(self) -> Optional[Tensor]:
raise RuntimeError(f"Transformation matrices for {self.__class__.__name__} is not supported.")
diff --git a/kornia/augmentation/auto/operations/ops.py b/kornia/augmentation/auto/operations/ops.py
index 2b87a7317..eb625f05e 100644
--- a/kornia/augmentation/auto/operations/ops.py
+++ b/kornia/augmentation/auto/operations/ops.py
@@ -38,7 +38,9 @@ class AutoContrast(OperationBase):
symmetric_megnitude: if to randomly assign the magnitude as negative or not.
"""
- def __init__(self, initial_probability: float = 0.5, temperature: float = 0.1, symmetric_megnitude: bool = False):
+ def __init__(
+ self, initial_probability: float = 0.5, temperature: float = 0.1, symmetric_megnitude: bool = False
+ ) -> None:
super().__init__(
K.RandomAutoContrast(same_on_batch=False, p=initial_probability),
initial_magnitude=None,
@@ -66,7 +68,7 @@ class Brightness(OperationBase):
magnitude_range: Tuple[float, float] = (0.2, 1.8),
temperature: float = 0.1,
symmetric_megnitude: bool = False,
- ):
+ ) -> None:
super().__init__(
K.RandomBrightness(magnitude_range, same_on_batch=False, p=initial_probability),
initial_magnitude=[("brightness_factor", initial_magnitude)],
@@ -94,7 +96,7 @@ class Contrast(OperationBase):
magnitude_range: Tuple[float, float] = (0.2, 1.8),
temperature: float = 0.1,
symmetric_megnitude: bool = False,
- ):
+ ) -> None:
super().__init__(
K.RandomContrast(magnitude_range, same_on_batch=False, p=initial_probability),
initial_magnitude=[("contrast_factor", initial_magnitude)],
@@ -122,7 +124,7 @@ class Hue(OperationBase):
magnitude_range: Tuple[float, float] = (-0.5, 0.5),
temperature: float = 0.1,
symmetric_megnitude: bool = False,
- ):
+ ) -> None:
super().__init__(
K.RandomHue(magnitude_range, same_on_batch=False, p=initial_probability),
initial_magnitude=[("hue_factor", initial_magnitude)],
@@ -150,7 +152,7 @@ class Saturate(OperationBase):
magnitude_range: Tuple[float, float] = (0.2, 1.8),
temperature: float = 0.1,
symmetric_megnitude: bool = False,
- ):
+ ) -> None:
super().__init__(
K.RandomSaturation(magnitude_range, same_on_batch=False, p=initial_probability),
initial_magnitude=[("saturation_factor", initial_magnitude)],
@@ -175,7 +177,7 @@ class Equalize(OperationBase):
STE gradient estimator applied for back propagation.
"""
- def __init__(self, initial_probability: float = 0.5, temperature: float = 0.1):
+ def __init__(self, initial_probability: float = 0.5, temperature: float = 0.1) -> None:
super().__init__(
K.RandomEqualize(same_on_batch=False, p=initial_probability),
initial_magnitude=None,
@@ -194,7 +196,7 @@ class Gray(OperationBase):
temperature: temperature for RelaxedBernoulli distribution used during training.
"""
- def __init__(self, initial_probability: float = 0.5, temperature: float = 0.1):
+ def __init__(self, initial_probability: float = 0.5, temperature: float = 0.1) -> None:
super().__init__(
K.RandomGrayscale(same_on_batch=False, p=initial_probability),
initial_magnitude=None,
@@ -212,7 +214,7 @@ class Invert(OperationBase):
temperature: temperature for RelaxedBernoulli distribution used during training.
"""
- def __init__(self, initial_probability: float = 0.5, temperature: float = 0.1):
+ def __init__(self, initial_probability: float = 0.5, temperature: float = 0.1) -> None:
super().__init__(
K.RandomInvert(same_on_batch=False, p=initial_probability),
initial_magnitude=None,
@@ -247,7 +249,7 @@ class Posterize(OperationBase):
magnitude_range: Tuple[float, float] = (1.0, 8.0),
temperature: float = 0.1,
symmetric_megnitude: bool = False,
- ):
+ ) -> None:
super().__init__(
K.RandomPosterize(magnitude_range, same_on_batch=False, p=initial_probability),
initial_magnitude=[("bits_factor", initial_magnitude)],
@@ -280,7 +282,7 @@ class Solarize(OperationBase):
magnitude_range: Tuple[float, float] = (0.0, 1.0),
temperature: float = 0.1,
symmetric_megnitude: bool = False,
- ):
+ ) -> None:
super().__init__(
K.RandomSolarize(magnitude_range, additions=0.0, same_on_batch=False, p=initial_probability),
initial_magnitude=[("thresholds", initial_magnitude)],
@@ -312,7 +314,7 @@ class SolarizeAdd(OperationBase):
magnitude_range: Tuple[float, float] = (-0.3, 0.3),
temperature: float = 0.1,
symmetric_megnitude: bool = False,
- ):
+ ) -> None:
super().__init__(
K.RandomSolarize(thresholds=0.5, additions=magnitude_range, same_on_batch=False, p=initial_probability),
initial_magnitude=[("additions", initial_magnitude)],
@@ -341,7 +343,7 @@ class Sharpness(OperationBase):
magnitude_range: Tuple[float, float] = (0.1, 1.9),
temperature: float = 0.1,
symmetric_megnitude: bool = False,
- ):
+ ) -> None:
super().__init__(
K.RandomSharpness(magnitude_range, same_on_batch=False, p=initial_probability),
initial_magnitude=[("sharpness", initial_magnitude)],
@@ -359,7 +361,7 @@ class HorizontalFlip(OperationBase):
temperature: temperature for RelaxedBernoulli distribution used during training.
"""
- def __init__(self, initial_probability: float = 0.5, temperature: float = 0.1):
+ def __init__(self, initial_probability: float = 0.5, temperature: float = 0.1) -> None:
super().__init__(
K.RandomHorizontalFlip(same_on_batch=False, p=initial_probability),
initial_magnitude=None,
@@ -376,7 +378,7 @@ class VerticalFlip(OperationBase):
temperature: temperature for RelaxedBernoulli distribution used during training.
"""
- def __init__(self, initial_probability: float = 0.5, temperature: float = 0.1):
+ def __init__(self, initial_probability: float = 0.5, temperature: float = 0.1) -> None:
super().__init__(
K.RandomVerticalFlip(same_on_batch=False, p=initial_probability),
initial_magnitude=None,
@@ -404,7 +406,7 @@ class Rotate(OperationBase):
magnitude_range: Tuple[float, float] = (0.0, 30.0),
temperature: float = 0.1,
symmetric_megnitude: bool = True,
- ):
+ ) -> None:
if symmetric_megnitude and magnitude_range[0] < 0:
raise ValueError(
f"Lower bound of {self.__class__.__name__} is a symmetric operation. "
@@ -442,7 +444,7 @@ class ShearX(OperationBase):
magnitude_range: Tuple[float, float] = (0.0, 0.3),
temperature: float = 0.1,
symmetric_megnitude: bool = True,
- ):
+ ) -> None:
if symmetric_megnitude and magnitude_range[0] < 0:
raise ValueError(
f"Lower bound of {self.__class__.__name__} is a symmetric operation. "
@@ -481,7 +483,7 @@ class ShearY(OperationBase):
magnitude_range: Tuple[float, float] = (0.0, 0.3),
temperature: float = 0.1,
symmetric_megnitude: bool = True,
- ):
+ ) -> None:
if symmetric_megnitude and magnitude_range[0] < 0:
raise ValueError(
f"Lower bound of {self.__class__.__name__} is a symmetric operation. "
@@ -517,7 +519,7 @@ class TranslateX(OperationBase):
magnitude_range: Tuple[float, float] = (0.0, 0.5),
temperature: float = 0.1,
symmetric_megnitude: bool = True,
- ):
+ ) -> None:
if symmetric_megnitude and magnitude_range[0] < 0:
raise ValueError(
f"Lower bound of {self.__class__.__name__} is a symmetric operation. "
@@ -550,7 +552,7 @@ class TranslateY(OperationBase):
magnitude_range: Tuple[float, float] = (0.0, 0.5),
temperature: float = 0.1,
symmetric_megnitude: bool = True,
- ):
+ ) -> None:
if symmetric_megnitude and magnitude_range[0] < 0:
raise ValueError(
f"Lower bound of {self.__class__.__name__} is a symmetric operation. "
diff --git a/kornia/augmentation/container/ops.py b/kornia/augmentation/container/ops.py
index 912f48750..febb73ee5 100644
--- a/kornia/augmentation/container/ops.py
+++ b/kornia/augmentation/container/ops.py
@@ -1,6 +1,8 @@
from abc import ABCMeta, abstractmethod
from typing import Any, Callable, Dict, Generic, List, Optional, Type, TypeVar, Union
+from typing_extensions import ParamSpec
+
import kornia.augmentation as K
from kornia.augmentation.base import _AugmentationBase
from kornia.constants import DataKey
@@ -128,12 +130,14 @@ class AugmentationSequentialOps:
return outputs
-def make_input_only_sequential(module: 'K.container.ImageSequentialBase') -> Callable[..., Tensor]:
+P = ParamSpec('P')
+
+
+def make_input_only_sequential(module: 'K.container.ImageSequentialBase') -> Callable[P, Tensor]:
"""Disable all other additional inputs (e.g. ) for ImageSequential."""
- def f(*args, **kwargs):
- out = module(*args, **kwargs)
- return out
+ def f(*args: P.args, **kwargs: P.kwargs) -> Tensor:
+ return module(*args, **kwargs)
return f
diff --git a/kornia/augmentation/random_generator/base.py b/kornia/augmentation/random_generator/base.py
index 6f4d2cb04..a7f0dbee3 100644
--- a/kornia/augmentation/random_generator/base.py
+++ b/kornia/augmentation/random_generator/base.py
@@ -1,15 +1,17 @@
-from typing import Callable, Dict, Optional, Tuple
+from typing import Any, Callable, Dict, Optional, Tuple, Type, TypeVar
import torch
from torch.distributions import Distribution
from kornia.core import Device, Module, Tensor
+T = TypeVar('T')
+
class _PostInitInjectionMetaClass(type):
"""To inject the ``__post_init__`` function after the creation of each instance."""
- def __call__(cls, *args, **kwargs):
+ def __call__(cls: Type[T], *args: Any, **kwargs: Any) -> T:
obj = type.__call__(cls, *args, **kwargs)
obj.__post_init__()
return obj
@@ -41,7 +43,7 @@ class RandomGeneratorBase(Module, metaclass=_PostInitInjectionMetaClass):
self.dtype = dtype
# TODO: refine the logic with module.to()
- def to(self, *args, **kwargs):
+ def to(self, *args: Any, **kwargs: Any) -> 'RandomGeneratorBase':
device, dtype, non_blocking, convert_to_format = torch._C._nn._parse_to(*args, **kwargs)
self.set_rng_device_and_dtype(device=device, dtype=dtype)
return self
@@ -100,7 +102,7 @@ class DistributionWithMapper(Distribution):
out = self.map_fn(out)
return out
- def __getattr__(self, attr):
+ def __getattr__(self, attr: str) -> Any:
try:
return getattr(self, attr)
except AttributeError:
diff --git a/kornia/color/colormap.py b/kornia/color/colormap.py
index 9b08432a4..0d402eb29 100644
--- a/kornia/color/colormap.py
+++ b/kornia/color/colormap.py
@@ -26,7 +26,7 @@ class ColorMap(ABC):
num_colors: int,
device: Optional[torch.device],
dtype: Optional[torch.dtype],
- ):
+ ) -> None:
self._dtype = dtype
self._device = device
@@ -118,7 +118,7 @@ class AUTUMN(ColorMap):
def __init__(
self, num_colors: int = 64, device: Optional[torch.device] = None, dtype: Optional[torch.dtype] = None
- ):
+ ) -> None:
super().__init__(base_colormap=_BASE_AUTUMN, num_colors=num_colors, device=device, dtype=dtype)
diff --git a/kornia/constants.py b/kornia/constants.py
index 81a10ade7..d46853074 100644
--- a/kornia/constants.py
+++ b/kornia/constants.py
@@ -27,7 +27,7 @@ class _KORNIA_EnumMeta(EnumMeta):
return any(val == other for val in self)
- def __repr__(self):
+ def __repr__(self) -> str:
return ' | '.join(f"{self.__name__}.{val.name}" for val in self)
diff --git a/kornia/contrib/distance_transform.py b/kornia/contrib/distance_transform.py
index 5ff641c4b..b16b2a20f 100644
--- a/kornia/contrib/distance_transform.py
+++ b/kornia/contrib/distance_transform.py
@@ -79,7 +79,7 @@ class DistanceTransform(nn.Module):
h: value that influence the approximation of the min function.
"""
- def __init__(self, kernel_size: int = 3, h: float = 0.35):
+ def __init__(self, kernel_size: int = 3, h: float = 0.35) -> None:
super().__init__()
self.kernel_size = kernel_size
self.h = h
diff --git a/kornia/contrib/face_detection.py b/kornia/contrib/face_detection.py
index b7054cfa9..104cbf47e 100644
--- a/kornia/contrib/face_detection.py
+++ b/kornia/contrib/face_detection.py
@@ -228,7 +228,7 @@ class FaceDetector(nn.Module):
class ConvDPUnit(nn.Sequential):
- def __init__(self, in_channels, out_channels, withBNRelu=True):
+ def __init__(self, in_channels: int, out_channels: int, withBNRelu: bool = True) -> None:
super().__init__()
self.add_module("conv1", nn.Conv2d(in_channels, out_channels, 1, 1, 0, bias=True, groups=1))
self.add_module("conv2", nn.Conv2d(out_channels, out_channels, 3, 1, 1, bias=True, groups=out_channels))
diff --git a/kornia/contrib/vit.py b/kornia/contrib/vit.py
index e56aa75fe..ee9cd89e6 100644
--- a/kornia/contrib/vit.py
+++ b/kornia/contrib/vit.py
@@ -212,7 +212,7 @@ class VisionTransformer(Module):
self.encoder = TransformerEncoder(hidden_dim, depth, num_heads, dropout_rate, dropout_attn)
@property
- def encoder_results(self):
+ def encoder_results(self) -> List[Tensor]:
return self.encoder.results
def forward(self, x: torch.Tensor) -> torch.Tensor:
diff --git a/kornia/core/tensor_wrapper.py b/kornia/core/tensor_wrapper.py
index 232c63dda..5a6e37c80 100644
--- a/kornia/core/tensor_wrapper.py
+++ b/kornia/core/tensor_wrapper.py
@@ -1,3 +1,4 @@
+# type: ignore
# pytorch tensor wrapper class
# insipired by:
# https://github.com/pytorch/pytorch/blob/591dfffa38848de54b7f5f4e49260847024c9281/test/test_overrides.py#L748
@@ -6,12 +7,10 @@ import collections
import torch
from torch import Tensor
-# wrap inputs if necessary
# TODO: promote to KORNIA_WRAP
-
-
def wrap(v, cls):
+ # wrap inputs if necessary
if type(v) in {tuple, list}:
return type(v)(wrap(vi, cls) for vi in v)
@@ -19,8 +18,6 @@ def wrap(v, cls):
# TODO: promote to KORNIA_UNWRAP
-
-
def unwrap(v):
if type(v) in {tuple, list}:
return type(v)(unwrap(vi) for vi in v)
@@ -69,14 +66,14 @@ class TensorWrapper:
return wrap(val, type(self))
- def __setattr__(self, name, value):
+ def __setattr__(self, name, value) -> None:
if name in self.__dict__:
self.__dict__[name] = value
self.used_attrs.add(name)
setattr(self._data, name, value)
- def __setitem__(self, key, value):
+ def __setitem__(self, key, value) -> None:
self._data[key] = value
def __getitem__(self, key):
@@ -144,10 +141,10 @@ class TensorWrapper:
def __ne__(self, other):
return self.__unary_op__(torch.ne, other)
- def __bool__(self):
+ def __bool__(self) -> bool:
return self.__unary_op__(Tensor.__bool__)
- def __int__(self):
+ def __int__(self) -> int:
return self.__unary_op__(Tensor.__int__)
def __neg__(self):
@@ -157,5 +154,5 @@ class TensorWrapper:
args = (self, other) if other is not None else (self,)
return self.__torch_function__(func, (type(self),), args)
- def __len__(self):
+ def __len__(self) -> int:
return len(self._data)
diff --git a/kornia/enhance/adjust.py b/kornia/enhance/adjust.py
index 95b8b0ed7..625ea38ba 100644
--- a/kornia/enhance/adjust.py
+++ b/kornia/enhance/adjust.py
@@ -867,7 +867,7 @@ def _blend_one(input1: Tensor, input2: Tensor, factor: Tensor) -> Tensor:
return torch.clamp(res, 0, 1)
-def _build_lut(histo, step):
+def _build_lut(histo: Tensor, step: Tensor) -> Tensor:
# Compute the cumulative sum, shifting by step // 2
# and then normalization by step.
step_trunc = torch.div(step, 2, rounding_mode='trunc')
diff --git a/kornia/enhance/normalize.py b/kornia/enhance/normalize.py
index 0a00046b5..7306b8929 100644
--- a/kornia/enhance/normalize.py
+++ b/kornia/enhance/normalize.py
@@ -63,7 +63,7 @@ class Normalize(nn.Module):
def forward(self, input: torch.Tensor) -> torch.Tensor:
return normalize(input, self.mean, self.std)
- def __repr__(self):
+ def __repr__(self) -> str:
repr = f"(mean={self.mean}, std={self.std})"
return self.__class__.__name__ + repr
@@ -165,7 +165,7 @@ class Denormalize(nn.Module):
def forward(self, input: torch.Tensor) -> torch.Tensor:
return denormalize(input, self.mean, self.std)
- def __repr__(self):
+ def __repr__(self) -> str:
repr = f"(mean={self.mean}, std={self.std})"
return self.__class__.__name__ + repr
diff --git a/kornia/feature/adalam/adalam.py b/kornia/feature/adalam/adalam.py
index e5e1971f0..8b0f0f2af 100644
--- a/kornia/feature/adalam/adalam.py
+++ b/kornia/feature/adalam/adalam.py
@@ -95,7 +95,7 @@ def match_adalam(
class AdalamFilter:
- def __init__(self, custom_config: Optional[AdalamConfig] = None):
+ def __init__(self, custom_config: Optional[AdalamConfig] = None) -> None:
"""This class acts as a wrapper to the method AdaLAM for outlier filtering.
init args:
diff --git a/kornia/feature/adalam/ransac.py b/kornia/feature/adalam/ransac.py
index cc2d62e0f..30298a40c 100644
--- a/kornia/feature/adalam/ransac.py
+++ b/kornia/feature/adalam/ransac.py
@@ -1,4 +1,4 @@
-from typing import Any, Dict, Tuple
+from typing import Any, Dict, Tuple, Union
import torch
@@ -7,7 +7,7 @@ from kornia.core import Tensor
from .utils import arange_sequence, batch_2x2_ellipse, batch_2x2_inv, draw_first_k_couples, piecewise_arange
-def stable_sort_residuals(residuals, ransidx):
+def stable_sort_residuals(residuals: Tensor, ransidx: Tensor) -> Tuple[Tensor, Tensor]:
logres = torch.log(residuals + 1e-10)
minlogres = torch.min(logres)
maxlogres = torch.max(logres)
@@ -21,7 +21,9 @@ def stable_sort_residuals(residuals, ransidx):
return residuals[iters_range.unsqueeze(-1), sorting_idxes], sorting_idxes
-def group_sum_and_cumsum(scores_mat, end_group_idx, group_idx=None):
+def group_sum_and_cumsum(
+ scores_mat: Tensor, end_group_idx: Tensor, group_idx: Union[Tensor, slice, None] = None
+) -> Tuple[Tensor, Union[Tensor, None]]:
cumulative_scores = torch.cumsum(scores_mat, dim=1)
ending_cumusums = cumulative_scores[:, end_group_idx]
shifted_ending_cumusums = torch.cat(
@@ -39,7 +41,9 @@ def group_sum_and_cumsum(scores_mat, end_group_idx, group_idx=None):
return grouped_sums, None
-def confidence_based_inlier_selection(residuals, ransidx, rdims, idxoffsets, dv, min_confidence):
+def confidence_based_inlier_selection(
+ residuals: Tensor, ransidx: Tensor, rdims: Tensor, idxoffsets: Tensor, dv: torch.device, min_confidence: Tensor
+) -> Tuple[Tensor, Tensor, Tensor, Tensor, Tensor]:
numransacs = rdims.shape[0]
numiters = residuals.shape[0]
@@ -58,6 +62,9 @@ def confidence_based_inlier_selection(residuals, ransidx, rdims, idxoffsets, dv,
inlier_weights[too_perfect_fits] = 0.0
balanced_rdims, weights_cumsums = group_sum_and_cumsum(inlier_weights, end_rans_indexing, ransidx)
+ if not isinstance(weights_cumsums, Tensor):
+ raise TypeError('Expected the `weights_cumsums` to be a Tensor!')
+
progressive_inl_rates = weights_cumsums.float() / (balanced_rdims.repeat_interleave(rdims, dim=1)).float()
good_inl_mask = (sorted_res_sqr * min_confidence <= progressive_inl_rates) | too_perfect_fits
diff --git a/kornia/feature/adalam/utils.py b/kornia/feature/adalam/utils.py
index 3322e79ba..4b7afc7ce 100644
--- a/kornia/feature/adalam/utils.py
+++ b/kornia/feature/adalam/utils.py
@@ -1,4 +1,5 @@
import math
+from typing import Tuple
import torch
@@ -55,7 +56,7 @@ def piecewise_arange(piecewise_idxer: Tensor) -> Tensor:
return ranges[tmp]
-def batch_2x2_inv(m, check_dets=False):
+def batch_2x2_inv(m: Tensor, check_dets: bool = False) -> Tensor:
a = m[..., 0, 0]
b = m[..., 0, 1]
c = m[..., 1, 0]
@@ -71,15 +72,15 @@ def batch_2x2_inv(m, check_dets=False):
return minv / det.unsqueeze(-1).unsqueeze(-1)
-def batch_2x2_Q(m):
+def batch_2x2_Q(m: Tensor) -> Tensor:
return batch_2x2_inv(batch_2x2_invQ(m), check_dets=True)
-def batch_2x2_invQ(m):
+def batch_2x2_invQ(m: Tensor) -> Tensor:
return m @ m.transpose(-1, -2)
-def batch_2x2_det(m):
+def batch_2x2_det(m: Tensor) -> Tensor:
a = m[..., 0, 0]
b = m[..., 0, 1]
c = m[..., 1, 0]
@@ -87,7 +88,7 @@ def batch_2x2_det(m):
return a * d - b * c
-def batch_2x2_ellipse(m):
+def batch_2x2_ellipse(m: Tensor) -> Tuple[Tensor, Tensor]:
am = m[..., 0, 0]
bm = m[..., 0, 1]
cm = m[..., 1, 0]
@@ -130,7 +131,7 @@ def draw_first_k_couples(k: int, rdims: Tensor, dv: torch.device) -> Tensor:
return torch.remainder(idx_sequence.unsqueeze(-1), rdims)
-def random_samples_indices(iters, rdims, dv):
+def random_samples_indices(iters: int, rdims: Tensor, dv: torch.device) -> Tensor:
rands = torch.rand(size=(iters, 2, rdims.shape[0]), device=dv)
scaled_rands = rands * (rdims - 1e-8).float()
rand_samples_rel = scaled_rands.long()
diff --git a/kornia/feature/affine_shape.py b/kornia/feature/affine_shape.py
index 57b6fc20c..4bb63242a 100644
--- a/kornia/feature/affine_shape.py
+++ b/kornia/feature/affine_shape.py
@@ -34,7 +34,7 @@ class PatchAffineShapeEstimator(nn.Module):
eps: for safe division.
"""
- def __init__(self, patch_size: int = 19, eps: float = 1e-10):
+ def __init__(self, patch_size: int = 19, eps: float = 1e-10) -> None:
super().__init__()
self.patch_size: int = patch_size
self.gradient: nn.Module = SpatialGradient('sobel', 1)
@@ -42,7 +42,7 @@ class PatchAffineShapeEstimator(nn.Module):
sigma: float = float(self.patch_size) / math.sqrt(2.0)
self.weighting: torch.Tensor = get_gaussian_kernel2d((self.patch_size, self.patch_size), (sigma, sigma), True)
- def __repr__(self):
+ def __repr__(self) -> str:
return f"{self.__class__.__name__}(patch_size={self.patch_size}, eps={self.eps})"
def forward(self, patch: torch.Tensor) -> torch.Tensor:
@@ -111,7 +111,7 @@ class LAFAffineShapeEstimator(nn.Module):
stacklevel=2,
)
- def __repr__(self):
+ def __repr__(self) -> str:
return (
f'{self.__class__.__name__}'
f'(patch_size={self.patch_size}, '
@@ -160,7 +160,7 @@ class LAFAffNetShapeEstimator(nn.Module):
pretrained: Download and set pretrained weights to the model.
"""
- def __init__(self, pretrained: bool = False, preserve_orientation: bool = True):
+ def __init__(self, pretrained: bool = False, preserve_orientation: bool = True) -> None:
super().__init__()
self.features = nn.Sequential(
nn.Conv2d(1, 16, kernel_size=3, padding=1, bias=False),
diff --git a/kornia/feature/defmo.py b/kornia/feature/defmo.py
index 736e0e7a7..4aeac4fc1 100644
--- a/kornia/feature/defmo.py
+++ b/kornia/feature/defmo.py
@@ -206,7 +206,7 @@ class ResNet(Module):
class EncoderDeFMO(Module):
- def __init__(self):
+ def __init__(self) -> None:
super().__init__()
model = ResNet(Bottleneck, [3, 4, 6, 3]) # ResNet50
modelc1 = nn.Sequential(*list(model.children())[:3])
@@ -219,7 +219,7 @@ class EncoderDeFMO(Module):
class RenderingDeFMO(Module):
- def __init__(self):
+ def __init__(self) -> None:
super().__init__()
self.tsr_steps: int = 24
model = nn.Sequential(
diff --git a/kornia/feature/disk/_unets/blocks.py b/kornia/feature/disk/_unets/blocks.py
index ee0a434ce..5452331d1 100644
--- a/kornia/feature/disk/_unets/blocks.py
+++ b/kornia/feature/disk/_unets/blocks.py
@@ -1,3 +1,7 @@
+from __future__ import annotations
+
+from typing import Any
+
import torch
import torch.nn.functional as F
from torch import nn
@@ -6,18 +10,17 @@ from kornia.core import Module, Tensor
class TrivialUpsample(Module):
- def forward(self, x):
- r = F.interpolate(x, scale_factor=2, mode='bilinear', align_corners=False)
- return r
+ def forward(self, x: Tensor) -> Tensor:
+ return F.interpolate(x, scale_factor=2, mode='bilinear', align_corners=False)
class TrivialDownsample(Module):
- def forward(self, x):
+ def forward(self, x: Tensor) -> Tensor:
return F.avg_pool2d(x, 2)
class Conv(nn.Sequential):
- def __init__(self, in_, out_, size, skip_norm_and_gate=False):
+ def __init__(self, in_: int, out_: int, size: int, skip_norm_and_gate: bool = False) -> None:
norm: Module
nonl: Module
@@ -35,7 +38,7 @@ class Conv(nn.Sequential):
class ThinUnetDownBlock(nn.Sequential):
- def __init__(self, in_, out_, size=5, is_first=False, setup=None):
+ def __init__(self, in_: int, out_: int, size: int = 5, is_first: bool = False, setup: Any = None) -> None:
self.in_ = in_
self.out_ = out_
@@ -51,7 +54,7 @@ class ThinUnetDownBlock(nn.Sequential):
class ThinUnetUpBlock(Module):
- def __init__(self, bottom_, horizontal_, out_, size=5, setup=None):
+ def __init__(self, bottom_: int, horizontal_: int, out_: int, size: int = 5, setup: Any = None) -> None:
super().__init__()
self.bottom_ = bottom_
diff --git a/kornia/feature/disk/_unets/unet.py b/kornia/feature/disk/_unets/unet.py
index 1492154d2..a9af25d4f 100644
--- a/kornia/feature/disk/_unets/unet.py
+++ b/kornia/feature/disk/_unets/unet.py
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
from torch import nn
from kornia.core import Module, Tensor
@@ -6,7 +8,7 @@ from .blocks import ThinUnetDownBlock, ThinUnetUpBlock
class Unet(Module):
- def __init__(self, in_features=1, up=None, down=None, size=5):
+ def __init__(self, in_features: int = 1, up: list[int] = [], down: list[int] = [], size: int = 5) -> None:
super().__init__()
if not len(down) == len(up) + 1:
diff --git a/kornia/feature/disk/disk.py b/kornia/feature/disk/disk.py
index bc6b598db..0880f3712 100644
--- a/kornia/feature/disk/disk.py
+++ b/kornia/feature/disk/disk.py
@@ -28,7 +28,7 @@ class DISK(Module):
>>> features = disk(images)
"""
- def __init__(self, desc_dim=128, unet=None):
+ def __init__(self, desc_dim: int = 128, unet: None | Module = None) -> None:
super().__init__()
self.desc_dim = desc_dim
diff --git a/kornia/feature/disk/structs.py b/kornia/feature/disk/structs.py
index f7b9bd1a9..8f625e89a 100644
--- a/kornia/feature/disk/structs.py
+++ b/kornia/feature/disk/structs.py
@@ -5,7 +5,7 @@ from typing import Any
import torch.nn.functional as F
-from kornia.core import Tensor
+from kornia.core import Device, Tensor
@dataclass
@@ -25,11 +25,11 @@ class DISKFeatures:
detection_scores: Tensor
@property
- def n(self):
+ def n(self) -> int:
return self.keypoints.shape[0]
@property
- def device(self):
+ def device(self) -> Device:
return self.keypoints.device
@property
diff --git a/kornia/feature/hardnet.py b/kornia/feature/hardnet.py
index 2b75b923d..1fd9c6d7b 100644
--- a/kornia/feature/hardnet.py
+++ b/kornia/feature/hardnet.py
@@ -115,7 +115,7 @@ class HardNet8(nn.Module):
"""
patch_size = 32
- def __init__(self, pretrained: bool = False):
+ def __init__(self, pretrained: bool = False) -> None:
super().__init__()
self.features = nn.Sequential(
nn.Conv2d(1, 32, kernel_size=3, padding=1, bias=False),
@@ -154,7 +154,7 @@ class HardNet8(nn.Module):
self.eval()
@staticmethod
- def weights_init(m):
+ def weights_init(m: object) -> None:
if isinstance(m, nn.Conv2d):
nn.init.orthogonal_(m.weight.data, gain=0.6)
if m.bias is not None:
diff --git a/kornia/feature/hynet.py b/kornia/feature/hynet.py
index 4e4210977..a30f85726 100644
--- a/kornia/feature/hynet.py
+++ b/kornia/feature/hynet.py
@@ -49,7 +49,7 @@ class FilterResponseNorm2d(Module):
is_bias: bool = True,
is_scale: bool = True,
is_eps_leanable: bool = False,
- ):
+ ) -> None:
super().__init__()
self.num_features = num_features
@@ -66,13 +66,13 @@ class FilterResponseNorm2d(Module):
self.register_buffer('eps', tensor([eps]))
self.reset_parameters()
- def reset_parameters(self):
+ def reset_parameters(self) -> None:
nn.init.ones_(self.weight)
nn.init.zeros_(self.bias)
if self.is_eps_leanable:
nn.init.constant_(self.eps, self.init_eps)
- def extra_repr(self):
+ def extra_repr(self) -> str:
return 'num_features={num_features}, eps={init_eps}'.format(**self.__dict__)
def forward(self, x: Tensor) -> Tensor:
@@ -108,18 +108,18 @@ class TLU(Module):
- Output: :math:`(B, \text{num_features}, H, W)`
"""
- def __init__(self, num_features: int):
+ def __init__(self, num_features: int) -> None:
"""max(y, tau) = max(y - tau, 0) + tau = ReLU(y - tau) + tau"""
super().__init__()
self.num_features = num_features
self.tau = Parameter(-torch.ones(1, num_features, 1, 1), requires_grad=True)
self.reset_parameters()
- def reset_parameters(self):
+ def reset_parameters(self) -> None:
# nn.init.zeros_(self.tau)
nn.init.constant_(self.tau, -1)
- def extra_repr(self):
+ def extra_repr(self) -> str:
return 'num_features={num_features}'.format(**self.__dict__)
def forward(self, x: Tensor) -> Tensor:
@@ -163,7 +163,7 @@ class HyNet(Module):
dim_desc: int = 128,
drop_rate: float = 0.3,
eps_l2_norm: float = 1e-10,
- ):
+ ) -> None:
super().__init__()
self.eps_l2_norm = eps_l2_norm
self.dim_desc = dim_desc
diff --git a/kornia/feature/integrated.py b/kornia/feature/integrated.py
index eda7662f8..b874530e0 100644
--- a/kornia/feature/integrated.py
+++ b/kornia/feature/integrated.py
@@ -154,7 +154,7 @@ class SIFTFeature(LocalFeature):
rootsift: bool = True,
device: Device = torch.device('cpu'),
config: Detector_config = get_default_detector_config(),
- ):
+ ) -> None:
patch_size: int = 41
detector = MultiResolutionDetector(
BlobDoGSingle(1.0, 1.6),
@@ -182,7 +182,7 @@ class SIFTFeatureScaleSpace(LocalFeature):
upright: bool = False,
rootsift: bool = True,
device: Device = torch.device('cpu'),
- ):
+ ) -> None:
patch_size: int = 41
detector = ScaleSpaceDetector(
num_features,
@@ -209,7 +209,7 @@ class GFTTAffNetHardNet(LocalFeature):
upright: bool = False,
device: Device = torch.device('cpu'),
config: Detector_config = get_default_detector_config(),
- ):
+ ) -> None:
detector = MultiResolutionDetector(
CornerGFTT(),
num_features,
@@ -230,7 +230,7 @@ class HesAffNetHardNet(LocalFeature):
upright: bool = False,
device: Device = torch.device('cpu'),
config: Detector_config = get_default_detector_config(),
- ):
+ ) -> None:
detector = MultiResolutionDetector(
BlobHessian(),
num_features,
@@ -251,7 +251,7 @@ class KeyNetHardNet(LocalFeature):
upright: bool = False,
device: Device = torch.device('cpu'),
scale_laf: float = 1.0,
- ):
+ ) -> None:
ori_module = PassLAF() if upright else LAFOrienter(angle_detector=OriNet(True))
detector = KeyNetDetector(True, num_features=num_features, ori_module=ori_module).to(device)
descriptor = LAFDescriptor(None, patch_size=32, grayscale_descriptor=True).to(device)
@@ -270,7 +270,7 @@ class KeyNetAffNetHardNet(LocalFeature):
upright: bool = False,
device: Device = torch.device('cpu'),
scale_laf: float = 1.0,
- ):
+ ) -> None:
ori_module = PassLAF() if upright else LAFOrienter(angle_detector=OriNet(True))
detector = KeyNetDetector(
True, num_features=num_features, ori_module=ori_module, aff_module=LAFAffNetShapeEstimator(True).eval()
diff --git a/kornia/feature/keynet.py b/kornia/feature/keynet.py
index 69137019e..ded908ff9 100644
--- a/kornia/feature/keynet.py
+++ b/kornia/feature/keynet.py
@@ -38,7 +38,7 @@ class _FeatureExtractor(Module):
It loads both, the handcrafted and learnable blocks
"""
- def __init__(self):
+ def __init__(self) -> None:
super().__init__()
self.hc_block = _HandcraftedBlock()
@@ -53,7 +53,7 @@ class _FeatureExtractor(Module):
class _HandcraftedBlock(Module):
"""Helper class for KeyNet, it defines the handcrafted filters within the Key.Net handcrafted block."""
- def __init__(self):
+ def __init__(self) -> None:
super().__init__()
self.spatial_gradient = SpatialGradient('sobel', 1)
@@ -78,7 +78,7 @@ class _LearnableBlock(nn.Sequential):
It defines the learnable blocks within the Key.Net
"""
- def __init__(self, in_channels: int = 10):
+ def __init__(self, in_channels: int = 10) -> None:
super().__init__()
self.conv0 = _KeyNetConvBlock(in_channels)
@@ -128,7 +128,7 @@ class KeyNet(Module):
- Output: :math:`(B, 1, H, W)`
"""
- def __init__(self, pretrained: bool = False, keynet_conf: KeyNet_conf = keynet_default_config):
+ def __init__(self, pretrained: bool = False, keynet_conf: KeyNet_conf = keynet_default_config) -> None:
super().__init__()
num_filters = keynet_conf['num_filters']
@@ -190,6 +190,6 @@ class KeyNetDetector(MultiResolutionDetector):
keynet_conf: KeyNet_conf = keynet_default_config,
ori_module: Optional[Module] = None,
aff_module: Optional[Module] = None,
- ):
+ ) -> None:
model = KeyNet(pretrained, keynet_conf)
super().__init__(model, num_features, keynet_conf['Detector_conf'], ori_module, aff_module)
diff --git a/kornia/feature/loftr/__init__.py b/kornia/feature/loftr/__init__.py
index 59a4f95e7..90ff3e51d 100644
--- a/kornia/feature/loftr/__init__.py
+++ b/kornia/feature/loftr/__init__.py
@@ -1 +1,3 @@
+from __future__ import annotations
+
from .loftr import LoFTR
diff --git a/kornia/feature/loftr/backbone/__init__.py b/kornia/feature/loftr/backbone/__init__.py
index b6e731b3f..dbfd9e515 100644
--- a/kornia/feature/loftr/backbone/__init__.py
+++ b/kornia/feature/loftr/backbone/__init__.py
@@ -1,11 +1,15 @@
+from __future__ import annotations
+
+from typing import Any
+
from .resnet_fpn import ResNetFPN_8_2, ResNetFPN_16_4
-def build_backbone(config):
+def build_backbone(config: dict[str, Any]) -> ResNetFPN_8_2 | ResNetFPN_16_4:
if config['backbone_type'] == 'ResNetFPN':
if config['resolution'] == (8, 2):
return ResNetFPN_8_2(config['resnetfpn'])
elif config['resolution'] == (16, 4):
return ResNetFPN_16_4(config['resnetfpn'])
- else:
- raise ValueError(f"LOFTR.BACKBONE_TYPE {config['backbone_type']} not supported.")
+
+ raise ValueError(f"LOFTR.BACKBONE_TYPE {config['backbone_type']} with res {config['resolution']} not supported.")
diff --git a/kornia/feature/loftr/backbone/resnet_fpn.py b/kornia/feature/loftr/backbone/resnet_fpn.py
index e1cfec90c..79e140718 100644
--- a/kornia/feature/loftr/backbone/resnet_fpn.py
+++ b/kornia/feature/loftr/backbone/resnet_fpn.py
@@ -1,19 +1,23 @@
+from typing import Any, Dict, List, Type, Union
+
import torch.nn.functional as F
from torch import nn
+from kornia.core import Module, Tensor
+
-def conv1x1(in_planes, out_planes, stride=1):
+def conv1x1(in_planes: int, out_planes: int, stride: int = 1) -> nn.Conv2d:
"""1x1 convolution without padding."""
return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, padding=0, bias=False)
-def conv3x3(in_planes, out_planes, stride=1):
+def conv3x3(in_planes: int, out_planes: int, stride: int = 1) -> nn.Conv2d:
"""3x3 convolution with padding."""
return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=False)
-class BasicBlock(nn.Module):
- def __init__(self, in_planes, planes, stride=1):
+class BasicBlock(Module):
+ def __init__(self, in_planes: int, planes: int, stride: int = 1) -> None:
super().__init__()
self.conv1 = conv3x3(in_planes, planes, stride)
self.conv2 = conv3x3(planes, planes)
@@ -26,7 +30,7 @@ class BasicBlock(nn.Module):
else:
self.downsample = nn.Sequential(conv1x1(in_planes, planes, stride=stride), nn.BatchNorm2d(planes))
- def forward(self, x):
+ def forward(self, x: Tensor) -> Tensor:
y = x
y = self.relu(self.bn1(self.conv1(y)))
y = self.bn2(self.conv2(y))
@@ -43,7 +47,7 @@ class ResNetFPN_8_2(nn.Module):
Each block has 2 layers.
"""
- def __init__(self, config):
+ def __init__(self, config: Dict[str, Any]) -> None:
super().__init__()
# Config
block = BasicBlock
@@ -86,7 +90,7 @@ class ResNetFPN_8_2(nn.Module):
nn.init.constant_(m.weight, 1)
nn.init.constant_(m.bias, 0)
- def _make_layer(self, block, dim, stride=1):
+ def _make_layer(self, block: Union[Type[BasicBlock], Module], dim: int, stride: int = 1) -> nn.Sequential:
layer1 = block(self.in_planes, dim, stride=stride)
layer2 = block(dim, dim, stride=1)
layers = (layer1, layer2)
@@ -94,7 +98,7 @@ class ResNetFPN_8_2(nn.Module):
self.in_planes = dim
return nn.Sequential(*layers)
- def forward(self, x):
+ def forward(self, x: Tensor) -> List[Tensor]:
# ResNet Backbone
x0 = self.relu(self.bn1(self.conv1(x)))
x1 = self.layer1(x0) # 1/2
@@ -121,7 +125,7 @@ class ResNetFPN_16_4(nn.Module):
Each block has 2 layers.
"""
- def __init__(self, config):
+ def __init__(self, config: Dict[str, Any]) -> None:
super().__init__()
# Config
block = BasicBlock
@@ -166,7 +170,7 @@ class ResNetFPN_16_4(nn.Module):
nn.init.constant_(m.weight, 1)
nn.init.constant_(m.bias, 0)
- def _make_layer(self, block, dim, stride=1):
+ def _make_layer(self, block: Union[Type[BasicBlock], Module], dim: int, stride: int = 1) -> nn.Sequential:
layer1 = block(self.in_planes, dim, stride=stride)
layer2 = block(dim, dim, stride=1)
layers = (layer1, layer2)
@@ -174,7 +178,7 @@ class ResNetFPN_16_4(nn.Module):
self.in_planes = dim
return nn.Sequential(*layers)
- def forward(self, x):
+ def forward(self, x: Tensor) -> List[Tensor]:
# ResNet Backbone
x0 = self.relu(self.bn1(self.conv1(x)))
x1 = self.layer1(x0) # 1/2
diff --git a/kornia/feature/loftr/loftr.py b/kornia/feature/loftr/loftr.py
index ed8fb6ba7..5dc19dddb 100644
--- a/kornia/feature/loftr/loftr.py
+++ b/kornia/feature/loftr/loftr.py
@@ -1,4 +1,6 @@
-from typing import Any, Dict, Optional, Union
+from __future__ import annotations
+
+from typing import Any
import torch
@@ -12,7 +14,7 @@ from .utils.coarse_matching import CoarseMatching
from .utils.fine_matching import FineMatching
from .utils.position_encoding import PositionEncodingSine
-urls: Dict[str, str] = {}
+urls: dict[str, str] = {}
urls["outdoor"] = "http://cmp.felk.cvut.cz/~mishkdmy/models/loftr_outdoor.ckpt"
urls["indoor_new"] = "http://cmp.felk.cvut.cz/~mishkdmy/models/loftr_indoor_ds_new.ckpt"
urls["indoor"] = "http://cmp.felk.cvut.cz/~mishkdmy/models/loftr_indoor.ckpt"
@@ -74,7 +76,7 @@ class LoFTR(Module):
>>> out = loftr(input)
"""
- def __init__(self, pretrained: Optional[str] = 'outdoor', config: Dict[str, Any] = default_cfg):
+ def __init__(self, pretrained: str | None = 'outdoor', config: dict[str, Any] = default_cfg) -> None:
super().__init__()
# Misc
self.config = config
@@ -99,7 +101,7 @@ class LoFTR(Module):
self.load_state_dict(pretrained_dict['state_dict'])
self.eval()
- def forward(self, data: Dict[str, Tensor]) -> Dict[str, Tensor]:
+ def forward(self, data: dict[str, Tensor]) -> dict[str, Tensor]:
"""
Args:
data: dictionary containing the input data in the following format:
@@ -117,7 +119,7 @@ class LoFTR(Module):
- ``batch_indexes``, batch indexes for the keypoints and lafs :math:`(NC)`.
"""
# 1. Local Feature CNN
- _data: Dict[str, Union[Tensor, int, torch.Size]] = {
+ _data: dict[str, Tensor | int | torch.Size] = {
'bs': data['image0'].size(0),
'hw0_i': data['image0'].shape[2:],
'hw1_i': data['image1'].shape[2:],
@@ -169,13 +171,13 @@ class LoFTR(Module):
# 5. match fine-level
self.fine_matching(feat_f0_unfold, feat_f1_unfold, _data)
- rename_keys: Dict[str, str] = {
+ rename_keys: dict[str, str] = {
"mkpts0_f": 'keypoints0',
"mkpts1_f": 'keypoints1',
"mconf": 'confidence',
"b_ids": 'batch_indexes',
}
- out: Dict[str, Tensor] = {}
+ out: dict[str, Tensor] = {}
for k, v in rename_keys.items():
_d = _data[k]
if isinstance(_d, Tensor):
@@ -184,7 +186,7 @@ class LoFTR(Module):
raise TypeError(f'Expected Tensor for item `{k}`. Gotcha {type(_d)}')
return out
- def load_state_dict(self, state_dict, *args, **kwargs):
+ def load_state_dict(self, state_dict: dict[str, Any], *args: Any, **kwargs: Any) -> Any: # type: ignore[override]
for k in list(state_dict.keys()):
if k.startswith('matcher.'):
state_dict[k.replace('matcher.', '', 1)] = state_dict.pop(k)
diff --git a/kornia/feature/loftr/loftr_module/fine_preprocess.py b/kornia/feature/loftr/loftr_module/fine_preprocess.py
index 42fe10d06..e0ab06702 100644
--- a/kornia/feature/loftr/loftr_module/fine_preprocess.py
+++ b/kornia/feature/loftr/loftr_module/fine_preprocess.py
@@ -1,10 +1,14 @@
+from typing import Any, Dict, Tuple
+
import torch
import torch.nn.functional as F
from torch import nn
+from kornia.core import Module, Tensor
+
-class FinePreprocess(nn.Module):
- def __init__(self, config):
+class FinePreprocess(Module):
+ def __init__(self, config: Dict[str, Any]) -> None:
super().__init__()
self.config = config
@@ -20,12 +24,14 @@ class FinePreprocess(nn.Module):
self._reset_parameters()
- def _reset_parameters(self):
+ def _reset_parameters(self) -> None:
for p in self.parameters():
if p.dim() > 1:
nn.init.kaiming_normal_(p, mode="fan_out", nonlinearity="relu")
- def forward(self, feat_f0, feat_f1, feat_c0, feat_c1, data):
+ def forward(
+ self, feat_f0: Tensor, feat_f1: Tensor, feat_c0: Tensor, feat_c1: Tensor, data: Dict[str, Any]
+ ) -> Tuple[Tensor, Tensor]:
W = self.W
stride = data['hw0_f'][0] // data['hw0_c'][0]
diff --git a/kornia/feature/loftr/loftr_module/linear_attention.py b/kornia/feature/loftr/loftr_module/linear_attention.py
index c5ed6dc74..c9122a7bc 100644
--- a/kornia/feature/loftr/loftr_module/linear_attention.py
+++ b/kornia/feature/loftr/loftr_module/linear_attention.py
@@ -5,27 +5,29 @@ transformers/blob/master/fast_transformers/attention/linear_attention.py."""
from typing import Optional
import torch
-from torch.nn import Dropout, Module
+from torch.nn import Dropout
+from kornia.core import Module, Tensor
-def elu_feature_map(x):
+
+def elu_feature_map(x: Tensor) -> Tensor:
return torch.nn.functional.elu(x) + 1
class LinearAttention(Module):
- def __init__(self, eps=1e-6):
+ def __init__(self, eps: float = 1e-6) -> None:
super().__init__()
self.feature_map = elu_feature_map
self.eps = eps
def forward(
self,
- queries: torch.Tensor,
- keys: torch.Tensor,
- values: torch.Tensor,
- q_mask: Optional[torch.Tensor] = None,
- kv_mask: Optional[torch.Tensor] = None,
- ) -> torch.Tensor:
+ queries: Tensor,
+ keys: Tensor,
+ values: Tensor,
+ q_mask: Optional[Tensor] = None,
+ kv_mask: Optional[Tensor] = None,
+ ) -> Tensor:
"""Multi-Head linear attention proposed in "Transformers are RNNs"
Args:
queries: [N, L, H, D]
@@ -56,12 +58,19 @@ class LinearAttention(Module):
class FullAttention(Module):
- def __init__(self, use_dropout=False, attention_dropout=0.1):
+ def __init__(self, use_dropout: bool = False, attention_dropout: float = 0.1) -> None:
super().__init__()
self.use_dropout = use_dropout
self.dropout = Dropout(attention_dropout)
- def forward(self, queries, keys, values, q_mask=None, kv_mask=None):
+ def forward(
+ self,
+ queries: Tensor,
+ keys: Tensor,
+ values: Tensor,
+ q_mask: Optional[Tensor] = None,
+ kv_mask: Optional[Tensor] = None,
+ ) -> Tensor:
"""Multi-head scaled dot-product attention, a.k.a full attention.
Args:
@@ -75,7 +84,7 @@ class FullAttention(Module):
"""
# Compute the unnormalized attention and apply the masks
QK = torch.einsum("nlhd,nshd->nlsh", queries, keys)
- if kv_mask is not None:
+ if kv_mask is not None and q_mask is not None:
QK.masked_fill_(~(q_mask[:, :, None, None] * kv_mask[:, None, :, None]), float('-inf'))
# Compute the attention and the weighted average
diff --git a/kornia/feature/loftr/loftr_module/transformer.py b/kornia/feature/loftr/loftr_module/transformer.py
index cf731e833..fe16b106c 100644
--- a/kornia/feature/loftr/loftr_module/transformer.py
+++ b/kornia/feature/loftr/loftr_module/transformer.py
@@ -1,14 +1,18 @@
+from __future__ import annotations
+
import copy
-from typing import Optional
+from typing import Any, Literal
import torch
from torch import nn
+from kornia.core import Module, Tensor
+
from .linear_attention import FullAttention, LinearAttention
-class LoFTREncoderLayer(nn.Module):
- def __init__(self, d_model, nhead, attention='linear'):
+class LoFTREncoderLayer(Module):
+ def __init__(self, d_model: int, nhead: int, attention: Literal['linear'] | None = 'linear') -> None:
super().__init__()
self.dim = d_model // nhead
@@ -31,18 +35,14 @@ class LoFTREncoderLayer(nn.Module):
self.norm2 = nn.LayerNorm(d_model)
def forward(
- self,
- x: torch.Tensor,
- source: torch.Tensor,
- x_mask: Optional[torch.Tensor] = None,
- source_mask: Optional[torch.Tensor] = None,
- ) -> torch.Tensor:
+ self, x: Tensor, source: Tensor, x_mask: Tensor | None = None, source_mask: Tensor | None = None
+ ) -> Tensor:
"""
Args:
- x (torch.Tensor): [N, L, C]
- source (torch.Tensor): [N, S, C]
- x_mask (torch.Tensor): [N, L] (optional)
- source_mask (torch.Tensor): [N, S] (optional)
+ x: [N, L, C]
+ source: [N, S, C]
+ x_mask: [N, L] (optional)
+ source_mask: [N, S] (optional)
"""
bs = x.size(0)
query, key, value = x, source, source
@@ -62,10 +62,10 @@ class LoFTREncoderLayer(nn.Module):
return x + message
-class LocalFeatureTransformer(nn.Module):
+class LocalFeatureTransformer(Module):
"""A Local Feature Transformer (LoFTR) module."""
- def __init__(self, config):
+ def __init__(self, config: dict[str, Any]) -> None:
super().__init__()
self.config = config
@@ -76,18 +76,20 @@ class LocalFeatureTransformer(nn.Module):
self.layers = nn.ModuleList([copy.deepcopy(encoder_layer) for _ in range(len(self.layer_names))])
self._reset_parameters()
- def _reset_parameters(self):
+ def _reset_parameters(self) -> None:
for p in self.parameters():
if p.dim() > 1:
nn.init.xavier_uniform_(p)
- def forward(self, feat0, feat1, mask0=None, mask1=None):
+ def forward(
+ self, feat0: Tensor, feat1: Tensor, mask0: None | Tensor = None, mask1: None | Tensor = None
+ ) -> tuple[Tensor, Tensor]:
"""
Args:
- feat0 (torch.Tensor): [N, L, C]
- feat1 (torch.Tensor): [N, S, C]
- mask0 (torch.Tensor): [N, L] (optional)
- mask1 (torch.Tensor): [N, S] (optional)
+ feat0: [N, L, C]
+ feat1: [N, S, C]
+ mask0: [N, L] (optional)
+ mask1: [N, S] (optional)
"""
if self.d_model != feat0.size(2):
msg = "the feature number of src and transformer must be equal"
diff --git a/kornia/feature/loftr/utils/fine_matching.py b/kornia/feature/loftr/utils/fine_matching.py
index a26894344..70c849c24 100644
--- a/kornia/feature/loftr/utils/fine_matching.py
+++ b/kornia/feature/loftr/utils/fine_matching.py
@@ -1,19 +1,22 @@
+from __future__ import annotations
+
import math
+from typing import Any
import torch
-from torch import nn
+from kornia.core import Module, Tensor
from kornia.geometry.subpix import dsnt
from kornia.utils.grid import create_meshgrid
-class FineMatching(nn.Module):
+class FineMatching(Module):
"""FineMatching with s2d paradigm."""
- def __init__(self):
+ def __init__(self) -> None:
super().__init__()
- def forward(self, feat_f0, feat_f1, data):
+ def forward(self, feat_f0: Tensor, feat_f1: Tensor, data: dict[str, Any]) -> None:
"""
Args:
feat0 (torch.Tensor): [M, WW, C]
@@ -68,7 +71,7 @@ class FineMatching(nn.Module):
self.get_fine_match(coords_normalized, data)
@torch.no_grad()
- def get_fine_match(self, coords_normed, data):
+ def get_fine_match(self, coords_normed: Tensor, data: dict[str, Any]) -> None:
W, _, _, scale = self.W, self.WW, self.C, self.scale
# mkpts0_f and mkpts1_f
diff --git a/kornia/feature/loftr/utils/geometry.py b/kornia/feature/loftr/utils/geometry.py
index cd73bc983..089b6c41c 100644
--- a/kornia/feature/loftr/utils/geometry.py
+++ b/kornia/feature/loftr/utils/geometry.py
@@ -1,21 +1,27 @@
+from typing import Tuple
+
import torch
+from kornia.core import Tensor
+
@torch.no_grad()
-def warp_kpts(kpts0, depth0, depth1, T_0to1, K0, K1):
+def warp_kpts(
+ kpts0: Tensor, depth0: Tensor, depth1: Tensor, T_0to1: Tensor, K0: Tensor, K1: Tensor
+) -> Tuple[Tensor, Tensor]:
"""Warp kpts0 from I0 to I1 with depth, K and Rt Also check covisibility and depth consistency. Depth is
consistent if relative error < 0.2 (hard-coded).
Args:
- kpts0 (torch.Tensor): [N, L, 2] - <x, y>,
- depth0 (torch.Tensor): [N, H, W],
- depth1 (torch.Tensor): [N, H, W],
- T_0to1 (torch.Tensor): [N, 3, 4],
- K0 (torch.Tensor): [N, 3, 3],
- K1 (torch.Tensor): [N, 3, 3],
+ kpts0: [N, L, 2] - <x, y>,
+ depth0: [N, H, W],
+ depth1: [N, H, W],
+ T_0to1: [N, 3, 4],
+ K0: [N, 3, 3],
+ K1: [N, 3, 3],
Returns:
- calculable_mask (torch.Tensor): [N, L]
- warped_keypoints0 (torch.Tensor): [N, L, 2] <x0_hat, y1_hat>
+ calculable_mask: [N, L]
+ warped_keypoints0: [N, L, 2] <x0_hat, y1_hat>
"""
kpts0_long = kpts0.round().long()
diff --git a/kornia/feature/loftr/utils/position_encoding.py b/kornia/feature/loftr/utils/position_encoding.py
index ce2b71768..dd6991260 100644
--- a/kornia/feature/loftr/utils/position_encoding.py
+++ b/kornia/feature/loftr/utils/position_encoding.py
@@ -1,4 +1,5 @@
import math
+from typing import Tuple
import torch
@@ -10,7 +11,7 @@ class PositionEncodingSine(Module):
pe: Tensor
- def __init__(self, d_model, max_shape=(256, 256), temp_bug_fix=True):
+ def __init__(self, d_model: int, max_shape: Tuple[int, int] = (256, 256), temp_bug_fix: bool = True) -> None:
"""
Args:
max_shape (tuple): for 1/8 featmap, the max length of 256 corresponds to 2048 pixels
@@ -26,7 +27,7 @@ class PositionEncodingSine(Module):
pe = self._create_position_encoding(max_shape)
self.register_buffer('pe', pe, persistent=False) # [1, C, H, W]
- def _create_position_encoding(self, max_shape):
+ def _create_position_encoding(self, max_shape: Tuple[int, int]) -> Tensor:
"""Creates a position encoding from scratch.
For 1/8 feature map (which is standard): If the input image size is H, W (both divisible by 8), the max_shape
@@ -50,7 +51,7 @@ class PositionEncodingSine(Module):
pe[3::4, :, :] = torch.cos(y_position * div_term)
return pe.unsqueeze(0)
- def update_position_encoding_size(self, max_shape):
+ def update_position_encoding_size(self, max_shape: Tuple[int, int]) -> None:
"""Updates position encoding to new max_shape.
For 1/8 feature map (which is standard): If the input image size is H, W (both divisible by 8), the max_shape
@@ -58,7 +59,7 @@ class PositionEncodingSine(Module):
"""
self.pe = self._create_position_encoding(max_shape).to(self.pe.device)
- def forward(self, x):
+ def forward(self, x: Tensor) -> Tensor:
"""
Args:
x: [N, C, H, W]
diff --git a/kornia/feature/loftr/utils/supervision.py b/kornia/feature/loftr/utils/supervision.py
index 76bbeb39b..c4a4aba9d 100644
--- a/kornia/feature/loftr/utils/supervision.py
+++ b/kornia/feature/loftr/utils/supervision.py
@@ -1,14 +1,18 @@
+from __future__ import annotations
+
+from typing import Any
+
import torch
+from kornia.core import Tensor
from kornia.utils import create_meshgrid
from .geometry import warp_kpts
-# Coarse-Level supervision
-
+# Coarse-Level supervision
@torch.no_grad()
-def mask_pts_at_padded_regions(grid_pt, mask):
+def mask_pts_at_padded_regions(grid_pt: Tensor, mask: Tensor) -> Tensor:
"""For megadepth dataset, zero-padding exists in images."""
n, h, w = mask.shape
mask = mask.reshape(n, h * w).unsqueeze(-1).repeat(1, 1, 2)
@@ -19,7 +23,7 @@ def mask_pts_at_padded_regions(grid_pt, mask):
@torch.no_grad()
-def spvs_coarse(data, config):
+def spvs_coarse(data: dict[str, Any], config: dict[str, Any]) -> None:
"""
Update:
data (dict): {
@@ -71,7 +75,7 @@ def spvs_coarse(data, config):
nearest_index0 = w_pt1_c_round[..., 0] + w_pt1_c_round[..., 1] * w0
# corner case: out of boundary
- def out_bound_mask(pt, w, h):
+ def out_bound_mask(pt: Tensor, w: Tensor, h: Tensor) -> Tensor:
return (pt[..., 0] < 0) + (pt[..., 0] >= w) + (pt[..., 1] < 0) + (pt[..., 1] >= h)
nearest_index1[out_bound_mask(w_pt0_c_round, w1, h1)] = 0
@@ -102,7 +106,7 @@ def spvs_coarse(data, config):
data.update({'spv_w_pt0_i': w_pt0_i, 'spv_pt1_i': grid_pt1_i})
-def compute_supervision_coarse(data, config):
+def compute_supervision_coarse(data: dict[str, Any], config: dict[str, Any]) -> None:
if len(set(data['dataset_name'])) != 1:
raise ValueError("Do not support mixed datasets training!")
data_source = data['dataset_name'][0]
@@ -113,10 +117,8 @@ def compute_supervision_coarse(data, config):
# Fine-Level supervision
-
-
@torch.no_grad()
-def spvs_fine(data, config):
+def spvs_fine(data: dict[str, Any], config: dict[str, Any]) -> None:
"""
Update:
data (dict):{
@@ -138,7 +140,7 @@ def spvs_fine(data, config):
data.update({"expec_f_gt": expec_f_gt})
-def compute_supervision_fine(data, config):
+def compute_supervision_fine(data: dict[str, Any], config: dict[str, Any]) -> None:
data_source = data['dataset_name'][0]
if data_source.lower() in ['scannet', 'megadepth']:
spvs_fine(data, config)
diff --git a/kornia/feature/matching.py b/kornia/feature/matching.py
index 918c96f12..92ed6cbab 100644
--- a/kornia/feature/matching.py
+++ b/kornia/feature/matching.py
@@ -1,4 +1,4 @@
-from typing import Dict, Optional, Tuple
+from typing import Any, Dict, Optional, Tuple
import torch
@@ -21,7 +21,7 @@ def _cdist(d1: Tensor, d2: Tensor) -> Tensor:
return dm
-def _get_default_fginn_params():
+def _get_default_fginn_params() -> Dict[str, Any]:
config = {"th": 0.85, "mutual": False, "spatial_th": 10.0}
return config
@@ -371,9 +371,9 @@ class GeometryAwareDescriptorMatcher(Module):
params.update(self.params)
out = match_fginn(desc1, desc2, lafs1, lafs2, params['th'], params['spatial_th'], params['mutual'])
elif self.match_mode == 'adalam':
- params = get_adalam_default_config()
- params.update(self.params)
- out = match_adalam(desc1, desc2, lafs1, lafs2, config=params)
+ _params = get_adalam_default_config()
+ _params.update(self.params) # type: ignore[typeddict-item]
+ out = match_adalam(desc1, desc2, lafs1, lafs2, config=_params)
else:
raise NotImplementedError
return out
diff --git a/kornia/feature/orientation.py b/kornia/feature/orientation.py
index d6bade110..b217044f7 100644
--- a/kornia/feature/orientation.py
+++ b/kornia/feature/orientation.py
@@ -42,7 +42,7 @@ class PatchDominantGradientOrientation(nn.Module):
eps: for safe division, and arctan.
"""
- def __init__(self, patch_size: int = 32, num_angular_bins: int = 36, eps: float = 1e-8):
+ def __init__(self, patch_size: int = 32, num_angular_bins: int = 36, eps: float = 1e-8) -> None:
super().__init__()
self.patch_size = patch_size
self.num_ang_bins = num_angular_bins
@@ -54,7 +54,7 @@ class PatchDominantGradientOrientation(nn.Module):
sigma: float = float(self.patch_size) / 6.0
self.weighting = get_gaussian_kernel2d((self.patch_size, self.patch_size), (sigma, sigma), True)
- def __repr__(self):
+ def __repr__(self) -> str:
return (
f'{self.__class__.__name__}('
f'patch_size={self.patch_size}, '
@@ -137,7 +137,7 @@ class OriNet(nn.Module):
>>> angle = orinet(input) # 16
"""
- def __init__(self, pretrained: bool = False, eps: float = 1e-8):
+ def __init__(self, pretrained: bool = False, eps: float = 1e-8) -> None:
super().__init__()
self.features = nn.Sequential(
nn.Conv2d(1, 16, kernel_size=3, padding=1, bias=False),
@@ -205,7 +205,9 @@ class LAFOrienter(nn.Module):
or OriNet.
""" # pylint: disable
- def __init__(self, patch_size: int = 32, num_angular_bins: int = 36, angle_detector: Optional[nn.Module] = None):
+ def __init__(
+ self, patch_size: int = 32, num_angular_bins: int = 36, angle_detector: Optional[nn.Module] = None
+ ) -> None:
super().__init__()
self.patch_size = patch_size
self.num_ang_bins = num_angular_bins
@@ -215,7 +217,7 @@ class LAFOrienter(nn.Module):
else:
self.angle_detector = angle_detector
- def __repr__(self):
+ def __repr__(self) -> str:
return f"{self.__class__.__name__}(patch_size={self.patch_size}, angle_detector={self.angle_detector})"
def forward(self, laf: torch.Tensor, img: torch.Tensor) -> torch.Tensor:
diff --git a/kornia/feature/scale_space_detector.py b/kornia/feature/scale_space_detector.py
index d8c4e9efc..25c3f9353 100644
--- a/kornia/feature/scale_space_detector.py
+++ b/kornia/feature/scale_space_detector.py
@@ -102,7 +102,7 @@ class ScaleSpaceDetector(Module):
# like Difference-of-Gaussians
self.scale_space_response = scale_space_response
- def __repr__(self):
+ def __repr__(self) -> str:
return (
f"{self.__class__.__name__}("
f"num_features={self.num_features}, "
@@ -268,7 +268,7 @@ class MultiResolutionDetector(Module):
config: Detector_config = get_default_detector_config(),
ori_module: Optional[Module] = None,
aff_module: Optional[Module] = None,
- ):
+ ) -> None:
super().__init__()
self.model = model
# Load extraction configuration
diff --git a/kornia/feature/siftdesc.py b/kornia/feature/siftdesc.py
index b88bc918f..3c4ab2206 100644
--- a/kornia/feature/siftdesc.py
+++ b/kornia/feature/siftdesc.py
@@ -128,7 +128,7 @@ class SIFTDescriptor(Module):
def get_weighting_kernel(self) -> Tensor:
return self.gk.detach()
- def forward(self, input):
+ def forward(self, input: Tensor) -> Tensor:
KORNIA_CHECK_SHAPE(input, ["B", "1", f"{self.patch_size}", f"{self.patch_size}"])
B: int = input.shape[0]
self.pk = self.pk.to(input.dtype).to(input.device)
diff --git a/kornia/feature/sold2/backbones.py b/kornia/feature/sold2/backbones.py
index 03892353e..cd7cebc1b 100644
--- a/kornia/feature/sold2/backbones.py
+++ b/kornia/feature/sold2/backbones.py
@@ -1,12 +1,21 @@
"""Implements several backbone networks."""
-from typing import Any, Dict, List, Optional, Tuple, Type, Union
+from typing import Any, Dict, List, NamedTuple, Optional, Tuple, Type, Union
import torch
import torch.nn.functional as F
from torch import nn
from torch.nn.functional import pixel_shuffle, softmax
-from kornia.core import Module
+from kornia.core import Module, Tensor
+
+
+class HourglassConfig(NamedTuple):
+ depth: int
+ num_stacks: int
+ num_blocks: int
+ num_classes: int
+ input_channels: int
+ head: Type[Module]
# [Hourglass backbone classes]
@@ -23,26 +32,17 @@ class HourglassBackbone(Module):
def __init__(
self, input_channel: int = 1, depth: int = 4, num_stacks: int = 2, num_blocks: int = 1, num_classes: int = 5
- ):
+ ) -> None:
super().__init__()
self.head = MultitaskHead
- self.net = hg(
- **{
- "head": self.head,
- "depth": depth,
- "num_stacks": num_stacks,
- "num_blocks": num_blocks,
- "num_classes": num_classes,
- "input_channels": input_channel,
- }
- )
+ self.net = hg(HourglassConfig(depth, num_stacks, num_blocks, num_classes, input_channel, head=self.head))
- def forward(self, input_images: torch.Tensor) -> torch.Tensor:
+ def forward(self, input_images: Tensor) -> Tensor:
return self.net(input_images)
class MultitaskHead(Module):
- def __init__(self, input_channels: int):
+ def __init__(self, input_channels: int) -> None:
super().__init__()
m = int(input_channels / 4)
@@ -58,14 +58,14 @@ class MultitaskHead(Module):
)
self.heads = nn.ModuleList(heads)
- def forward(self, x: torch.Tensor) -> torch.Tensor:
+ def forward(self, x: Tensor) -> Tensor:
return torch.cat([head(x) for head in self.heads], dim=1)
class Bottleneck2D(Module):
def __init__(
self, inplanes: int, planes: int, stride: Union[int, Tuple[int, int]] = 1, downsample: Optional[Module] = None
- ):
+ ) -> None:
super().__init__()
self.bn1 = nn.BatchNorm2d(inplanes)
@@ -78,7 +78,7 @@ class Bottleneck2D(Module):
self.downsample = downsample
self.stride = stride
- def forward(self, x: torch.Tensor) -> torch.Tensor:
+ def forward(self, x: Tensor) -> Tensor:
residual = x
out = self.bn1(x)
@@ -102,7 +102,7 @@ class Bottleneck2D(Module):
class Hourglass(Module):
- def __init__(self, block: Type[Bottleneck2D], num_blocks: int, planes: int, depth: int, expansion: int = 2):
+ def __init__(self, block: Type[Bottleneck2D], num_blocks: int, planes: int, depth: int, expansion: int = 2) -> None:
super().__init__()
self.depth = depth
self.block = block
@@ -126,7 +126,7 @@ class Hourglass(Module):
hgl.append(nn.ModuleList(res))
return nn.ModuleList(hgl)
- def _hour_glass_forward(self, n: int, x: torch.Tensor) -> torch.Tensor:
+ def _hour_glass_forward(self, n: int, x: Tensor) -> Tensor:
up1 = self.hg[n - 1][0](x)
low1 = F.max_pool2d(x, 2, stride=2)
low1 = self.hg[n - 1][1](low1)
@@ -140,7 +140,7 @@ class Hourglass(Module):
out = up1 + up2
return out
- def forward(self, x: torch.Tensor) -> torch.Tensor:
+ def forward(self, x: Tensor) -> Tensor:
return self._hour_glass_forward(self.depth, x)
@@ -150,14 +150,14 @@ class HourglassNet(Module):
def __init__(
self,
block: Type[Bottleneck2D],
- head: Module,
+ head: Type[Module],
depth: int,
num_stacks: int,
num_blocks: int,
num_classes: int,
input_channels: int,
expansion: int = 2,
- ):
+ ) -> None:
super().__init__()
self.inplanes = 64
@@ -210,7 +210,7 @@ class HourglassNet(Module):
conv = nn.Conv2d(inplanes, outplanes, kernel_size=1)
return nn.Sequential(conv, bn, self.relu)
- def forward(self, x: torch.Tensor) -> torch.Tensor:
+ def forward(self, x: Tensor) -> Tensor:
out = []
x = self.conv1(x)
x = self.bn1(x)
@@ -235,17 +235,16 @@ class HourglassNet(Module):
return y
-def hg(**kwargs):
- model = HourglassNet(
+def hg(cfg: HourglassConfig) -> HourglassNet:
+ return HourglassNet(
Bottleneck2D,
- head=kwargs.get("head", lambda c_in, c_out: nn.Conv2d(c_in, c_out, 1)),
- depth=kwargs["depth"],
- num_stacks=kwargs["num_stacks"],
- num_blocks=kwargs["num_blocks"],
- num_classes=kwargs["num_classes"],
- input_channels=kwargs["input_channels"],
+ head=cfg.head,
+ depth=cfg.depth,
+ num_stacks=cfg.num_stacks,
+ num_blocks=cfg.num_blocks,
+ num_classes=cfg.num_classes,
+ input_channels=cfg.input_channels,
)
- return model
# [Backbone decoders]
@@ -258,7 +257,7 @@ class SuperpointDecoder(Module):
the junction heatmap, with shape (B, H, W).
"""
- def __init__(self, input_feat_dim: int = 128, grid_size: int = 8):
+ def __init__(self, input_feat_dim: int = 128, grid_size: int = 8) -> None:
super().__init__()
self.relu = nn.ReLU(inplace=True)
# Perform strided convolution when using lcnn backbone.
@@ -266,7 +265,7 @@ class SuperpointDecoder(Module):
self.convPb = nn.Conv2d(256, 65, kernel_size=1, stride=1, padding=0)
self.grid_size = grid_size
- def forward(self, input_features: torch.Tensor) -> torch.Tensor:
+ def forward(self, input_features: Tensor) -> Tensor:
feat = self.relu(self.convPa(input_features))
semi = self.convPb(feat)
@@ -287,7 +286,7 @@ class PixelShuffleDecoder(Module):
the (B, 1, H, W) line heatmap.
"""
- def __init__(self, input_feat_dim: int = 128, num_upsample: int = 2, output_channel: int = 2):
+ def __init__(self, input_feat_dim: int = 128, num_upsample: int = 2, output_channel: int = 2) -> None:
super().__init__()
# Get channel parameters
self.channel_conf = self.get_channel_conf(num_upsample)
@@ -328,7 +327,7 @@ class PixelShuffleDecoder(Module):
return [256, 64, 16]
return [256, 64, 16, 4]
- def forward(self, input_features: torch.Tensor) -> torch.Tensor:
+ def forward(self, input_features: Tensor) -> Tensor:
# Iterate til output block
out = input_features
for block in self.conv_block_lst[:-1]:
@@ -351,13 +350,13 @@ class SuperpointDescriptor(Module):
the semi-dense descriptors with shape (B, 128, H/4, W/4).
"""
- def __init__(self, input_feat_dim: int = 128):
+ def __init__(self, input_feat_dim: int = 128) -> None:
super().__init__()
self.relu = nn.ReLU(inplace=True)
self.convPa = nn.Conv2d(input_feat_dim, 256, kernel_size=3, stride=1, padding=1)
self.convPb = nn.Conv2d(256, 128, kernel_size=1, stride=1, padding=0)
- def forward(self, input_features: torch.Tensor) -> torch.Tensor:
+ def forward(self, input_features: Tensor) -> Tensor:
feat = self.relu(self.convPa(input_features))
semi = self.convPb(feat)
@@ -379,7 +378,7 @@ class SOLD2Net(Module):
descriptors: semi-dense descriptors.
"""
- def __init__(self, model_cfg: Dict[str, Any]):
+ def __init__(self, model_cfg: Dict[str, Any]) -> None:
super().__init__()
self.cfg = model_cfg
@@ -397,7 +396,7 @@ class SOLD2Net(Module):
if "use_descriptor" in self.cfg:
self.descriptor_decoder = SuperpointDescriptor(feat_channel)
- def forward(self, input_images):
+ def forward(self, input_images: Tensor) -> Dict[str, Tensor]:
# The backbone
features = self.backbone_net(input_images)
diff --git a/kornia/feature/sold2/sold2.py b/kornia/feature/sold2/sold2.py
index fc8d222e0..f5870e118 100644
--- a/kornia/feature/sold2/sold2.py
+++ b/kornia/feature/sold2/sold2.py
@@ -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[str, Any]] = None):
+ def __init__(self, pretrained: bool = True, config: Optional[Dict[str, Any]] = None) -> None:
super().__init__()
# Initialize some parameters
self.config = default_cfg if config is None else config
@@ -143,7 +143,7 @@ class SOLD2(Module):
"""
return self.line_matcher(line_seg1, line_seg2, desc1, desc2)
- def adapt_state_dict(self, state_dict):
+ def adapt_state_dict(self, state_dict: Dict[str, Any]) -> Dict[str, Any]:
del state_dict["w_junc"]
del state_dict["w_heatmap"]
del state_dict["w_desc"]
@@ -168,7 +168,7 @@ class WunschLineMatcher(Module):
top_k_candidates: int = 10,
grid_size: int = 8,
line_score: bool = False,
- ):
+ ) -> None:
super().__init__()
self.cross_check = cross_check
self.num_samples = num_samples
@@ -343,7 +343,7 @@ def keypoints_to_grid(keypoints: Tensor, img_size: Tuple[int, int]) -> Tensor:
return grid_points
-def batched_linspace(start, end, step, dim):
+def batched_linspace(start: Tensor, end: Tensor, step: int, dim: int) -> Tensor:
"""Batch version of torch.normalize (similar to the numpy one)."""
intervals = ((end - start) / (step - 1)).unsqueeze(dim)
broadcast_size = [1] * len(intervals.shape)
diff --git a/kornia/feature/sold2/sold2_detector.py b/kornia/feature/sold2/sold2_detector.py
index a29d1f512..3083192a0 100644
--- a/kornia/feature/sold2/sold2_detector.py
+++ b/kornia/feature/sold2/sold2_detector.py
@@ -61,7 +61,7 @@ class SOLD2_detector(Module):
>>> line_segments = sold2_detector(img)["line_segments"]
"""
- def __init__(self, pretrained: bool = True, config: Optional[Dict[str, Any]] = None):
+ def __init__(self, pretrained: bool = True, config: Optional[Dict[str, Any]] = None) -> None:
super().__init__()
# Initialize some parameters
self.config = default_detector_cfg if config is None else config
@@ -81,7 +81,7 @@ class SOLD2_detector(Module):
self.line_detector_cfg = self.config["line_detector_cfg"]
self.line_detector = LineSegmentDetectionModule(**self.config["line_detector_cfg"])
- def adapt_state_dict(self, state_dict):
+ def adapt_state_dict(self, state_dict: Dict[str, Any]) -> Dict[str, Any]:
del state_dict["w_junc"]
del state_dict["w_heatmap"]
del state_dict["w_desc"]
diff --git a/kornia/filters/blur_pool.py b/kornia/filters/blur_pool.py
index 1b2083422..b34a9cbdb 100644
--- a/kornia/filters/blur_pool.py
+++ b/kornia/filters/blur_pool.py
@@ -49,7 +49,7 @@ class BlurPool2D(Module):
[0.0000, 0.0625, 0.3125]]]])
"""
- def __init__(self, kernel_size: tuple[int, int] | int, stride: int = 2):
+ def __init__(self, kernel_size: tuple[int, int] | int, stride: int = 2) -> None:
super().__init__()
self.kernel_size = kernel_size
self.stride = stride
@@ -96,7 +96,7 @@ class MaxBlurPool2D(Module):
def __init__(
self, kernel_size: tuple[int, int] | int, stride: int = 2, max_pool_size: int = 2, ceil_mode: bool = False
- ):
+ ) -> None:
super().__init__()
self.kernel_size = kernel_size
self.stride = stride
@@ -114,7 +114,7 @@ class MaxBlurPool2D(Module):
class EdgeAwareBlurPool2D(Module):
def __init__(
self, kernel_size: tuple[int, int] | int, edge_threshold: float = 1.25, edge_dilation_kernel_size: int = 3
- ):
+ ) -> None:
super().__init__()
self.kernel_size = kernel_size
self.edge_threshold = edge_threshold
diff --git a/kornia/filters/dexined.py b/kornia/filters/dexined.py
index 0e9ec18f7..0cc61b76b 100644
--- a/kornia/filters/dexined.py
+++ b/kornia/filters/dexined.py
@@ -15,7 +15,7 @@ from kornia.utils import map_location_to_cpu
url: str = "http://cmp.felk.cvut.cz/~mishkdmy/models/DexiNed_BIPED_10.pth"
-def weight_init(m):
+def weight_init(m: Module) -> None:
if isinstance(m, (nn.Conv2d,)):
# torch.nn.init.xavier_uniform_(m.weight, gain=1.0)
torch.nn.init.xavier_normal_(m.weight, gain=1.0)
@@ -39,7 +39,7 @@ def weight_init(m):
class CoFusion(Module):
- def __init__(self, in_ch, out_ch):
+ def __init__(self, in_ch: int, out_ch: int) -> None:
super().__init__()
self.conv1 = nn.Conv2d(in_ch, 64, kernel_size=3, stride=1, padding=1)
self.conv2 = nn.Conv2d(64, 64, kernel_size=3, stride=1, padding=1)
@@ -59,7 +59,7 @@ class CoFusion(Module):
class _DenseLayer(nn.Sequential):
- def __init__(self, input_features, out_features):
+ def __init__(self, input_features: int, out_features: int) -> None:
super().__init__(
OrderedDict(
[
@@ -82,7 +82,7 @@ class _DenseLayer(nn.Sequential):
class _DenseBlock(nn.Sequential):
- def __init__(self, num_layers, input_features, out_features):
+ def __init__(self, num_layers: int, input_features: int, out_features: int) -> None:
super().__init__()
for i in range(num_layers):
layer = _DenseLayer(input_features, out_features)
@@ -97,7 +97,7 @@ class _DenseBlock(nn.Sequential):
class UpConvBlock(Module):
- def __init__(self, in_features, up_scale):
+ def __init__(self, in_features: int, up_scale: int) -> None:
super().__init__()
self.up_factor = 2
self.constant_features = 16
@@ -130,7 +130,7 @@ class UpConvBlock(Module):
class SingleConvBlock(Module):
- def __init__(self, in_features, out_features, stride, use_bs=True):
+ def __init__(self, in_features: int, out_features: int, stride: int, use_bs: bool = True) -> None:
super().__init__()
self.use_bn = use_bs
self.conv = nn.Conv2d(in_features, out_features, 1, stride=stride, bias=True)
@@ -144,7 +144,14 @@ class SingleConvBlock(Module):
class DoubleConvBlock(nn.Sequential):
- def __init__(self, in_features, mid_features, out_features=None, stride=1, use_act=True):
+ def __init__(
+ self,
+ in_features: int,
+ mid_features: int,
+ out_features: int | None = None,
+ stride: int = 1,
+ use_act: bool = True,
+ ) -> None:
super().__init__()
if out_features is None:
out_features = mid_features
@@ -172,7 +179,7 @@ class DexiNed(Module):
torch.Size([1, 1, 320, 320])
"""
- def __init__(self, pretrained: bool):
+ def __init__(self, pretrained: bool) -> None:
super().__init__()
self.block_1 = DoubleConvBlock(3, 32, 64, stride=2)
self.block_2 = DoubleConvBlock(64, 128, use_act=False)
diff --git a/kornia/filters/guided.py b/kornia/filters/guided.py
index 9884b4993..1e975f5af 100644
--- a/kornia/filters/guided.py
+++ b/kornia/filters/guided.py
@@ -193,7 +193,7 @@ class GuidedBlur(Module):
def __init__(
self, kernel_size: tuple[int, int] | int, eps: float, border_type: str = 'reflect', subsample: int = 1
- ):
+ ) -> None:
super().__init__()
self.kernel_size = kernel_size
self.eps = eps
diff --git a/kornia/geometry/boxes.py b/kornia/geometry/boxes.py
index ba0b16db6..126178833 100644
--- a/kornia/geometry/boxes.py
+++ b/kornia/geometry/boxes.py
@@ -3,6 +3,7 @@ from __future__ import annotations
from typing import cast
import torch
+from torch import Size
from kornia.core import Tensor
from kornia.geometry.bbox import validate_bbox
@@ -226,7 +227,7 @@ class Boxes:
return self
@property
- def shape(self):
+ def shape(self) -> tuple[int, ...] | Size:
return self.data.shape
def get_boxes_shape(self) -> tuple[torch.Tensor, torch.Tensor]:
@@ -741,7 +742,7 @@ class Boxes3D:
return self
@property
- def shape(self):
+ def shape(self) -> tuple[int, ...] | Size:
return self.data.shape
def get_boxes_shape(self) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
diff --git a/kornia/geometry/camera/stereo.py b/kornia/geometry/camera/stereo.py
index 1b027e1bd..2f81344c1 100644
--- a/kornia/geometry/camera/stereo.py
+++ b/kornia/geometry/camera/stereo.py
@@ -29,7 +29,7 @@ class StereoException(Exception):
class StereoCamera:
- def __init__(self, rectified_left_camera: Tensor, rectified_right_camera: Tensor):
+ def __init__(self, rectified_left_camera: Tensor, rectified_right_camera: Tensor) -> None:
r"""Class representing a horizontal stereo camera setup.
Args:
diff --git a/kornia/geometry/conversions.py b/kornia/geometry/conversions.py
index 7794f462f..a6cef4565 100644
--- a/kornia/geometry/conversions.py
+++ b/kornia/geometry/conversions.py
@@ -284,7 +284,7 @@ def angle_axis_to_rotation_matrix(angle_axis: Tensor) -> Tensor:
if not angle_axis.shape[-1] == 3:
raise ValueError(f"Input size must be a (*, 3) tensor. Got {angle_axis.shape}")
- def _compute_rotation_matrix(angle_axis, theta2, eps=1e-6):
+ def _compute_rotation_matrix(angle_axis: Tensor, theta2: Tensor, eps: float = 1e-6) -> Tensor:
# We want to be careful to only evaluate the square root if the
# norm of the angle_axis vector is greater than zero. Otherwise
# we get a division by zero.
@@ -307,7 +307,7 @@ def angle_axis_to_rotation_matrix(angle_axis: Tensor) -> Tensor:
rotation_matrix = concatenate([r00, r01, r02, r10, r11, r12, r20, r21, r22], dim=1)
return rotation_matrix.view(-1, 3, 3)
- def _compute_rotation_matrix_taylor(angle_axis):
+ def _compute_rotation_matrix_taylor(angle_axis: Tensor) -> Tensor:
rx, ry, rz = torch.chunk(angle_axis, 3, dim=1)
k_one = torch.ones_like(rx)
rotation_matrix = concatenate([k_one, -rz, ry, rz, k_one, -rx, -ry, rx, k_one], dim=1)
@@ -400,7 +400,7 @@ def rotation_matrix_to_quaternion(rotation_matrix: Tensor, eps: float = 1.0e-8)
trace: Tensor = m00 + m11 + m22
- def trace_positive_cond():
+ def trace_positive_cond() -> Tensor:
sq = torch.sqrt(trace + 1.0 + eps) * 2.0 # sq = 4 * qw.
qw = 0.25 * sq
qx = safe_zero_division(m21 - m12, sq)
@@ -408,7 +408,7 @@ def rotation_matrix_to_quaternion(rotation_matrix: Tensor, eps: float = 1.0e-8)
qz = safe_zero_division(m10 - m01, sq)
return concatenate((qw, qx, qy, qz), dim=-1)
- def cond_1():
+ def cond_1() -> Tensor:
sq = torch.sqrt(1.0 + m00 - m11 - m22 + eps) * 2.0 # sq = 4 * qx.
qw = safe_zero_division(m21 - m12, sq)
qx = 0.25 * sq
@@ -416,7 +416,7 @@ def rotation_matrix_to_quaternion(rotation_matrix: Tensor, eps: float = 1.0e-8)
qz = safe_zero_division(m02 + m20, sq)
return concatenate((qw, qx, qy, qz), dim=-1)
- def cond_2():
+ def cond_2() -> Tensor:
sq = torch.sqrt(1.0 + m11 - m00 - m22 + eps) * 2.0 # sq = 4 * qy.
qw = safe_zero_division(m02 - m20, sq)
qx = safe_zero_division(m01 + m10, sq)
@@ -424,7 +424,7 @@ def rotation_matrix_to_quaternion(rotation_matrix: Tensor, eps: float = 1.0e-8)
qz = safe_zero_division(m12 + m21, sq)
return concatenate((qw, qx, qy, qz), dim=-1)
- def cond_3():
+ def cond_3() -> Tensor:
sq = torch.sqrt(1.0 + m22 - m00 - m11 + eps) * 2.0 # sq = 4 * qz.
qw = safe_zero_division(m10 - m01, sq)
qx = safe_zero_division(m02 + m20, sq)
diff --git a/kornia/geometry/depth.py b/kornia/geometry/depth.py
index b90c83100..3d066182f 100644
--- a/kornia/geometry/depth.py
+++ b/kornia/geometry/depth.py
@@ -193,7 +193,7 @@ class DepthWarper(Module):
mode: str = 'bilinear',
padding_mode: str = 'zeros',
align_corners: bool = True,
- ):
+ ) -> None:
super().__init__()
# constructor members
self.width: int = width
@@ -241,16 +241,16 @@ class DepthWarper(Module):
self._dst_proj_src = dst_proj_src
return self
- def _compute_projection(self, x, y, invd):
+ def _compute_projection(self, x: Union[int, float], y: Union[int, float], invd: Union[int, float]) -> Tensor:
if self._dst_proj_src is None or self._pinhole_src is None:
raise ValueError("Please, call compute_projection_matrix.")
point = tensor([[[x], [y], [invd], [1.0]]], device=self._dst_proj_src.device, dtype=self._dst_proj_src.dtype)
flow = torch.matmul(self._dst_proj_src, point)
z = 1.0 / flow[:, 2]
- x = flow[:, 0] * z
- y = flow[:, 1] * z
- return concatenate([x, y], 1)
+ _x = flow[:, 0] * z
+ _y = flow[:, 1] * z
+ return concatenate([_x, _y], 1)
def compute_subpixel_step(self) -> Tensor:
"""Compute the required inverse depth step to achieve sub pixel accurate sampling of the depth cost volume,
diff --git a/kornia/geometry/epipolar/fundamental.py b/kornia/geometry/epipolar/fundamental.py
index 5f7101f31..dc84933ac 100644
--- a/kornia/geometry/epipolar/fundamental.py
+++ b/kornia/geometry/epipolar/fundamental.py
@@ -4,7 +4,7 @@ from typing import Optional, Tuple
import torch
-from kornia.core import Tensor
+from kornia.core import Tensor, concatenate
from kornia.core.check import KORNIA_CHECK_SHAPE
from kornia.geometry.conversions import convert_points_from_homogeneous, convert_points_to_homogeneous
from kornia.geometry.linalg import transform_points
@@ -259,8 +259,8 @@ def fundamental_from_projections(P1: Tensor, P2: Tensor) -> Tensor:
if P1.shape[:-2] != P2.shape[:-2]:
raise AssertionError
- def vstack(x, y):
- return torch.cat([x, y], dim=-2)
+ def vstack(x: Tensor, y: Tensor) -> Tensor:
+ return concatenate([x, y], dim=-2)
X1 = P1[..., 1:, :]
X2 = vstack(P1[..., 2:3, :], P1[..., 0:1, :])
diff --git a/kornia/geometry/epipolar/projection.py b/kornia/geometry/epipolar/projection.py
index 22bac8e7b..7fdccbe21 100644
--- a/kornia/geometry/epipolar/projection.py
+++ b/kornia/geometry/epipolar/projection.py
@@ -4,13 +4,14 @@ from typing import Tuple, Union
import torch
from torch.linalg import qr as linalg_qr
+from kornia.core import Tensor, concatenate, pad
from kornia.utils import eye_like, vec_like
from kornia.utils.helpers import _torch_svd_cast
from .numeric import cross_product_matrix
-def intrinsics_like(focal: float, input: torch.Tensor) -> torch.Tensor:
+def intrinsics_like(focal: float, input: Tensor) -> Tensor:
r"""Return a 3x3 instrinsics matrix, with same size as the input.
The center of projection will be based in the input image size.
@@ -38,7 +39,7 @@ def intrinsics_like(focal: float, input: torch.Tensor) -> torch.Tensor:
return intrinsics
-def random_intrinsics(low: Union[float, torch.Tensor], high: Union[float, torch.Tensor]) -> torch.Tensor:
+def random_intrinsics(low: Union[float, Tensor], high: Union[float, Tensor]) -> Tensor:
r"""Generate a random camera matrix based on a given uniform distribution.
Args:
@@ -51,11 +52,11 @@ def random_intrinsics(low: Union[float, torch.Tensor], high: Union[float, torch.
sampler = torch.distributions.Uniform(low, high)
fx, fy, cx, cy = (sampler.sample(torch.Size((1,))) for _ in range(4))
zeros, ones = torch.zeros_like(fx), torch.ones_like(fx)
- camera_matrix: torch.Tensor = torch.cat([fx, zeros, cx, zeros, fy, cy, zeros, zeros, ones])
+ camera_matrix = concatenate([fx, zeros, cx, zeros, fy, cy, zeros, zeros, ones])
return camera_matrix.view(1, 3, 3)
-def scale_intrinsics(camera_matrix: torch.Tensor, scale_factor: Union[float, torch.Tensor]) -> torch.Tensor:
+def scale_intrinsics(camera_matrix: Tensor, scale_factor: Union[float, Tensor]) -> Tensor:
r"""Scale a camera matrix containing the intrinsics.
Applies the scaling factor to the focal length and center of projection.
@@ -76,7 +77,7 @@ def scale_intrinsics(camera_matrix: torch.Tensor, scale_factor: Union[float, tor
return K_scale
-def projection_from_KRt(K: torch.Tensor, R: torch.Tensor, t: torch.Tensor) -> torch.Tensor:
+def projection_from_KRt(K: Tensor, R: Tensor, t: Tensor) -> Tensor:
r"""Get the projection matrix P from K, R and t.
This function estimate the projection matrix by solving the following equation: :math:`P = K * [R|t]`.
@@ -98,17 +99,17 @@ def projection_from_KRt(K: torch.Tensor, R: torch.Tensor, t: torch.Tensor) -> to
if not len(K.shape) == len(R.shape) == len(t.shape):
raise AssertionError
- Rt: torch.Tensor = torch.cat([R, t], dim=-1) # 3x4
- Rt_h = torch.nn.functional.pad(Rt, [0, 0, 0, 1], "constant", 0.0) # 4x4
+ Rt = concatenate([R, t], dim=-1) # 3x4
+ Rt_h = pad(Rt, [0, 0, 0, 1], "constant", 0.0) # 4x4
Rt_h[..., -1, -1] += 1.0
- K_h: torch.Tensor = torch.nn.functional.pad(K, [0, 1, 0, 1], "constant", 0.0) # 4x4
+ K_h = pad(K, [0, 1, 0, 1], "constant", 0.0) # 4x4
K_h[..., -1, -1] += 1.0
return K @ Rt
-def KRt_from_projection(P: torch.Tensor, eps: float = 1e-6) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
+def KRt_from_projection(P: Tensor, eps: float = 1e-6) -> Tuple[Tensor, Tensor, Tensor]:
r"""Decompose the Projection matrix into Camera-Matrix, Rotation Matrix and Translation vector.
Args:
@@ -146,7 +147,7 @@ def KRt_from_projection(P: torch.Tensor, eps: float = 1e-6) -> Tuple[torch.Tenso
return K, R, t
-def depth_from_point(R: torch.Tensor, t: torch.Tensor, X: torch.Tensor) -> torch.Tensor:
+def depth_from_point(R: Tensor, t: Tensor, X: Tensor) -> Tensor:
r"""Return the depth of a point transformed by a rigid transform.
Args:
@@ -165,9 +166,7 @@ def depth_from_point(R: torch.Tensor, t: torch.Tensor, X: torch.Tensor) -> torch
# adapted from:
# https://github.com/opencv/opencv_contrib/blob/master/modules/sfm/src/fundamental.cpp#L61
# https://github.com/mapillary/OpenSfM/blob/master/opensfm/multiview.py#L14
-
-
-def _nullspace(A):
+def _nullspace(A: Tensor) -> Tuple[Tensor, Tensor]:
"""Compute the null space of A.
Return the smallest singular value and the corresponding vector.
@@ -176,7 +175,7 @@ def _nullspace(A):
return s[..., -1], v[..., -1]
-def projections_from_fundamental(F_mat: torch.Tensor) -> torch.Tensor:
+def projections_from_fundamental(F_mat: Tensor) -> Tensor:
r"""Get the projection matrices from the Fundamental Matrix.
Args:
diff --git a/kornia/geometry/keypoints.py b/kornia/geometry/keypoints.py
index 7710af75a..372105021 100644
--- a/kornia/geometry/keypoints.py
+++ b/kornia/geometry/keypoints.py
@@ -1,6 +1,7 @@
from typing import List, Optional, Tuple, Union, cast
import torch
+from torch import Size
from kornia.core import Tensor
from kornia.geometry import transform_points
@@ -56,11 +57,11 @@ class Keypoints:
return self
@property
- def shape(self):
+ def shape(self) -> Union[Tuple[int, ...], Size]:
return self.data.shape
@property
- def data(self):
+ def data(self) -> Tensor:
return self._data
@property
@@ -250,7 +251,7 @@ class Keypoints3D:
return self
@property
- def shape(self) -> torch.Size:
+ def shape(self) -> Size:
return self.data.shape
@property
diff --git a/kornia/geometry/liegroup/_utils.py b/kornia/geometry/liegroup/_utils.py
index 9af19e934..953870c4c 100644
--- a/kornia/geometry/liegroup/_utils.py
+++ b/kornia/geometry/liegroup/_utils.py
@@ -1,19 +1,22 @@
-# Temporary shape check functions until KORNIA_CHECK_SHAPE is ready
-def check_so2_z_shape(z):
+from kornia.core import Tensor
+
+
+# TODO: Temporary shape check functions until KORNIA_CHECK_SHAPE is ready
+def check_so2_z_shape(z: Tensor) -> None:
z_shape = z.shape
len_z_shape = len(z_shape)
if (len_z_shape == 2 and z_shape[1] != 1) or (len_z_shape == 0 and not z.numel()) or (len_z_shape > 2):
raise ValueError(f"Invalid input size, we expect [B]. Got: {z.shape}")
-def check_so2_t_shape(t):
+def check_so2_t_shape(t: Tensor) -> None:
t_shape = t.shape
len_t_shape = len(t_shape)
if ((len_t_shape == 2) and (t_shape[1] != 2)) or ((len_t_shape == 1) and (t_shape[0] != 2)) or (len_t_shape > 2):
raise ValueError(f"Invalid translation shape, we expect [B, 2], or [2] Got: {t_shape}")
-def check_so2_theta_shape(theta):
+def check_so2_theta_shape(theta: Tensor) -> None:
theta_shape = theta.shape
len_theta_shape = len(theta_shape)
if (
@@ -24,7 +27,7 @@ def check_so2_theta_shape(theta):
raise ValueError(f"Invalid input size, we expect [B]. Got: {theta_shape}")
-def check_so2_matrix_shape(matrix):
+def check_so2_matrix_shape(matrix: Tensor) -> None:
matrix_shape = matrix.shape
len_matrix_shape = len(matrix_shape)
if (
@@ -35,27 +38,18 @@ def check_so2_matrix_shape(matrix):
raise ValueError(f"Invalid input size, we expect [B, 2, 2] or [2, 2]. Got: {matrix_shape}")
-def check_se2_t_shape(t):
+def check_se2_t_shape(t: Tensor) -> None:
check_so2_t_shape(t)
-def check_se2_r_t_shape(r, t):
- if ((len(r.z.shape) == 1) and (len(t.shape) == 2)) or ((len(r.z.shape) == 0) and len(t.shape) == 1):
- check_se2_t_shape(t)
- else:
- raise ValueError(
- f"Invalid input, both the inputs should be either batched or unbatched. Got: {r.z.shape} and {t.shape}"
- )
-
-
-def check_v_shape(v):
+def check_v_shape(v: Tensor) -> None:
v_shape = v.shape
len_v_shape = len(v_shape)
if ((len_v_shape == 2) and (v_shape[1] != 3)) or ((len_v_shape == 1) and (v_shape[0] != 3)) or (len_v_shape > 3):
raise ValueError(f"Invalid input shape, we expect [B, 3], [3] Got: {v_shape}")
-def check_se2_omega_shape(matrix):
+def check_se2_omega_shape(matrix: Tensor) -> None:
matrix_shape = matrix.shape
len_matrix_shape = len(matrix_shape)
if (
diff --git a/kornia/geometry/liegroup/se2.py b/kornia/geometry/liegroup/se2.py
index 17d62801f..56be78c83 100644
--- a/kornia/geometry/liegroup/se2.py
+++ b/kornia/geometry/liegroup/se2.py
@@ -19,11 +19,21 @@ from kornia.core import (
zeros_like,
)
from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_SAME_DEVICES, KORNIA_CHECK_TYPE
-from kornia.geometry.liegroup._utils import check_se2_omega_shape, check_se2_r_t_shape, check_v_shape
+from kornia.geometry.liegroup._utils import check_se2_omega_shape, check_se2_t_shape, check_v_shape
from kornia.geometry.liegroup.so2 import So2
from kornia.geometry.vector import Vector2
+def _check_se2_r_t_shape(r: So2, t: Tensor) -> None:
+ z_shape = r.z.shape
+ if ((len(z_shape) == 1) and (len(t.shape) == 2)) or ((len(z_shape) == 0) and len(t.shape) == 1):
+ check_se2_t_shape(t)
+ else:
+ raise ValueError(
+ f"Invalid input, both the inputs should be either batched or unbatched. Got: {r.z.shape} and {t.shape}"
+ )
+
+
class Se2(Module):
r"""Base class to represent the Se2 group.
@@ -70,7 +80,7 @@ class Se2(Module):
self._translation: Vector2 | Parameter
self._rotation: So2 = rotation
if isinstance(translation, Tensor):
- check_se2_r_t_shape(rotation, translation) # TODO remove
+ _check_se2_r_t_shape(rotation, translation) # TODO remove
self._translation = Parameter(translation)
else:
self._translation = translation
@@ -89,7 +99,7 @@ class Se2(Module):
def __mul__(self, right: Tensor) -> Tensor:
...
- def __mul__(self, right):
+ def __mul__(self, right: Se2 | Tensor) -> Se2 | Tensor:
"""Compose two Se2 transformations.
Args:
@@ -107,7 +117,7 @@ class Se2(Module):
return Se2(_r, _t)
elif isinstance(right, (Vector2, Tensor)):
# TODO change to KORNIA_CHECK_SHAPE once there is multiple shape support
- # check_se2_r_t_shape(so2, risght)
+ # _check_se2_r_t_shape(so2, risght)
return so2 * right + t
else:
raise TypeError(f"Unsupported type: {type(right)}")
@@ -188,7 +198,7 @@ class Se2(Module):
return stack((upsilon[..., 0, 0], upsilon[..., 1, 0], theta), -1)
@staticmethod
- def hat(v):
+ def hat(v: Tensor) -> Tensor:
"""Converts elements from vector space to lie algebra. Returns matrix of shape :math:`(B, 3, 3)`.
Args:
@@ -280,8 +290,11 @@ class Se2(Module):
tensor([[-1., -1.]], requires_grad=True)
"""
r_inv: So2 = self.r.inverse()
- t_inv: Tensor = r_inv * (-1 * self.t)
- return Se2(r_inv, t_inv)
+ _t = -1 * self.t
+ if isinstance(_t, int):
+ raise TypeError('Unexpected integer from `-1 * translation`')
+
+ return Se2(r_inv, r_inv * _t)
@classmethod
def random(cls, batch_size: int | None = None, device: Device | None = None, dtype: Dtype = None) -> Se2:
diff --git a/kornia/geometry/liegroup/se3.py b/kornia/geometry/liegroup/se3.py
index 2c4ba28b3..0b46513df 100644
--- a/kornia/geometry/liegroup/se3.py
+++ b/kornia/geometry/liegroup/se3.py
@@ -124,7 +124,7 @@ class Se3(Module):
return self._rotation
@property
- def t(self) -> Vector3 | Parameter:
+ def t(self) -> Vector3 | Tensor:
"""Return the underlying translation vector of shape :math:`(B,3)`."""
return self._translation
@@ -134,7 +134,7 @@ class Se3(Module):
return self._rotation
@property
- def translation(self) -> Vector3 | Parameter:
+ def translation(self) -> Vector3 | Tensor:
"""Return the underlying translation vector of shape :math:`(B,3)`."""
return self._translation
@@ -312,7 +312,11 @@ class Se3(Module):
tensor([-1., -1., -1.], requires_grad=True)
"""
r_inv = self.r.inverse()
- return Se3(r_inv, r_inv * (-1 * self.t))
+ _t = -1 * self.t
+ if isinstance(_t, int):
+ raise TypeError('Unexpected integer from `-1 * translation`')
+
+ return Se3(r_inv, r_inv * _t)
@classmethod
def random(cls, batch_size: int | None = None, device: Device | None = None, dtype: Dtype = None) -> Se3:
diff --git a/kornia/geometry/liegroup/so2.py b/kornia/geometry/liegroup/so2.py
index 4f65774e9..92b13cdae 100644
--- a/kornia/geometry/liegroup/so2.py
+++ b/kornia/geometry/liegroup/so2.py
@@ -67,7 +67,7 @@ class So2(Module):
def __mul__(self, right: Tensor) -> Tensor:
...
- def __mul__(self, right):
+ def __mul__(self, right: So2 | Tensor) -> So2 | Tensor:
"""Performs a left-multiplication either rotation concatenation or point-transform.
Args:
diff --git a/kornia/geometry/liegroup/so3.py b/kornia/geometry/liegroup/so3.py
index dc020ce95..d5177e15c 100644
--- a/kornia/geometry/liegroup/so3.py
+++ b/kornia/geometry/liegroup/so3.py
@@ -52,7 +52,7 @@ class So3(Module):
def __getitem__(self, idx: int | slice) -> So3:
return So3(self._q[idx])
- def __mul__(self, right):
+ def __mul__(self, right: So3) -> So3:
"""Compose two So3 transformations.
Args:
@@ -146,7 +146,8 @@ class So3(Module):
"""
# KORNIA_CHECK_SHAPE(v, ["B", "3"]) # FIXME: resolve shape bugs. @edgarriba
if isinstance(v, Tensor):
- a, b, c = v[..., 0], v[..., 1], v[..., 2]
+ # TODO: Figure out why mypy think `v` can be a Vector3 which didn't allow ellipsis on index
+ a, b, c = v[..., 0], v[..., 1], v[..., 2] # type: ignore[index]
else:
a, b, c = v.x, v.y, v.z
z = zeros_like(a)
diff --git a/kornia/geometry/linalg.py b/kornia/geometry/linalg.py
index 676ed1646..ae440983f 100644
--- a/kornia/geometry/linalg.py
+++ b/kornia/geometry/linalg.py
@@ -42,11 +42,8 @@ def compose_transformations(trans_01: Tensor, trans_12: Tensor) -> Tensor:
>>> trans_12 = torch.eye(4) # 4x4
>>> trans_02 = compose_transformations(trans_01, trans_12) # 4x4
"""
- if not torch.is_tensor(trans_01):
- raise TypeError(f"Input trans_01 type is not a Tensor. Got {type(trans_01)}")
-
- if not torch.is_tensor(trans_12):
- raise TypeError(f"Input trans_12 type is not a Tensor. Got {type(trans_12)}")
+ KORNIA_CHECK_IS_TENSOR(trans_01)
+ KORNIA_CHECK_IS_TENSOR(trans_12)
if not ((trans_01.dim() in (2, 3)) and (trans_01.shape[-2:] == (4, 4))):
raise ValueError("Input trans_01 must be a of the shape Nx4x4 or 4x4." " Got {}".format(trans_01.shape))
@@ -97,20 +94,20 @@ def inverse_transformation(trans_12: Tensor) -> Tensor:
>>> trans_12 = torch.rand(1, 4, 4) # Nx4x4
>>> trans_21 = inverse_transformation(trans_12) # Nx4x4
"""
- if not torch.is_tensor(trans_12):
- raise TypeError(f"Input type is not a Tensor. Got {type(trans_12)}")
+ KORNIA_CHECK_IS_TENSOR(trans_12)
+
if not ((trans_12.dim() in (2, 3)) and (trans_12.shape[-2:] == (4, 4))):
raise ValueError(f"Input size must be a Nx4x4 or 4x4. Got {trans_12.shape}")
# unpack input tensor
- rmat_12: Tensor = trans_12[..., :3, 0:3] # Nx3x3
- tvec_12: Tensor = trans_12[..., :3, 3:4] # Nx3x1
+ rmat_12 = trans_12[..., :3, 0:3] # Nx3x3
+ tvec_12 = trans_12[..., :3, 3:4] # Nx3x1
# compute the actual inverse
- rmat_21: Tensor = torch.transpose(rmat_12, -1, -2)
- tvec_21: Tensor = torch.matmul(-rmat_21, tvec_12)
+ rmat_21 = torch.transpose(rmat_12, -1, -2)
+ tvec_21 = torch.matmul(-rmat_21, tvec_12)
# pack to output tensor
- trans_21: Tensor = torch.zeros_like(trans_12)
+ trans_21 = torch.zeros_like(trans_12)
trans_21[..., :3, 0:3] += rmat_21
trans_21[..., :3, -1:] += tvec_21
trans_21[..., -1, -1:] += 1.0
@@ -141,18 +138,17 @@ def relative_transformation(trans_01: Tensor, trans_02: Tensor) -> Tensor:
>>> trans_02 = torch.eye(4) # 4x4
>>> trans_12 = relative_transformation(trans_01, trans_02) # 4x4
"""
- if not torch.is_tensor(trans_01):
- raise TypeError(f"Input trans_01 type is not a Tensor. Got {type(trans_01)}")
- if not torch.is_tensor(trans_02):
- raise TypeError(f"Input trans_02 type is not a Tensor. Got {type(trans_02)}")
+ KORNIA_CHECK_IS_TENSOR(trans_01)
+ KORNIA_CHECK_IS_TENSOR(trans_02)
if not ((trans_01.dim() in (2, 3)) and (trans_01.shape[-2:] == (4, 4))):
raise ValueError("Input must be a of the shape Nx4x4 or 4x4." " Got {}".format(trans_01.shape))
if not ((trans_02.dim() in (2, 3)) and (trans_02.shape[-2:] == (4, 4))):
raise ValueError("Input must be a of the shape Nx4x4 or 4x4." " Got {}".format(trans_02.shape))
if not trans_01.dim() == trans_02.dim():
raise ValueError(f"Input number of dims must match. Got {trans_01.dim()} and {trans_02.dim()}")
- trans_10: Tensor = inverse_transformation(trans_01)
- trans_12: Tensor = compose_transformations(trans_10, trans_02)
+
+ trans_10 = inverse_transformation(trans_01)
+ trans_12 = compose_transformations(trans_10, trans_02)
return trans_12
@@ -160,11 +156,11 @@ def transform_points(trans_01: Tensor, points_1: Tensor) -> Tensor:
r"""Function that applies transformations to a set of points.
Args:
- trans_01 (Tensor): tensor for transformations of shape
+ trans_01: tensor for transformations of shape
:math:`(B, D+1, D+1)`.
- points_1 (Tensor): tensor of points of shape :math:`(B, N, D)`.
+ points_1: tensor of points of shape :math:`(B, N, D)`.
Returns:
- Tensor: tensor of N-dimensional points.
+ a tensor of N-dimensional points.
Shape:
- Output: :math:`(B, N, D)`
diff --git a/kornia/geometry/line.py b/kornia/geometry/line.py
index c120de2c0..d2ee95b63 100644
--- a/kornia/geometry/line.py
+++ b/kornia/geometry/line.py
@@ -1,6 +1,6 @@
# kornia.geometry.line module inspired by Eigen::geometry::ParametrizedLine
# https://gitlab.com/libeigen/eigen/-/blob/master/Eigen/src/Geometry/ParametrizedLine.h
-from typing import Optional, Tuple, Union
+from typing import Iterator, Optional, Tuple, Union
import torch
@@ -49,7 +49,7 @@ class ParametrizedLine(Module):
def __getitem__(self, idx: int) -> Tensor:
return self.origin if idx == 0 else self.direction
- def __iter__(self):
+ def __iter__(self) -> Iterator[Tensor]:
yield from (self.origin, self.direction)
@property
diff --git a/kornia/geometry/plane.py b/kornia/geometry/plane.py
index da76c2884..64089c107 100644
--- a/kornia/geometry/plane.py
+++ b/kornia/geometry/plane.py
@@ -5,7 +5,7 @@ from typing import Optional
from kornia.core import Module, Tensor, stack, where
from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_SHAPE, KORNIA_CHECK_TYPE
-from kornia.core.tensor_wrapper import unwrap, wrap
+from kornia.core.tensor_wrapper import unwrap, wrap # type: ignore[attr-defined]
from kornia.geometry.linalg import batched_dot_product
from kornia.geometry.vector import Scalar, Vector3
from kornia.utils.helpers import _torch_svd_cast
@@ -89,14 +89,14 @@ class Hyperplane(Module):
norm = normal.norm(-1)
# https://gitlab.com/libeigen/eigen/-/blob/master/Eigen/src/Geometry/Hyperplane.h#L108
- def compute_normal_svd(v0, v1):
+ def compute_normal_svd(v0: Tensor, v1: Tensor) -> 'Vector3':
# NOTE: for reason TensorWrapper does not stack well
m = stack((unwrap(v0), unwrap(v1)), -2) # Bx2x3
_, _, V = _torch_svd_cast(m) # kornia solution lies in the last row
return wrap(V[..., :, -1], Vector3) # Bx3
normal_mask = norm <= v0.norm(-1) * v1.norm(-1) * 1e-6
- normal = where(normal_mask, compute_normal_svd(v0, v1), normal / (norm + 1e-6))
+ normal = where(normal_mask, compute_normal_svd(v0, v1).data, normal / (norm + 1e-6))
offset = -batched_dot_product(p0, normal)
return Hyperplane(wrap(normal, Vector3), wrap(offset, Scalar))
diff --git a/kornia/geometry/ransac.py b/kornia/geometry/ransac.py
index 802294675..3a666b1bb 100644
--- a/kornia/geometry/ransac.py
+++ b/kornia/geometry/ransac.py
@@ -43,7 +43,7 @@ class RANSAC(Module):
max_iter: int = 10,
confidence: float = 0.99,
max_lo_iters: int = 5,
- ):
+ ) -> None:
super().__init__()
self.supported_models = ['homography', 'fundamental', 'homography_from_linesegments']
self.inl_th = inl_th
diff --git a/kornia/geometry/subpix/nms.py b/kornia/geometry/subpix/nms.py
index 0fec5c2b1..b93ddfd02 100644
--- a/kornia/geometry/subpix/nms.py
+++ b/kornia/geometry/subpix/nms.py
@@ -31,7 +31,7 @@ class NonMaximaSuppression2d(Module):
"""
kernel: Tensor
- def __init__(self, kernel_size: tuple[int, int]):
+ def __init__(self, kernel_size: tuple[int, int]) -> None:
super().__init__()
self.kernel_size: tuple[int, int] = kernel_size
self.padding: tuple[int, int, int, int] = self._compute_zero_padding2d(kernel_size)
@@ -39,12 +39,13 @@ class NonMaximaSuppression2d(Module):
@staticmethod
def _compute_zero_padding2d(kernel_size: tuple[int, int]) -> tuple[int, int, int, int]:
+ # TODO: This method is duplicated with some utility function on kornia.filters
if not isinstance(kernel_size, tuple):
raise AssertionError(type(kernel_size))
if len(kernel_size) != 2:
raise AssertionError(kernel_size)
- def pad(x):
+ def pad(x: int) -> int:
return (x - 1) // 2 # zero padding function
ky, kx = kernel_size # we assume a cubic kernel
@@ -71,7 +72,7 @@ class NonMaximaSuppression2d(Module):
class NonMaximaSuppression3d(Module):
r"""Apply non maxima suppression to filter."""
- def __init__(self, kernel_size: tuple[int, int, int]):
+ def __init__(self, kernel_size: tuple[int, int, int]) -> None:
super().__init__()
self.kernel_size: tuple[int, int, int] = kernel_size
self.padding: tuple[int, int, int, int, int, int] = self._compute_zero_padding3d(kernel_size)
@@ -79,12 +80,13 @@ class NonMaximaSuppression3d(Module):
@staticmethod
def _compute_zero_padding3d(kernel_size: tuple[int, int, int]) -> tuple[int, int, int, int, int, int]:
+ # TODO: This method is duplicated with some utility function on kornia.filters
if not isinstance(kernel_size, tuple):
raise AssertionError(type(kernel_size))
if len(kernel_size) != 3:
raise AssertionError(kernel_size)
- def pad(x):
+ def pad(x: int) -> int:
return (x - 1) // 2 # zero padding function
kd, ky, kx = kernel_size # we assume a cubic kernel
diff --git a/kornia/geometry/transform/flips.py b/kornia/geometry/transform/flips.py
index d0c66192a..6519725dd 100644
--- a/kornia/geometry/transform/flips.py
+++ b/kornia/geometry/transform/flips.py
@@ -32,7 +32,7 @@ class Vflip(Module):
def forward(self, input: Tensor) -> Tensor:
return vflip(input)
- def __repr__(self):
+ def __repr__(self) -> str:
return self.__class__.__name__
@@ -63,7 +63,7 @@ class Hflip(Module):
def forward(self, input: Tensor) -> Tensor:
return hflip(input)
- def __repr__(self):
+ def __repr__(self) -> str:
return self.__class__.__name__
@@ -91,7 +91,7 @@ class Rot180(Module):
def forward(self, input: Tensor) -> Tensor:
return rot180(input)
- def __repr__(self):
+ def __repr__(self) -> str:
return self.__class__.__name__
diff --git a/kornia/geometry/transform/image_registrator.py b/kornia/geometry/transform/image_registrator.py
index 7d524713c..eb28bc599 100644
--- a/kornia/geometry/transform/image_registrator.py
+++ b/kornia/geometry/transform/image_registrator.py
@@ -40,7 +40,7 @@ class Homography(BaseModel):
def __repr__(self) -> str:
return f'{self.__class__.__name__}({self.model})'
- def reset_model(self):
+ def reset_model(self) -> None:
"""Initializes the model with identity transform."""
torch.nn.init.eye_(self.model)
diff --git a/kornia/geometry/transform/imgwarp.py b/kornia/geometry/transform/imgwarp.py
index 152277b6a..5e5eebc35 100644
--- a/kornia/geometry/transform/imgwarp.py
+++ b/kornia/geometry/transform/imgwarp.py
@@ -815,7 +815,9 @@ def get_shear_matrix3d(
return shear_mat
-def _compute_shear_matrix_3d(sxy_tan, sxz_tan, syx_tan, syz_tan, szx_tan, szy_tan):
+def _compute_shear_matrix_3d(
+ sxy_tan: Tensor, sxz_tan: Tensor, syx_tan: Tensor, syz_tan: Tensor, szx_tan: Tensor, szy_tan: Tensor
+) -> tuple[Tensor, ...]:
ones = torch.ones_like(sxy_tan)
m00, m10, m20 = ones, sxy_tan, sxz_tan
diff --git a/kornia/geometry/transform/pyramid.py b/kornia/geometry/transform/pyramid.py
index f0cf859de..01222ea3a 100644
--- a/kornia/geometry/transform/pyramid.py
+++ b/kornia/geometry/transform/pyramid.py
@@ -92,7 +92,7 @@ class PyrUp(Module):
>>> output = PyrUp()(input) # 1x2x8x8
"""
- def __init__(self, border_type: str = 'reflect', align_corners: bool = False):
+ def __init__(self, border_type: str = 'reflect', align_corners: bool = False) -> None:
super().__init__()
self.border_type: str = border_type
self.align_corners: bool = align_corners
@@ -128,7 +128,9 @@ class ScalePyramid(Module):
>>> sp, sigmas, pds = ScalePyramid(3, 15)(input)
"""
- def __init__(self, n_levels: int = 3, init_sigma: float = 1.6, min_size: int = 15, double_image: bool = False):
+ def __init__(
+ self, n_levels: int = 3, init_sigma: float = 1.6, min_size: int = 15, double_image: bool = False
+ ) -> None:
super().__init__()
# 3 extra levels are needed for DoG nms.
self.n_levels = n_levels
@@ -342,12 +344,12 @@ def build_pyramid(
return pyramid
-def is_powerof_two(x):
+def is_powerof_two(x: int) -> bool:
# check if number x is a power of two
- return x and (not (x & (x - 1)))
+ return bool(x) and (not (x & (x - 1)))
-def find_next_powerof_two(x):
+def find_next_powerof_two(x: int) -> int:
# return the nearest power of 2
n = math.ceil(math.log(x) / math.log(2))
return 2**n
diff --git a/kornia/geometry/vector.py b/kornia/geometry/vector.py
index cceaa6a49..66062bd1b 100644
--- a/kornia/geometry/vector.py
+++ b/kornia/geometry/vector.py
@@ -2,7 +2,7 @@ from typing import Optional, Tuple, Union, cast
from kornia.core import Device, Dtype, Tensor, as_tensor, normalize, rand, stack
from kornia.core.check import KORNIA_CHECK
-from kornia.core.tensor_wrapper import TensorWrapper, wrap
+from kornia.core.tensor_wrapper import TensorWrapper, wrap # type: ignore[attr-defined]
from kornia.geometry.linalg import batched_dot_product, batched_squared_norm
__all__ = ["Vector3", "Vector2", "Scalar"]
diff --git a/kornia/grad_estimator/ste.py b/kornia/grad_estimator/ste.py
index f83642ccc..52857f3a3 100644
--- a/kornia/grad_estimator/ste.py
+++ b/kornia/grad_estimator/ste.py
@@ -104,12 +104,12 @@ class StraightThroughEstimator(nn.Module):
[0.0422, 0.0566, 0.0626, 0.0422]]]])
"""
- def __init__(self, target_fn: nn.Module, grad_fn: Optional[Callable[..., Any]] = None):
+ def __init__(self, target_fn: nn.Module, grad_fn: Optional[Callable[..., Any]] = None) -> None:
super().__init__()
self.target_fn = target_fn
self.grad_fn = grad_fn
- def __repr__(self):
+ def __repr__(self) -> str:
return f"{self.__class__.__name__}(target_fn={self.target_fn}, grad_fn={self.grad_fn})"
def forward(self, input: Tensor) -> Tensor:
diff --git a/kornia/metrics/average_meter.py b/kornia/metrics/average_meter.py
index 4e13a684a..722e678e3 100644
--- a/kornia/metrics/average_meter.py
+++ b/kornia/metrics/average_meter.py
@@ -22,7 +22,7 @@ class AverageMeter:
def __init__(self) -> None:
self.reset()
- def reset(self):
+ def reset(self) -> None:
self.val = 0
self._avg = 0
self.sum = 0
diff --git a/kornia/nerf/rays.py b/kornia/nerf/rays.py
index b758a1103..92e7883a3 100755
--- a/kornia/nerf/rays.py
+++ b/kornia/nerf/rays.py
@@ -81,11 +81,11 @@ class RaySampler:
self._camera_ids = camera_ids
@property
- def points_2d(self):
+ def points_2d(self) -> Tensor:
return self._points_2d
@property
- def camera_ids(self):
+ def camera_ids(self) -> List[int]:
return self._camera_ids
def _calc_ray_params(self, cameras: PinholeCamera, points_2d_camera: Dict[int, Points2D]) -> None:
diff --git a/kornia/testing/__init__.py b/kornia/testing/__init__.py
index 93ea1d9f1..ccadaccfe 100644
--- a/kornia/testing/__init__.py
+++ b/kornia/testing/__init__.py
@@ -4,13 +4,13 @@ import math
from abc import ABC, abstractmethod
from copy import deepcopy
from itertools import product
-from typing import Any, Callable, Dict, Optional, Sequence, Tuple, TypeVar, Union
+from typing import Any, Callable, Dict, Iterator, Optional, Sequence, Tuple, TypeVar, Union
import torch
from torch.autograd import gradcheck
from torch.testing import assert_close as _assert_close
-from kornia.core import Tensor, eye, tensor
+from kornia.core import Device, Dtype, Tensor, eye, tensor
__all__ = ["tensor_to_gradcheck_var", "create_eye_batch", "xla_is_available", "assert_close"]
@@ -28,19 +28,21 @@ def is_mps_tensor_safe(x: Tensor) -> bool:
# TODO: Isn't this function duplicated with eye_like?
-def create_eye_batch(batch_size, eye_size, device=None, dtype=None):
+def create_eye_batch(batch_size: int, eye_size: int, device: Device = None, dtype: Dtype = None) -> Tensor:
"""Create a batch of identity matrices of shape Bx3x3."""
return eye(eye_size, device=device, dtype=dtype).view(1, eye_size, eye_size).expand(batch_size, -1, -1)
-def create_random_homography(batch_size, eye_size, std_val=1e-3):
+def create_random_homography(batch_size: int, eye_size: int, std_val: float = 1e-3) -> Tensor:
"""Create a batch of random homographies of shape Bx3x3."""
std = torch.FloatTensor(batch_size, eye_size, eye_size)
eye = create_eye_batch(batch_size, eye_size)
return eye + std.uniform_(-std_val, std_val)
-def tensor_to_gradcheck_var(tensor, dtype=torch.float64, requires_grad=True):
+def tensor_to_gradcheck_var(
+ tensor: Tensor, dtype: Dtype = torch.float64, requires_grad: bool = True
+) -> Union[Tensor, str]:
"""Convert the input tensor to a valid variable to check the gradient.
`gradcheck` needs 64-bit floating point and requires gradient.
@@ -53,26 +55,26 @@ def tensor_to_gradcheck_var(tensor, dtype=torch.float64, requires_grad=True):
T = TypeVar('T')
-def dict_to(data: Dict[T, Any], device: torch.device, dtype: torch.dtype) -> Dict[T, Any]:
+def dict_to(data: Dict[T, Any], device: Device, dtype: 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
-def compute_patch_error(x, y, h, w):
+def compute_patch_error(x: Tensor, y: Tensor, h: int, w: int) -> Tensor:
"""Compute the absolute error between patches."""
return torch.abs(x - y)[..., h // 4 : -h // 4, w // 4 : -w // 4].mean()
-def create_rectified_fundamental_matrix(batch_size):
+def create_rectified_fundamental_matrix(batch_size: int) -> Tensor:
"""Create a batch of rectified fundamental matrices of shape Bx3x3."""
F_rect = tensor([[0.0, 0.0, 0.0], [0.0, 0.0, -1.0], [0.0, 1.0, 0.0]]).view(1, 3, 3)
F_repeat = F_rect.expand(batch_size, 3, 3)
return F_repeat
-def create_random_fundamental_matrix(batch_size, std_val=1e-3):
+def create_random_fundamental_matrix(batch_size: int, std_val: float = 1e-3) -> Tensor:
"""Create a batch of random fundamental matrices of shape Bx3x3."""
F_rect = create_rectified_fundamental_matrix(batch_size)
H_left = create_random_homography(batch_size, 3, std_val)
@@ -92,27 +94,27 @@ _DTYPE_PRECISIONS = {
class BaseTester(ABC):
@abstractmethod
- def test_smoke(self, device, dtype):
+ def test_smoke(self, device: Device, dtype: Dtype) -> None:
raise NotImplementedError("Implement a stupid routine.")
@abstractmethod
- def test_exception(self, device, dtype):
+ def test_exception(self, device: Device, dtype: Dtype) -> None:
raise NotImplementedError("Implement a stupid routine.")
@abstractmethod
- def test_cardinality(self, device, dtype):
+ def test_cardinality(self, device: Device, dtype: Dtype) -> None:
raise NotImplementedError("Implement a stupid routine.")
# TODO: add @abstractmethod
- def test_dynamo(self, device, dtype, torch_optimizer):
+ def test_dynamo(self, device: Device, dtype: Dtype, torch_optimizer: Callable[..., Any]) -> None:
pass # TODO: raise NotImplementedError -- now we see a bunch of dynamo tests running by inheritance
@abstractmethod
- def test_gradcheck(self, device):
+ def test_gradcheck(self, device: Device) -> None:
raise NotImplementedError("Implement a stupid routine.")
@abstractmethod
- def test_module(self, device, dtype):
+ def test_module(self, device: Device, dtype: Dtype) -> None:
raise NotImplementedError("Implement a stupid routine.")
def assert_close(
@@ -166,7 +168,7 @@ class BaseTester(ABC):
def generate_two_view_random_scene(
- device: torch.device = torch.device("cpu"), dtype: torch.dtype = torch.float32
+ device: Device = torch.device("cpu"), dtype: Dtype = torch.float32
) -> Dict[str, Tensor]:
from kornia.geometry import epipolar as epi
@@ -219,7 +221,7 @@ def generate_two_view_random_scene(
}
-def cartesian_product_of_parameters(**possible_parameters):
+def cartesian_product_of_parameters(**possible_parameters: Sequence[Any]) -> Iterator[Dict[str, Any]]:
"""Create cartesian product of given parameters."""
parameter_names = possible_parameters.keys()
possible_values = [possible_parameters[parameter_name] for parameter_name in parameter_names]
@@ -228,7 +230,7 @@ def cartesian_product_of_parameters(**possible_parameters):
yield dict(zip(parameter_names, param_combination))
-def default_with_one_parameter_changed(*, default={}, **possible_parameters):
+def default_with_one_parameter_changed(*, default: Dict[str, Any] = {}, **possible_parameters: Any) -> Any:
if not isinstance(default, dict):
raise AssertionError(f"default should be a dict not a {type(default)}")
@@ -239,7 +241,7 @@ def default_with_one_parameter_changed(*, default={}, **possible_parameters):
yield param_set
-def _get_precision(device: torch.device, dtype: torch.dtype) -> float:
+def _get_precision(device: torch.device, dtype: Dtype) -> float:
if 'xla' in device.type:
return 1e-2
if dtype == torch.float16:
diff --git a/kornia/utils/image.py b/kornia/utils/image.py
index 2362317a3..282e05753 100644
--- a/kornia/utils/image.py
+++ b/kornia/utils/image.py
@@ -198,7 +198,7 @@ class ImageToTensor(nn.Module):
keepdim: If ``False`` unsqueeze the input image to match the shape :math:`(B, H, W, C)`.
"""
- def __init__(self, keepdim: bool = False):
+ def __init__(self, keepdim: bool = False) -> None:
super().__init__()
self.keepdim = keepdim
diff --git a/kornia/x/trainer.py b/kornia/x/trainer.py
index 6c991b715..e5ec9bcec 100644
--- a/kornia/x/trainer.py
+++ b/kornia/x/trainer.py
@@ -185,7 +185,7 @@ class Trainer:
return stats.as_dict()
- def on_epoch_start(self, *args, **kwargs):
+ def on_epoch_start(self, *args: Any, **kwargs: Any) -> None:
...
def preprocess(self, x: Dict[str, Tensor]) -> Dict[str, Tensor]:
diff --git a/kornia/x/utils.py b/kornia/x/utils.py
index ef00276ff..bcc2c2213 100644
--- a/kornia/x/utils.py
+++ b/kornia/x/utils.py
@@ -1,8 +1,8 @@
from dataclasses import dataclass, field
from enum import Enum
-from typing import Dict, Tuple
+from typing import Any, Callable, Dict, Tuple
-from kornia.core import Module
+from kornia.core import Module, Tensor
from kornia.metrics.average_meter import AverageMeter
# import yaml
@@ -52,11 +52,11 @@ class Lambda(Module):
torch.Size([1, 4, 32, 16])
"""
- def __init__(self, fcn):
+ def __init__(self, fcn: Callable[..., Any]) -> None:
super().__init__()
self.fcn = fcn
- def forward(self, x):
+ def forward(self, x: Tensor) -> Any:
return self.fcn(x)
@@ -67,7 +67,7 @@ class StatsTracker:
self._stats: Dict[str, AverageMeter] = {}
@property
- def stats(self):
+ def stats(self) -> Dict[str, AverageMeter]:
return self._stats
def update(self, key: str, val: float, batch_size: int) -> None:
diff --git a/pyproject.toml b/pyproject.toml
index f192a3fb1..789c21e38 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -183,6 +183,7 @@ exclude_lines = [
check_untyped_defs = true
disallow_any_generics = true
disallow_incomplete_defs = true
+ disallow_untyped_defs = true
files = ["kornia/"]
ignore_missing_imports = true
no_implicit_optional = true