Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

enable `disallow_incomplete_defs` on mypy (#2094)

João Gustavo A. Amorimd680c3773a1e
diff --git a/.github/workflows/pr_test_typing.yml b/.github/workflows/pr_test_typing.yml
index b3b901813..e599264dd 100644
--- a/.github/workflows/pr_test_typing.yml
+++ b/.github/workflows/pr_test_typing.yml
@@ -19,7 +19,7 @@ jobs:
matrix:
os: ['Ubuntu']
python-version: ['3.7']
- pytorch-version: ['1.9.1', '1.13.1']
+ pytorch-version: ['1.13.1']
steps:
- name: Checkout kornia
diff --git a/.github/workflows/scheduled_test_typing.yml b/.github/workflows/scheduled_test_typing.yml
index 63ec1ae07..f01bceadf 100644
--- a/.github/workflows/scheduled_test_typing.yml
+++ b/.github/workflows/scheduled_test_typing.yml
@@ -21,7 +21,7 @@ jobs:
matrix:
os: ['Ubuntu']
python-version: ['3.7']
- pytorch-version: ['1.9.1', '1.10.2', '1.11.0', '1.12.1', '1.13.1', 'nightly']
+ pytorch-version: ['1.13.1', 'nightly']
steps:
- name: Checkout kornia
diff --git a/kornia/augmentation/_2d/base.py b/kornia/augmentation/_2d/base.py
index 3807d6e56..d022fc6e9 100644
--- a/kornia/augmentation/_2d/base.py
+++ b/kornia/augmentation/_2d/base.py
@@ -61,7 +61,7 @@ class RigidAffineAugmentationBase2D(AugmentationBase2D):
def transform_matrix(self) -> Optional[Tensor]:
return self._transform_matrix
- def identity_matrix(self, input) -> Tensor:
+ def identity_matrix(self, input: Tensor) -> Tensor:
"""Return 3x3 identity matrix."""
return eye_like(3, input)
diff --git a/kornia/augmentation/_2d/geometric/base.py b/kornia/augmentation/_2d/geometric/base.py
index 119f7c360..a1e0d3178 100644
--- a/kornia/augmentation/_2d/geometric/base.py
+++ b/kornia/augmentation/_2d/geometric/base.py
@@ -31,7 +31,7 @@ class GeometricAugmentationBase2D(RigidAffineAugmentationBase2D):
"""By default, the exact transformation as ``apply_transform`` will be used."""
raise NotImplementedError
- def compute_inverse_transformation(self, transform: Tensor):
+ def compute_inverse_transformation(self, transform: Tensor) -> Tensor:
"""Compute the inverse transform of given transformation matrices."""
return _torch_inverse_cast(transform)
@@ -127,7 +127,7 @@ class GeometricAugmentationBase2D(RigidAffineAugmentationBase2D):
params: Dict[str, Tensor],
flags: Dict[str, Any],
transform: Optional[Tensor] = None,
- **kwargs,
+ **kwargs: Any,
) -> Tensor:
in_tensor = self.transform_tensor(input)
output = in_tensor.clone()
@@ -165,7 +165,7 @@ class GeometricAugmentationBase2D(RigidAffineAugmentationBase2D):
params: Dict[str, Tensor],
flags: Dict[str, Any],
transform: Optional[Tensor] = None,
- **kwargs,
+ **kwargs: Any,
) -> Tensor:
resample_method: Optional[Resample] = None
if "resample" in flags:
@@ -182,7 +182,7 @@ class GeometricAugmentationBase2D(RigidAffineAugmentationBase2D):
params: Dict[str, Tensor],
flags: Dict[str, Any],
transform: Optional[Tensor] = None,
- **kwargs,
+ **kwargs: Any,
) -> Boxes:
output = input.clone()
batch_prob = params['batch_prob']
@@ -212,7 +212,7 @@ class GeometricAugmentationBase2D(RigidAffineAugmentationBase2D):
params: Dict[str, Tensor],
flags: Dict[str, Any],
transform: Optional[Tensor] = None,
- **kwargs,
+ **kwargs: Any,
) -> Keypoints:
"""Inverse the transformation on keypoints.
@@ -250,11 +250,11 @@ class GeometricAugmentationBase2D(RigidAffineAugmentationBase2D):
params: Dict[str, Tensor],
flags: Dict[str, Any],
transform: Optional[Tensor] = None,
- **kwargs,
+ **kwargs: Any,
) -> Tensor:
return input
- def inverse(self, input: Tensor, params: Optional[Dict[str, Tensor]] = None, **kwargs) -> Tensor:
+ def inverse(self, input: Tensor, params: Optional[Dict[str, Tensor]] = None, **kwargs: Any) -> Tensor:
"""Perform inverse operations.
Args:
diff --git a/kornia/augmentation/_2d/geometric/center_crop.py b/kornia/augmentation/_2d/geometric/center_crop.py
index 9b6f97359..22f26b562 100644
--- a/kornia/augmentation/_2d/geometric/center_crop.py
+++ b/kornia/augmentation/_2d/geometric/center_crop.py
@@ -1,11 +1,9 @@
from typing import Any, Dict, Optional, Tuple, Union
-import torch
-from torch import Tensor
-
from kornia.augmentation import random_generator as rg
from kornia.augmentation._2d.geometric.base import GeometricAugmentationBase2D
from kornia.constants import Resample
+from kornia.core import Tensor
from kornia.geometry.transform import crop_by_indices, crop_by_transform_mat, get_perspective_transform
@@ -89,7 +87,7 @@ class CenterCrop(GeometricAugmentationBase2D):
padding_mode="zeros",
)
- def generate_parameters(self, batch_shape: torch.Size) -> Dict[str, Tensor]:
+ def generate_parameters(self, batch_shape: Tuple[int, ...]) -> Dict[str, Tensor]:
return rg.center_crop_generator(batch_shape[0], batch_shape[-2], batch_shape[-1], self.size, self.device)
def compute_transformation(self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Tensor:
diff --git a/kornia/augmentation/_2d/geometric/crop.py b/kornia/augmentation/_2d/geometric/crop.py
index f90b60de0..df1463f9d 100644
--- a/kornia/augmentation/_2d/geometric/crop.py
+++ b/kornia/augmentation/_2d/geometric/crop.py
@@ -100,7 +100,7 @@ class RandomCrop(GeometricAugmentationBase2D):
cropping_mode=cropping_mode,
)
- def compute_padding(self, shape: torch.Size, flags: Optional[Dict[str, Any]] = None) -> List[int]:
+ def compute_padding(self, shape: Tuple[int, ...], flags: Optional[Dict[str, Any]] = None) -> List[int]:
flags = self.flags if flags is None else flags
if len(shape) != 4:
raise AssertionError(f"Expected BCHW. Got {shape}.")
@@ -242,7 +242,7 @@ class RandomCrop(GeometricAugmentationBase2D):
params: Dict[str, Tensor],
flags: Dict[str, Any],
transform: Optional[Tensor] = None,
- **kwargs,
+ **kwargs: Any,
) -> Tensor:
if flags["cropping_mode"] != "resample":
raise NotImplementedError(
@@ -261,7 +261,7 @@ class RandomCrop(GeometricAugmentationBase2D):
params: Dict[str, Tensor],
flags: Dict[str, Any],
transform: Optional[Tensor] = None,
- **kwargs,
+ **kwargs: Any,
) -> Boxes:
if flags["cropping_mode"] != "resample":
raise NotImplementedError(
@@ -279,7 +279,7 @@ class RandomCrop(GeometricAugmentationBase2D):
params: Dict[str, Tensor],
flags: Dict[str, Any],
transform: Optional[Tensor] = None,
- **kwargs,
+ **kwargs: Any,
) -> Keypoints:
if flags["cropping_mode"] != "resample":
raise NotImplementedError(
@@ -292,12 +292,14 @@ class RandomCrop(GeometricAugmentationBase2D):
return output.unpad(params["padding_size"].to(device=input.device))
# Override parameters for precrop
- def forward_parameters(self, batch_shape) -> Dict[str, Tensor]:
+ def forward_parameters(self, batch_shape: Tuple[int, ...]) -> Dict[str, Tensor]:
input_pad = self.compute_padding(batch_shape)
- batch_shape_new = (
- *batch_shape[:2],
- batch_shape[2] + input_pad[2] + input_pad[3], # original height + top + bottom padding
- batch_shape[3] + input_pad[0] + input_pad[1], # original width + left + right padding
+ batch_shape_new = torch.Size(
+ (
+ *batch_shape[:2],
+ batch_shape[2] + input_pad[2] + input_pad[3], # original height + top + bottom padding
+ batch_shape[3] + input_pad[0] + input_pad[1], # original width + left + right padding
+ )
)
padding_size = tensor(tuple(input_pad), dtype=torch.long).expand(batch_shape[0], -1)
_params = super().forward_parameters(batch_shape_new)
diff --git a/kornia/augmentation/_2d/geometric/elastic_transform.py b/kornia/augmentation/_2d/geometric/elastic_transform.py
index 4bb102b10..0841fa412 100644
--- a/kornia/augmentation/_2d/geometric/elastic_transform.py
+++ b/kornia/augmentation/_2d/geometric/elastic_transform.py
@@ -1,10 +1,10 @@
from typing import Any, Dict, Optional, Tuple, Union
import torch
-from torch import Tensor
from kornia.augmentation._2d.base import AugmentationBase2D
from kornia.constants import Resample
+from kornia.core import Tensor
from kornia.geometry.boxes import Boxes
from kornia.geometry.transform import elastic_transform2d
@@ -70,7 +70,7 @@ class RandomElasticTransform(AugmentationBase2D):
padding_mode=padding_mode,
)
- def generate_parameters(self, shape: torch.Size) -> Dict[str, Tensor]:
+ def generate_parameters(self, shape: Tuple[int, ...]) -> Dict[str, Tensor]:
B, _, H, W = shape
if self.same_on_batch:
noise = torch.rand(1, 2, H, W, device=self.device, dtype=self.dtype).expand(B, 2, H, W)
diff --git a/kornia/augmentation/_2d/geometric/thin_plate_spline.py b/kornia/augmentation/_2d/geometric/thin_plate_spline.py
index b4526b21f..0aa2f1f1c 100644
--- a/kornia/augmentation/_2d/geometric/thin_plate_spline.py
+++ b/kornia/augmentation/_2d/geometric/thin_plate_spline.py
@@ -1,4 +1,4 @@
-from typing import Any, Dict, Optional
+from typing import Any, Dict, Optional, Tuple
import torch
@@ -49,7 +49,7 @@ class RandomThinPlateSpline(AugmentationBase2D):
self.flags = dict(align_corners=align_corners)
self.dist = torch.distributions.Uniform(-scale, scale)
- def generate_parameters(self, shape: torch.Size) -> Dict[str, Tensor]:
+ def generate_parameters(self, shape: Tuple[int, ...]) -> Dict[str, Tensor]:
B, _, _, _ = shape
src = tensor([[[-1.0, -1.0], [-1.0, 1.0], [1.0, -1.0], [1.0, 1.0], [0.0, 0.0]]]).expand(B, 5, 2) # Bx5x2
dst = src + self.dist.rsample(src.shape)
diff --git a/kornia/augmentation/_2d/intensity/channel_shuffle.py b/kornia/augmentation/_2d/intensity/channel_shuffle.py
index ad69ae850..72ece0537 100644
--- a/kornia/augmentation/_2d/intensity/channel_shuffle.py
+++ b/kornia/augmentation/_2d/intensity/channel_shuffle.py
@@ -1,9 +1,9 @@
-from typing import Any, Dict, Optional
+from typing import Any, Dict, Optional, Tuple
import torch
-from torch import Tensor
from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D
+from kornia.core import Tensor
class RandomChannelShuffle(IntensityAugmentationBase2D):
@@ -37,7 +37,7 @@ class RandomChannelShuffle(IntensityAugmentationBase2D):
def __init__(self, same_on_batch: bool = False, p: float = 0.5, keepdim: bool = False) -> None:
super().__init__(p=p, same_on_batch=same_on_batch, p_batch=1.0, keepdim=keepdim)
- def generate_parameters(self, shape: torch.Size) -> Dict[str, Tensor]:
+ def generate_parameters(self, shape: Tuple[int, ...]) -> Dict[str, Tensor]:
B, C, _, _ = shape
channels = torch.rand(B, C).argsort(dim=1)
return dict(channels=channels)
diff --git a/kornia/augmentation/_2d/intensity/gaussian_noise.py b/kornia/augmentation/_2d/intensity/gaussian_noise.py
index 433bada9e..bed3e5ff7 100644
--- a/kornia/augmentation/_2d/intensity/gaussian_noise.py
+++ b/kornia/augmentation/_2d/intensity/gaussian_noise.py
@@ -1,9 +1,9 @@
-from typing import Any, Dict, Optional
+from typing import Any, Dict, Optional, Tuple
import torch
-from torch import Tensor
from kornia.augmentation._2d.intensity.base import IntensityAugmentationBase2D
+from kornia.core import Tensor
def _randn_like(input: Tensor, mean: float, std: float) -> Tensor:
@@ -47,7 +47,7 @@ class RandomGaussianNoise(IntensityAugmentationBase2D):
super().__init__(p=p, same_on_batch=same_on_batch, p_batch=1.0, keepdim=keepdim)
self.flags = dict(mean=mean, std=std)
- def generate_parameters(self, shape: torch.Size) -> Dict[str, Tensor]:
+ def generate_parameters(self, shape: Tuple[int, ...]) -> Dict[str, Tensor]:
return {}
def apply_transform(
diff --git a/kornia/augmentation/_2d/intensity/motion_blur.py b/kornia/augmentation/_2d/intensity/motion_blur.py
index 91d554637..0a8176fc8 100644
--- a/kornia/augmentation/_2d/intensity/motion_blur.py
+++ b/kornia/augmentation/_2d/intensity/motion_blur.py
@@ -80,7 +80,7 @@ class RandomMotionBlur(IntensityAugmentationBase2D):
self._param_generator = rg.MotionBlurGenerator(kernel_size, angle, direction)
self.flags = dict(border_type=BorderType.get(border_type), resample=Resample.get(resample))
- def generate_parameters(self, batch_shape: torch.Size) -> Dict[str, Tensor]:
+ def generate_parameters(self, batch_shape: Tuple[int, ...]) -> Dict[str, Tensor]:
params = super().generate_parameters(batch_shape)
params["idx"] = tensor([0]) if batch_shape[0] == 0 else torch.randint(batch_shape[0], (1,))
return params
diff --git a/kornia/augmentation/_3d/base.py b/kornia/augmentation/_3d/base.py
index 169f6c65e..bc76a64c7 100644
--- a/kornia/augmentation/_3d/base.py
+++ b/kornia/augmentation/_3d/base.py
@@ -32,7 +32,7 @@ class AugmentationBase3D(_AugmentationBase):
_validate_input_dtype(input, accepted_dtypes=[float16, float32, float64])
return _transform_input3d(input)
- def identity_matrix(self, input) -> Tensor:
+ def identity_matrix(self, input: Tensor) -> Tensor:
"""Return 4x4 identity matrix."""
return kornia.eye_like(4, input)
diff --git a/kornia/augmentation/_3d/geometric/center_crop.py b/kornia/augmentation/_3d/geometric/center_crop.py
index fe8b63008..e7d2308e2 100644
--- a/kornia/augmentation/_3d/geometric/center_crop.py
+++ b/kornia/augmentation/_3d/geometric/center_crop.py
@@ -1,10 +1,9 @@
from typing import Any, Dict, Optional, Tuple, Union, cast
-from torch import Size, Tensor
-
from kornia.augmentation import random_generator as rg
from kornia.augmentation._3d.geometric.base import GeometricAugmentationBase3D
from kornia.constants import Resample
+from kornia.core import Tensor
from kornia.geometry import crop_by_transform_mat3d, get_perspective_transform3d
@@ -78,7 +77,7 @@ class CenterCrop3D(GeometricAugmentationBase3D):
raise Exception(f"Invalid size type. Expected (int, tuple(int, int int). Got: {size}.")
self.flags = dict(align_corners=align_corners, resample=Resample.get(resample))
- def generate_parameters(self, batch_shape: Size) -> Dict[str, Tensor]:
+ def generate_parameters(self, batch_shape: Tuple[int, ...]) -> Dict[str, Tensor]:
return rg.center_crop_generator3d(
batch_shape[0], batch_shape[-3], batch_shape[-2], batch_shape[-1], self.size, device=self.device
)
diff --git a/kornia/augmentation/_3d/geometric/crop.py b/kornia/augmentation/_3d/geometric/crop.py
index 3def111b4..77558a01c 100644
--- a/kornia/augmentation/_3d/geometric/crop.py
+++ b/kornia/augmentation/_3d/geometric/crop.py
@@ -131,7 +131,7 @@ class RandomCrop3D(GeometricAugmentationBase3D):
input, transform, flags["size"], mode=flags["resample"].name.lower(), align_corners=flags["align_corners"]
)
- def forward(self, input: Tensor, params: Optional[Dict[str, Tensor]] = None, **kwargs) -> Tensor:
+ def forward(self, input: Tensor, params: Optional[Dict[str, Tensor]] = None, **kwargs: Any) -> Tensor:
# TODO: need to align 2D implementations
input = self.precrop_padding(input)
return super().forward(input, params)
diff --git a/kornia/augmentation/base.py b/kornia/augmentation/base.py
index 32a98115b..3c8e34f5d 100644
--- a/kornia/augmentation/base.py
+++ b/kornia/augmentation/base.py
@@ -23,7 +23,7 @@ TensorWithTransformMat = Union[Tensor, Tuple[Tensor, Tensor]]
# forward as a value, rather than a function. See also
# https://github.com/python/mypy/issues/8795
# Based on the trick that torch.nn.Module does for the forward method
-def _apply_transform_unimplemented(self, *input: Any) -> Tensor:
+def _apply_transform_unimplemented(self: Module, *input: Any) -> Tensor:
r"""Defines the computation performed at every call.
Should be overridden by all subclasses.
@@ -99,7 +99,7 @@ class _BasicAugmentationBase(Module):
"""Standardize output tensors."""
return _transform_output_shape(output, output_shape) if self.keepdim else output
- def generate_parameters(self, batch_shape: torch.Size) -> Dict[str, Tensor]:
+ def generate_parameters(self, batch_shape: Tuple[int, ...]) -> Dict[str, Tensor]:
if self._param_generator is not None:
return self._param_generator(batch_shape, self.same_on_batch)
return {}
@@ -116,7 +116,7 @@ class _BasicAugmentationBase(Module):
self._param_generator.set_rng_device_and_dtype(device, dtype)
def __batch_prob_generator__(
- self, batch_shape: torch.Size, p: float, p_batch: float, same_on_batch: bool
+ self, batch_shape: Tuple[int, ...], p: float, p_batch: float, same_on_batch: bool
) -> Tensor:
batch_prob: Tensor
if p_batch == 1:
@@ -149,7 +149,7 @@ class _BasicAugmentationBase(Module):
return batch_prob
def _process_kwargs_to_params_and_flags(
- self, params: Optional[Dict[str, Tensor]] = None, flags: Optional[Dict[str, Any]] = None, **kwargs
+ self, params: Optional[Dict[str, Tensor]] = None, flags: Optional[Dict[str, Any]] = None, **kwargs: Any
) -> Tuple[Dict[str, Tensor], Dict[str, Any]]:
# NOTE: determine how to save self._params
save_kwargs = kwargs["save_kwargs"] if "save_kwargs" in kwargs else False
@@ -167,7 +167,7 @@ class _BasicAugmentationBase(Module):
flags = override_parameters(flags, kwargs, in_place=False)
return params, flags
- def forward_parameters(self, batch_shape) -> Dict[str, Tensor]:
+ def forward_parameters(self, batch_shape: Tuple[int, ...]) -> Dict[str, Tensor]:
batch_prob = self.__batch_prob_generator__(batch_shape, self.p, self.p_batch, self.same_on_batch)
to_apply = batch_prob > 0.5
_params = self.generate_parameters(torch.Size((int(to_apply.sum().item()), *batch_shape[1:])))
@@ -183,7 +183,7 @@ class _BasicAugmentationBase(Module):
def apply_func(self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Tensor:
return self.apply_transform(input, params, flags)
- def forward(self, input: Tensor, params: Optional[Dict[str, Tensor]] = None, **kwargs) -> Tensor:
+ def forward(self, input: Tensor, params: Optional[Dict[str, Tensor]] = None, **kwargs: Any) -> Tensor:
"""Perform forward operations.
Args:
@@ -247,7 +247,7 @@ class _AugmentationBase(_BasicAugmentationBase):
params: Dict[str, Tensor],
flags: Dict[str, Any],
transform: Optional[Tensor] = None,
- **kwargs,
+ **kwargs: Any,
) -> Tensor:
self.validate_tensor(input)
@@ -285,7 +285,7 @@ class _AugmentationBase(_BasicAugmentationBase):
params: Dict[str, Tensor],
flags: Dict[str, Any],
transform: Optional[Tensor] = None,
- **kwargs,
+ **kwargs: Any,
) -> Tensor:
self.validate_tensor(input)
@@ -316,7 +316,7 @@ class _AugmentationBase(_BasicAugmentationBase):
params: Dict[str, Tensor],
flags: Dict[str, Any],
transform: Optional[Tensor] = None,
- **kwargs,
+ **kwargs: Any,
) -> Boxes:
if not isinstance(input, Boxes):
raise RuntimeError(f"Only `Boxes` is supported. Got {type(input)}.")
@@ -350,7 +350,7 @@ class _AugmentationBase(_BasicAugmentationBase):
params: Dict[str, Tensor],
flags: Dict[str, Any],
transform: Optional[Tensor] = None,
- **kwargs,
+ **kwargs: Any,
) -> Keypoints:
if not isinstance(input, Keypoints):
raise RuntimeError(f"Only `Keypoints` is supported. Got {type(input)}.")
@@ -382,7 +382,7 @@ class _AugmentationBase(_BasicAugmentationBase):
params: Dict[str, Tensor],
flags: Dict[str, Any],
transform: Optional[Tensor] = None,
- **kwargs,
+ **kwargs: Any,
) -> Tensor:
params, flags = self._process_kwargs_to_params_and_flags(
self._params if params is None else params, flags, **kwargs
diff --git a/kornia/augmentation/container/augment.py b/kornia/augmentation/container/augment.py
index 406ef8601..3557015d2 100644
--- a/kornia/augmentation/container/augment.py
+++ b/kornia/augmentation/container/augment.py
@@ -284,7 +284,7 @@ class AugmentationSequential(ImageSequential):
return outputs
- def _validate_args_datakeys(self, *args: DataType, data_keys: List[DataKey]):
+ def _validate_args_datakeys(self, *args: DataType, data_keys: List[DataKey]) -> None:
if len(args) != len(data_keys):
raise AssertionError(
f"The number of inputs must align with the number of data_keys. Got {len(args)} and {len(data_keys)}."
diff --git a/kornia/augmentation/container/base.py b/kornia/augmentation/container/base.py
index 11fe60dd0..d96c8ca27 100644
--- a/kornia/augmentation/container/base.py
+++ b/kornia/augmentation/container/base.py
@@ -164,7 +164,7 @@ class SequentialBase(BasicSequentialBase):
class ImageSequentialBase(SequentialBase):
- def identity_matrix(self, input) -> Tensor:
+ def identity_matrix(self, input: Tensor) -> Tensor:
"""Return identity matrix."""
raise NotImplementedError
diff --git a/kornia/augmentation/container/image.py b/kornia/augmentation/container/image.py
index e520b55e2..d41828af1 100644
--- a/kornia/augmentation/container/image.py
+++ b/kornia/augmentation/container/image.py
@@ -204,7 +204,7 @@ class ImageSequential(ImageSequentialBase):
params.append(param)
return params
- def identity_matrix(self, input) -> Tensor:
+ def identity_matrix(self, input: Tensor) -> Tensor:
"""Return identity matrix."""
return eye_like(3, input)
diff --git a/kornia/augmentation/container/params.py b/kornia/augmentation/container/params.py
index c4e6b8079..93ae7d778 100644
--- a/kornia/augmentation/container/params.py
+++ b/kornia/augmentation/container/params.py
@@ -7,8 +7,7 @@ __all__ = ["ParamItem", "PatchParamItem"]
class ParamItem(NamedTuple):
name: str
- # TODO: add type List['ParamItem'] when mypy > 0.991 be available (see python/mypy#14200)
- data: Optional[Union[Dict[str, Tensor], List]] # type: ignore [type-arg]
+ data: Optional[Union[Dict[str, Tensor], List['ParamItem']]]
class PatchParamItem(NamedTuple):
diff --git a/kornia/augmentation/random_generator/_2d/affine.py b/kornia/augmentation/random_generator/_2d/affine.py
index 191a50e43..42f307723 100644
--- a/kornia/augmentation/random_generator/_2d/affine.py
+++ b/kornia/augmentation/random_generator/_2d/affine.py
@@ -133,7 +133,7 @@ class AffineGenerator(RandomGeneratorBase):
self.shear_x_sampler = shear_x_sampler
self.shear_y_sampler = shear_y_sampler
- def forward(self, batch_shape: torch.Size, same_on_batch: bool = False) -> Dict[str, Tensor]:
+ def forward(self, batch_shape: Tuple[int, ...], same_on_batch: bool = False) -> Dict[str, Tensor]:
batch_size = batch_shape[0]
height = batch_shape[-2]
width = batch_shape[-1]
diff --git a/kornia/augmentation/random_generator/_2d/color_jiggle.py b/kornia/augmentation/random_generator/_2d/color_jiggle.py
index dbb44f610..2004dde4c 100644
--- a/kornia/augmentation/random_generator/_2d/color_jiggle.py
+++ b/kornia/augmentation/random_generator/_2d/color_jiggle.py
@@ -73,7 +73,7 @@ class ColorJiggleGenerator(RandomGeneratorBase):
self.saturation_sampler = Uniform(saturation[0], saturation[1], validate_args=False)
self.randperm = partial(torch.randperm, device=device, dtype=dtype)
- def forward(self, batch_shape: torch.Size, same_on_batch: bool = False) -> Dict[str, Tensor]:
+ def forward(self, batch_shape: Tuple[int, ...], same_on_batch: bool = False) -> Dict[str, Tensor]:
batch_size = batch_shape[0]
_common_param_check(batch_size, same_on_batch)
_device, _dtype = _extract_device_dtype([self.brightness, self.contrast, self.hue, self.saturation])
diff --git a/kornia/augmentation/random_generator/_2d/color_jitter.py b/kornia/augmentation/random_generator/_2d/color_jitter.py
index f0d1bdaae..31f92a020 100644
--- a/kornia/augmentation/random_generator/_2d/color_jitter.py
+++ b/kornia/augmentation/random_generator/_2d/color_jitter.py
@@ -77,7 +77,7 @@ class ColorJitterGenerator(RandomGeneratorBase):
self.saturation_sampler = Uniform(saturation[0], saturation[1], validate_args=False)
self.randperm = partial(torch.randperm, device=device, dtype=dtype)
- def forward(self, batch_shape: torch.Size, same_on_batch: bool = False) -> Dict[str, Tensor]:
+ def forward(self, batch_shape: Tuple[int, ...], same_on_batch: bool = False) -> Dict[str, Tensor]:
batch_size = batch_shape[0]
_common_param_check(batch_size, same_on_batch)
_device, _dtype = _extract_device_dtype([self.brightness, self.contrast, self.hue, self.saturation])
diff --git a/kornia/augmentation/random_generator/_2d/crop.py b/kornia/augmentation/random_generator/_2d/crop.py
index 7e4a97b88..944826964 100644
--- a/kornia/augmentation/random_generator/_2d/crop.py
+++ b/kornia/augmentation/random_generator/_2d/crop.py
@@ -45,7 +45,7 @@ class CropGenerator(RandomGeneratorBase):
def make_samplers(self, device: torch.device, dtype: torch.dtype) -> None:
self.rand_sampler = Uniform(tensor(0.0, device=device, dtype=dtype), tensor(1.0, device=device, dtype=dtype))
- def forward(self, batch_shape: torch.Size, same_on_batch: bool = False) -> Dict[str, Tensor]:
+ def forward(self, batch_shape: Tuple[int, ...], same_on_batch: bool = False) -> Dict[str, Tensor]:
batch_size = batch_shape[0]
_common_param_check(batch_size, same_on_batch)
_device, _dtype = _extract_device_dtype([self.size if isinstance(self.size, Tensor) else None])
@@ -196,7 +196,7 @@ class ResizedCropGenerator(CropGenerator):
self.rand_sampler = Uniform(tensor(0.0, device=device, dtype=dtype), tensor(1.0, device=device, dtype=dtype))
self.log_ratio_sampler = Uniform(torch.log(ratio[0]), torch.log(ratio[1]), validate_args=False)
- def forward(self, batch_shape: torch.Size, same_on_batch: bool = False) -> Dict[str, Tensor]:
+ def forward(self, batch_shape: Tuple[int, ...], same_on_batch: bool = False) -> Dict[str, Tensor]:
batch_size = batch_shape[0]
size = (batch_shape[-2], batch_shape[-1])
_device, _dtype = _extract_device_dtype([self.scale, self.ratio])
diff --git a/kornia/augmentation/random_generator/_2d/cutmix.py b/kornia/augmentation/random_generator/_2d/cutmix.py
index 78a3691d4..8e7470460 100644
--- a/kornia/augmentation/random_generator/_2d/cutmix.py
+++ b/kornia/augmentation/random_generator/_2d/cutmix.py
@@ -75,7 +75,7 @@ class CutmixGenerator(RandomGeneratorBase):
tensor(0.0, device=device, dtype=dtype), tensor(1.0, device=device, dtype=dtype), validate_args=False
)
- def forward(self, batch_shape: torch.Size, same_on_batch: bool = False) -> Dict[str, torch.Tensor]:
+ def forward(self, batch_shape: Tuple[int, ...], same_on_batch: bool = False) -> Dict[str, torch.Tensor]:
batch_size = batch_shape[0]
height = batch_shape[-2]
width = batch_shape[-1]
diff --git a/kornia/augmentation/random_generator/_2d/gaussian_blur.py b/kornia/augmentation/random_generator/_2d/gaussian_blur.py
index 6c179f24d..7d61773f1 100644
--- a/kornia/augmentation/random_generator/_2d/gaussian_blur.py
+++ b/kornia/augmentation/random_generator/_2d/gaussian_blur.py
@@ -48,7 +48,7 @@ class RandomGaussianBlurGenerator(RandomGeneratorBase):
self.sigma_sampler = Uniform(sigma[0], sigma[1], validate_args=False)
- def forward(self, batch_shape: torch.Size, same_on_batch: bool = False) -> Dict[str, Tensor]:
+ def forward(self, batch_shape: Tuple[int, ...], same_on_batch: bool = False) -> Dict[str, Tensor]:
batch_size = batch_shape[0]
_common_param_check(batch_size, same_on_batch)
_device, _dtype = _extract_device_dtype([self.sigma])
diff --git a/kornia/augmentation/random_generator/_2d/jigsaw.py b/kornia/augmentation/random_generator/_2d/jigsaw.py
index 781b724b8..7080ce18f 100644
--- a/kornia/augmentation/random_generator/_2d/jigsaw.py
+++ b/kornia/augmentation/random_generator/_2d/jigsaw.py
@@ -39,7 +39,7 @@ class JigsawGenerator(RandomGeneratorBase):
self._device = device
self._dtype = dtype
- def forward(self, batch_shape: torch.Size, same_on_batch: bool = False) -> Dict[str, torch.Tensor]:
+ def forward(self, batch_shape: Tuple[int, ...], same_on_batch: bool = False) -> Dict[str, torch.Tensor]:
batch_size = batch_shape[0]
_common_param_check(batch_size, same_on_batch)
diff --git a/kornia/augmentation/random_generator/_2d/mixup.py b/kornia/augmentation/random_generator/_2d/mixup.py
index 2e240cb7d..75edb2844 100644
--- a/kornia/augmentation/random_generator/_2d/mixup.py
+++ b/kornia/augmentation/random_generator/_2d/mixup.py
@@ -47,7 +47,7 @@ class MixupGenerator(RandomGeneratorBase):
self.lambda_sampler = Uniform(lambda_val[0], lambda_val[1], validate_args=False)
self.prob_sampler = Bernoulli(torch.tensor(float(self.p), device=device, dtype=dtype))
- def forward(self, batch_shape: torch.Size, same_on_batch: bool = False) -> Dict[str, torch.Tensor]:
+ def forward(self, batch_shape: Tuple[int, ...], same_on_batch: bool = False) -> Dict[str, torch.Tensor]:
batch_size = batch_shape[0]
_common_param_check(batch_size, same_on_batch)
diff --git a/kornia/augmentation/random_generator/_2d/mosaic.py b/kornia/augmentation/random_generator/_2d/mosaic.py
index a3899416e..988db79d6 100644
--- a/kornia/augmentation/random_generator/_2d/mosaic.py
+++ b/kornia/augmentation/random_generator/_2d/mosaic.py
@@ -59,7 +59,7 @@ class MosaicGenerator(RandomGeneratorBase):
validate_args=False,
)
- def forward(self, batch_shape: torch.Size, same_on_batch: bool = False) -> Dict[str, torch.Tensor]:
+ def forward(self, batch_shape: Tuple[int, ...], same_on_batch: bool = False) -> Dict[str, torch.Tensor]:
batch_size = batch_shape[0]
input_sizes = (batch_shape[-2], batch_shape[-1])
# output_size = input_sizes if self.output_size is None else self.output_size
diff --git a/kornia/augmentation/random_generator/_2d/motion_blur.py b/kornia/augmentation/random_generator/_2d/motion_blur.py
index d9fc48969..06a02aaea 100644
--- a/kornia/augmentation/random_generator/_2d/motion_blur.py
+++ b/kornia/augmentation/random_generator/_2d/motion_blur.py
@@ -72,7 +72,7 @@ class MotionBlurGenerator(RandomGeneratorBase):
self.angle_sampler = Uniform(angle[0], angle[1], validate_args=False)
self.direction_sampler = Uniform(direction[0], direction[1], validate_args=False)
- def forward(self, batch_shape: torch.Size, same_on_batch: bool = False) -> Dict[str, Tensor]:
+ def forward(self, batch_shape: Tuple[int, ...], same_on_batch: bool = False) -> Dict[str, Tensor]:
batch_size = batch_shape[0]
_common_param_check(batch_size, same_on_batch)
# self.ksize_factor.expand((batch_size, -1))
diff --git a/kornia/augmentation/random_generator/_2d/perspective.py b/kornia/augmentation/random_generator/_2d/perspective.py
index 2ec49f690..e7ae0aba8 100644
--- a/kornia/augmentation/random_generator/_2d/perspective.py
+++ b/kornia/augmentation/random_generator/_2d/perspective.py
@@ -1,4 +1,4 @@
-from typing import Dict, Union
+from typing import Dict, Tuple, Union
import torch
from torch.distributions import Uniform
@@ -51,7 +51,7 @@ class PerspectiveGenerator(RandomGeneratorBase):
tensor(0, device=device, dtype=dtype), tensor(1, device=device, dtype=dtype), validate_args=False
)
- def forward(self, batch_shape: torch.Size, same_on_batch: bool = False) -> Dict[str, Tensor]:
+ def forward(self, batch_shape: Tuple[int, ...], same_on_batch: bool = False) -> Dict[str, Tensor]:
batch_size = batch_shape[0]
height = batch_shape[-2]
width = batch_shape[-1]
diff --git a/kornia/augmentation/random_generator/_2d/plain_uniform.py b/kornia/augmentation/random_generator/_2d/plain_uniform.py
index 14cf7c03f..1ea1d2d58 100644
--- a/kornia/augmentation/random_generator/_2d/plain_uniform.py
+++ b/kornia/augmentation/random_generator/_2d/plain_uniform.py
@@ -73,7 +73,7 @@ class PlainUniformGenerator(RandomGeneratorBase):
factor = _range_bound(factor, name, center=center, bounds=bound, device=device, dtype=dtype)
self.sampler_dict.update({name: Uniform(factor[0], factor[1], validate_args=False)})
- def forward(self, batch_shape: torch.Size, same_on_batch: bool = False) -> Dict[str, Tensor]:
+ def forward(self, batch_shape: Tuple[int, ...], same_on_batch: bool = False) -> Dict[str, Tensor]:
batch_size = batch_shape[0]
_common_param_check(batch_size, same_on_batch)
_device, _dtype = _extract_device_dtype([t for t, _, _, _ in self.samplers])
diff --git a/kornia/augmentation/random_generator/_2d/planckian_jitter.py b/kornia/augmentation/random_generator/_2d/planckian_jitter.py
index 0b9e159a3..0da9d065f 100644
--- a/kornia/augmentation/random_generator/_2d/planckian_jitter.py
+++ b/kornia/augmentation/random_generator/_2d/planckian_jitter.py
@@ -1,4 +1,4 @@
-from typing import Dict, List
+from typing import Dict, List, Tuple
import torch
from torch.distributions import Uniform
@@ -22,7 +22,7 @@ class PlanckianJitterGenerator(RandomGeneratorBase):
_joint_range_check(idx_range, 'idx_range', (0, self.domain[1]))
self.pl_idx_dist = Uniform(idx_range[0], idx_range[1], validate_args=False)
- def forward(self, batch_shape: torch.Size, same_on_batch: bool = False) -> Dict[str, torch.Tensor]:
+ def forward(self, batch_shape: Tuple[int, ...], same_on_batch: bool = False) -> Dict[str, torch.Tensor]:
batch_size = batch_shape[0]
_common_param_check(batch_size, same_on_batch)
pl_idx = _adapted_rsampling((batch_size,), self.pl_idx_dist, same_on_batch)
diff --git a/kornia/augmentation/random_generator/_2d/posterize.py b/kornia/augmentation/random_generator/_2d/posterize.py
index f82c007f4..1434629ae 100644
--- a/kornia/augmentation/random_generator/_2d/posterize.py
+++ b/kornia/augmentation/random_generator/_2d/posterize.py
@@ -47,7 +47,7 @@ class PosterizeGenerator(RandomGeneratorBase):
_joint_range_check(bits, 'bits', (0, 8))
self.bit_sampler = Uniform(bits[0], bits[1], validate_args=False)
- def forward(self, batch_shape: torch.Size, same_on_batch: bool = False) -> Dict[str, Tensor]:
+ def forward(self, batch_shape: Tuple[int, ...], same_on_batch: bool = False) -> Dict[str, Tensor]:
batch_size = batch_shape[0]
_common_param_check(batch_size, same_on_batch)
_device, _ = _extract_device_dtype([self.bits_factor if isinstance(self.bits_factor, Tensor) else None])
diff --git a/kornia/augmentation/random_generator/_2d/probability.py b/kornia/augmentation/random_generator/_2d/probability.py
index 5a94d9cda..efddb5569 100644
--- a/kornia/augmentation/random_generator/_2d/probability.py
+++ b/kornia/augmentation/random_generator/_2d/probability.py
@@ -1,4 +1,4 @@
-from typing import Dict
+from typing import Dict, Tuple
import torch
from torch.distributions import Bernoulli
@@ -38,7 +38,7 @@ class ProbabilityGenerator(RandomGeneratorBase):
p = torch.tensor(float(self.p), device=device, dtype=dtype)
self.sampler = Bernoulli(p)
- def forward(self, batch_shape: torch.Size, same_on_batch: bool = False) -> Dict[str, Tensor]:
+ def forward(self, batch_shape: Tuple[int, ...], same_on_batch: bool = False) -> Dict[str, Tensor]:
batch_size = batch_shape[0]
probs_mask: Tensor = _adapted_sampling((batch_size,), self.sampler, same_on_batch).bool()
return dict(probs=probs_mask)
diff --git a/kornia/augmentation/random_generator/_2d/rectangle_earase.py b/kornia/augmentation/random_generator/_2d/rectangle_earase.py
index 007845f70..31bb198ed 100644
--- a/kornia/augmentation/random_generator/_2d/rectangle_earase.py
+++ b/kornia/augmentation/random_generator/_2d/rectangle_earase.py
@@ -71,7 +71,7 @@ class RectangleEraseGenerator(RandomGeneratorBase):
tensor(0, device=device, dtype=dtype), tensor(1, device=device, dtype=dtype), validate_args=False
)
- def forward(self, batch_shape: torch.Size, same_on_batch: bool = False) -> Dict[str, Tensor]:
+ def forward(self, batch_shape: Tuple[int, ...], same_on_batch: bool = False) -> Dict[str, Tensor]:
batch_size = batch_shape[0]
height = batch_shape[-2]
width = batch_shape[-1]
diff --git a/kornia/augmentation/random_generator/_2d/resize.py b/kornia/augmentation/random_generator/_2d/resize.py
index 95deb206a..157ef5ef2 100644
--- a/kornia/augmentation/random_generator/_2d/resize.py
+++ b/kornia/augmentation/random_generator/_2d/resize.py
@@ -45,7 +45,7 @@ class ResizeGenerator(RandomGeneratorBase):
self.dtype = dtype
pass
- def forward(self, batch_shape: torch.Size, same_on_batch: bool = False) -> Dict[str, Tensor]:
+ def forward(self, batch_shape: Tuple[int, ...], same_on_batch: bool = False) -> Dict[str, Tensor]:
batch_size = batch_shape[0]
_common_param_check(batch_size, same_on_batch)
_device = self.device
diff --git a/kornia/augmentation/random_generator/_2d/shear.py b/kornia/augmentation/random_generator/_2d/shear.py
index 7128a69e8..ccc2a6659 100644
--- a/kornia/augmentation/random_generator/_2d/shear.py
+++ b/kornia/augmentation/random_generator/_2d/shear.py
@@ -67,7 +67,7 @@ class ShearGenerator(RandomGeneratorBase):
self.shear_x_sampler = shear_x_sampler
self.shear_y_sampler = shear_y_sampler
- def forward(self, batch_shape: torch.Size, same_on_batch: bool = False) -> Dict[str, Tensor]:
+ def forward(self, batch_shape: Tuple[int, ...], same_on_batch: bool = False) -> Dict[str, Tensor]:
batch_size = batch_shape[0]
height = batch_shape[-2]
width = batch_shape[-1]
diff --git a/kornia/augmentation/random_generator/_2d/translate.py b/kornia/augmentation/random_generator/_2d/translate.py
index 3a4b143ba..68986cc91 100644
--- a/kornia/augmentation/random_generator/_2d/translate.py
+++ b/kornia/augmentation/random_generator/_2d/translate.py
@@ -61,7 +61,7 @@ class TranslateGenerator(RandomGeneratorBase):
self.translate_y_sampler = Uniform(_translate_y[..., 0], _translate_y[..., 1], validate_args=False)
- def forward(self, batch_shape: torch.Size, same_on_batch: bool = False) -> Dict[str, Tensor]:
+ def forward(self, batch_shape: Tuple[int, ...], same_on_batch: bool = False) -> Dict[str, Tensor]:
batch_size = batch_shape[0]
height = batch_shape[-2]
width = batch_shape[-1]
diff --git a/kornia/augmentation/random_generator/_3d/affine.py b/kornia/augmentation/random_generator/_3d/affine.py
index 19150b099..2903d69e2 100644
--- a/kornia/augmentation/random_generator/_3d/affine.py
+++ b/kornia/augmentation/random_generator/_3d/affine.py
@@ -143,7 +143,7 @@ class AffineGenerator3D(RandomGeneratorBase):
validate_args=False,
)
- def forward(self, batch_shape: torch.Size, same_on_batch: bool = False) -> Dict[str, torch.Tensor]:
+ def forward(self, batch_shape: Tuple[int, ...], same_on_batch: bool = False) -> Dict[str, torch.Tensor]:
batch_size = batch_shape[0]
depth = batch_shape[-3]
height = batch_shape[-2]
diff --git a/kornia/augmentation/random_generator/_3d/crop.py b/kornia/augmentation/random_generator/_3d/crop.py
index 8996852a1..9a2449156 100644
--- a/kornia/augmentation/random_generator/_3d/crop.py
+++ b/kornia/augmentation/random_generator/_3d/crop.py
@@ -45,7 +45,7 @@ class CropGenerator3D(RandomGeneratorBase):
def make_samplers(self, device: torch.device, dtype: torch.dtype) -> None:
self.rand_sampler = Uniform(tensor(0.0, device=device, dtype=dtype), tensor(1.0, device=device, dtype=dtype))
- def forward(self, batch_shape: torch.Size, same_on_batch: bool = False) -> Dict[str, Tensor]:
+ def forward(self, batch_shape: Tuple[int, ...], same_on_batch: bool = False) -> Dict[str, Tensor]:
batch_size, _, depth, height, width = batch_shape
_common_param_check(batch_size, same_on_batch)
_device, _dtype = _extract_device_dtype([self.size if isinstance(self.size, Tensor) else None])
diff --git a/kornia/augmentation/random_generator/_3d/motion_blur.py b/kornia/augmentation/random_generator/_3d/motion_blur.py
index 472ee52b5..86b7def36 100644
--- a/kornia/augmentation/random_generator/_3d/motion_blur.py
+++ b/kornia/augmentation/random_generator/_3d/motion_blur.py
@@ -77,7 +77,7 @@ class MotionBlurGenerator3D(RandomGeneratorBase):
self.roll_sampler = Uniform(angle[2][0], angle[2][1], validate_args=False)
self.direction_sampler = Uniform(direction[0], direction[1], validate_args=False)
- def forward(self, batch_shape: torch.Size, same_on_batch: bool = False) -> Dict[str, Tensor]:
+ def forward(self, batch_shape: Tuple[int, ...], same_on_batch: bool = False) -> Dict[str, Tensor]:
batch_size = batch_shape[0]
_common_param_check(batch_size, same_on_batch)
# self.ksize_factor.expand((batch_size, -1))
diff --git a/kornia/augmentation/random_generator/_3d/perspective.py b/kornia/augmentation/random_generator/_3d/perspective.py
index 1f8278e74..6bfef2c93 100644
--- a/kornia/augmentation/random_generator/_3d/perspective.py
+++ b/kornia/augmentation/random_generator/_3d/perspective.py
@@ -1,4 +1,4 @@
-from typing import Dict, Union
+from typing import Dict, Tuple, Union
import torch
from torch.distributions import Uniform
@@ -42,7 +42,7 @@ class PerspectiveGenerator3D(RandomGeneratorBase):
tensor(0, device=device, dtype=dtype), tensor(1, device=device, dtype=dtype), validate_args=False
)
- def forward(self, batch_shape: torch.Size, same_on_batch: bool = False) -> Dict[str, Tensor]:
+ def forward(self, batch_shape: Tuple[int, ...], same_on_batch: bool = False) -> Dict[str, Tensor]:
batch_size = batch_shape[0]
depth = batch_shape[-3]
height = batch_shape[-2]
diff --git a/kornia/augmentation/random_generator/_3d/rotation.py b/kornia/augmentation/random_generator/_3d/rotation.py
index 371db6a48..c50254dad 100644
--- a/kornia/augmentation/random_generator/_3d/rotation.py
+++ b/kornia/augmentation/random_generator/_3d/rotation.py
@@ -56,7 +56,7 @@ class RotationGenerator3D(RandomGeneratorBase):
self.pitch_sampler = Uniform(degrees[1][0], degrees[1][1], validate_args=False)
self.roll_sampler = Uniform(degrees[2][0], degrees[2][1], validate_args=False)
- def forward(self, batch_shape: torch.Size, same_on_batch: bool = False) -> Dict[str, Tensor]:
+ def forward(self, batch_shape: Tuple[int, ...], same_on_batch: bool = False) -> Dict[str, Tensor]:
batch_size = batch_shape[0]
_common_param_check(batch_size, same_on_batch)
_device, _dtype = _extract_device_dtype([self.degrees])
diff --git a/kornia/augmentation/random_generator/base.py b/kornia/augmentation/random_generator/base.py
index 0b77f4e1d..afd15436c 100644
--- a/kornia/augmentation/random_generator/base.py
+++ b/kornia/augmentation/random_generator/base.py
@@ -1,4 +1,4 @@
-from typing import Callable, Dict, Optional
+from typing import Callable, Dict, Optional, Tuple, Union
import torch
from torch.distributions import Distribution
@@ -49,7 +49,7 @@ class RandomGeneratorBase(Module, metaclass=_PostInitInjectionMetaClass):
def make_samplers(self, device: torch.device, dtype: torch.dtype) -> None:
raise NotImplementedError
- def forward(self, batch_shape: torch.Size, same_on_batch: bool = False) -> Dict[str, Tensor]:
+ def forward(self, batch_shape: Tuple[int, ...], same_on_batch: bool = False) -> Dict[str, Tensor]:
raise NotImplementedError
@@ -82,19 +82,19 @@ class DistributionWithMapper(Distribution):
self.dist = dist
self.map_fn = map_fn
- def rsample(self, sample_shape: torch.Size) -> Tensor: # type: ignore[override]
+ def rsample(self, sample_shape: Tuple[int, ...]) -> Tensor: # type: ignore[override]
out = self.dist.rsample(sample_shape)
if self.map_fn is not None:
out = self.map_fn(out)
return out
- def sample(self, sample_shape: torch.Size) -> Tensor: # type: ignore[override]
+ def sample(self, sample_shape: Tuple[int, ...]) -> Tensor: # type: ignore[override]
out = self.dist.sample(sample_shape)
if self.map_fn is not None:
out = self.map_fn(out)
return out
- def sample_n(self, n) -> Tensor:
+ def sample_n(self, n: Union[int, float, Tensor]) -> Tensor:
out = self.dist.sample_n(n)
if self.map_fn is not None:
out = self.map_fn(out)
diff --git a/kornia/augmentation/random_generator/utils.py b/kornia/augmentation/random_generator/utils.py
index 518ff347b..9478e9a98 100644
--- a/kornia/augmentation/random_generator/utils.py
+++ b/kornia/augmentation/random_generator/utils.py
@@ -1,8 +1,11 @@
+from typing import Any
+
import torch
-from torch import Tensor
+
+from kornia.core import Tensor
-def randperm(n: int, ensure_perm: bool = True, **kwargs) -> Tensor:
+def randperm(n: int, ensure_perm: bool = True, **kwargs: Any) -> Tensor:
"""`randomperm` with the ability to ensure the different arrangement generated."""
perm = torch.randperm(n, **kwargs)
if ensure_perm:
diff --git a/kornia/augmentation/utils/helpers.py b/kornia/augmentation/utils/helpers.py
index 082543758..581ccf613 100644
--- a/kornia/augmentation/utils/helpers.py
+++ b/kornia/augmentation/utils/helpers.py
@@ -21,7 +21,7 @@ def _validate_input(f: Callable[..., Any]) -> Callable[..., Any]:
"""
@wraps(f)
- def wrapper(input: Tensor, *args, **kwargs):
+ def wrapper(input: Tensor, *args: Any, **kwargs: Any) -> Any:
if not torch.is_tensor(input):
raise TypeError(f"Input type is not a Tensor. Got {type(input)}")
@@ -44,7 +44,7 @@ def _validate_input3d(f: Callable[..., Any]) -> Callable[..., Any]:
"""
@wraps(f)
- def wrapper(input: Tensor, *args, **kwargs):
+ def wrapper(input: Tensor, *args: Any, **kwargs: Any) -> Any:
if not torch.is_tensor(input):
raise TypeError(f"Input type is not a Tensor. Got {type(input)}")
@@ -191,7 +191,9 @@ def _validate_input_shape(input: Tensor, channel_index: int, number: int) -> boo
def _adapted_rsampling(
- shape: Union[Tuple[int, ...], torch.Size], dist: torch.distributions.Distribution, same_on_batch=False
+ shape: Union[Tuple[int, ...], torch.Size],
+ dist: torch.distributions.Distribution,
+ same_on_batch: Optional[bool] = False,
) -> Tensor:
r"""The uniform reparameterized sampling function that accepts 'same_on_batch'.
@@ -207,7 +209,9 @@ def _adapted_rsampling(
def _adapted_sampling(
- shape: Union[Tuple[int, ...], torch.Size], dist: torch.distributions.Distribution, same_on_batch=False
+ shape: Union[Tuple[int, ...], torch.Size],
+ dist: torch.distributions.Distribution,
+ same_on_batch: Optional[bool] = False,
) -> Tensor:
r"""The uniform sampling function that accepts 'same_on_batch'.
@@ -320,7 +324,7 @@ def override_parameters(
return out
-def preprocess_boxes(input: Union[Tensor, Boxes], mode="vertices_plus") -> Boxes:
+def preprocess_boxes(input: Union[Tensor, Boxes], mode: str = "vertices_plus") -> Boxes:
r"""Preprocess input boxes.
Args:
diff --git a/kornia/augmentation/utils/param_validation.py b/kornia/augmentation/utils/param_validation.py
index 8800c9220..2ac94ef7e 100644
--- a/kornia/augmentation/utils/param_validation.py
+++ b/kornia/augmentation/utils/param_validation.py
@@ -5,7 +5,7 @@ import torch
from kornia.core import Tensor, as_tensor, tensor
-def _common_param_check(batch_size: int, same_on_batch: Optional[bool] = None):
+def _common_param_check(batch_size: int, same_on_batch: Optional[bool] = None) -> None:
"""Valid batch_size and same_on_batch params."""
if not (type(batch_size) is int and batch_size >= 0):
raise AssertionError(f"`batch_size` shall be a positive integer. Got {batch_size}.")
diff --git a/kornia/contrib/face_detection.py b/kornia/contrib/face_detection.py
index fbb0c60a4..bae3708dc 100644
--- a/kornia/contrib/face_detection.py
+++ b/kornia/contrib/face_detection.py
@@ -254,7 +254,7 @@ class Conv4layerBlock(nn.Sequential):
class YuFaceDetectNet(nn.Module):
- def __init__(self, phase, pretrained: bool):
+ def __init__(self, phase: str, pretrained: bool) -> None:
super().__init__()
self.phase = phase
self.num_classes = 2
diff --git a/kornia/contrib/image_stitching.py b/kornia/contrib/image_stitching.py
index 6b21c1fe0..5a7bae84b 100644
--- a/kornia/contrib/image_stitching.py
+++ b/kornia/contrib/image_stitching.py
@@ -1,4 +1,4 @@
-from typing import Dict, List, Optional, Tuple
+from typing import Dict, Optional, Tuple
import torch
@@ -50,7 +50,6 @@ class ImageStitcher(Module):
keypoints1: matched keypoint set from an image, shaped as :math:`(N, 2)`.
keypoints2: matched keypoint set from the other image, shaped as :math:`(N, 2)`.
"""
- homo: Tensor
if self.estimator == "vanilla":
homo = find_homography_dlt_iterated(
keypoints2[None], keypoints1[None], torch.ones_like(keypoints1[None, :, 0])
@@ -62,14 +61,14 @@ class ImageStitcher(Module):
raise NotImplementedError(f"Unsupported estimator {self.estimator}. Use ‘ransac’ or ‘vanilla’ instead.")
return homo
- def estimate_transform(self, **kwargs) -> Tensor:
+ def estimate_transform(self, *args: Tensor, **kwargs: Tensor) -> Tensor:
"""Compute the corresponding homography."""
- homos: List[Tensor] = []
kp1, kp2, idx = kwargs['keypoints0'], kwargs['keypoints1'], kwargs['batch_indexes']
- for i in range(len(idx.unique())):
- homos.append(self._estimate_homography(kp1[idx == i], kp2[idx == i]))
+ homos = [self._estimate_homography(kp1[idx == i], kp2[idx == i]) for i in range(len(idx.unique()))]
+
if len(homos) == 0:
raise RuntimeError("Compute homography failed. No matched keypoints found.")
+
return concatenate(homos)
def blend_image(self, src_img: Tensor, dst_img: Tensor, mask: Tensor) -> Tensor:
@@ -85,7 +84,7 @@ class ImageStitcher(Module):
"""Preprocess input to the required format."""
# TODO: probably perform histogram matching here.
if isinstance(self.matcher, LoFTR) or isinstance(self.matcher, LocalFeatureMatcher):
- input_dict: Dict[str, Tensor] = { # LofTR works on grayscale images only
+ input_dict = { # LofTR works on grayscale images only
"image0": rgb_to_grayscale(image_1),
"image1": rgb_to_grayscale(image_2),
}
@@ -101,7 +100,7 @@ class ImageStitcher(Module):
return image
return image[..., :index]
- def on_matcher(self, data) -> Dict[str, Tensor]:
+ def on_matcher(self, data: Dict[str, Tensor]) -> Dict[str, Tensor]:
return self.matcher(data)
def stitch_pair(
@@ -115,7 +114,7 @@ class ImageStitcher(Module):
input_dict = self.preprocess(images_left, images_right)
out_shape = (images_left.shape[-2], images_left.shape[-1] + images_right.shape[-1])
correspondences = self.on_matcher(input_dict)
- homo: Tensor = self.estimate_transform(**correspondences)
+ homo = self.estimate_transform(**correspondences)
src_img = warp_perspective(images_right, homo, out_shape)
dst_img = concatenate([images_left, zeros_like(images_right)], -1)
diff --git a/kornia/contrib/lambda_module.py b/kornia/contrib/lambda_module.py
index c14cb13cf..1cb34ee1e 100644
--- a/kornia/contrib/lambda_module.py
+++ b/kornia/contrib/lambda_module.py
@@ -1,4 +1,4 @@
-from typing import Callable
+from typing import Any, Callable
from kornia.core import Module, Tensor
@@ -27,5 +27,5 @@ class Lambda(Module):
self.func = func
- def forward(self, img: Tensor, *args, **kwargs) -> Tensor:
+ def forward(self, img: Tensor, *args: Any, **kwargs: Any) -> Tensor:
return self.func(img, *args, **kwargs)
diff --git a/kornia/contrib/vit.py b/kornia/contrib/vit.py
index 5fa38be2d..6bea7d844 100644
--- a/kornia/contrib/vit.py
+++ b/kornia/contrib/vit.py
@@ -5,20 +5,22 @@ Paper: https://paperswithcode.com/paper/an-image-is-worth-16x16-words-transforme
Based on: https://towardsdatascience.com/implementing-visualttransformer-in-pytorch-184f9f16f632
Added some tricks from https://github.com/rwightman/pytorch-image-models/blob/master/timm/models/vision_transformer.py
"""
-from typing import List, Optional, Tuple
+from typing import Any, Callable, Dict, List, Optional, Tuple
import torch
from torch import nn
+from kornia.core import Module, Tensor
+
__all__ = ["VisionTransformer"]
-class ResidualAdd(nn.Module):
- def __init__(self, fn) -> None:
+class ResidualAdd(Module):
+ def __init__(self, fn: Callable[..., Tensor]) -> None:
super().__init__()
self.fn = fn
- def forward(self, x, **kwargs) -> None:
+ def forward(self, x: Tensor, **kwargs: Dict[str, Any]) -> Tensor:
res = x
x = self.fn(x, **kwargs)
x += res
@@ -36,7 +38,7 @@ class FeedForward(nn.Sequential):
)
-class MultiHeadAttention(nn.Module):
+class MultiHeadAttention(Module):
def __init__(self, emb_size: int, num_heads: int, att_drop: float, proj_drop: float) -> None:
super().__init__()
self.emb_size = emb_size
@@ -91,7 +93,7 @@ class TransformerEncoderBlock(nn.Sequential):
)
-class TransformerEncoder(nn.Module):
+class TransformerEncoder(Module):
def __init__(
self,
embed_dim: int = 768,
@@ -115,7 +117,7 @@ class TransformerEncoder(nn.Module):
return out
-class PatchEmbedding(nn.Module):
+class PatchEmbedding(Module):
"""Compute the 2d image patch embedding ready to pass to transformer encoder."""
def __init__(
@@ -124,7 +126,7 @@ class PatchEmbedding(nn.Module):
out_channels: int = 768,
patch_size: int = 16,
image_size: int = 224,
- backbone: Optional[nn.Module] = None,
+ backbone: Optional[Module] = None,
) -> None:
super().__init__()
self.in_channels = in_channels
@@ -158,7 +160,7 @@ class PatchEmbedding(nn.Module):
return x
-class VisionTransformer(nn.Module):
+class VisionTransformer(Module):
"""Vision transformer (ViT) module.
The module is expected to be used as operator for different vision tasks.
@@ -196,7 +198,7 @@ class VisionTransformer(nn.Module):
num_heads: int = 12,
dropout_rate: float = 0.0,
dropout_attn: float = 0.0,
- backbone: Optional[nn.Module] = None,
+ backbone: Optional[Module] = None,
) -> None:
super().__init__()
self.image_size = image_size
diff --git a/kornia/contrib/vit_mobile.py b/kornia/contrib/vit_mobile.py
index 7d4872247..7b813661f 100644
--- a/kornia/contrib/vit_mobile.py
+++ b/kornia/contrib/vit_mobile.py
@@ -1,39 +1,41 @@
-from typing import Tuple
+from typing import Any, Dict, Tuple
import torch
from torch import nn
+from kornia.core import Module, Tensor
-def conv_1x1_bn(inp: int, oup: int) -> nn.Module:
+
+def conv_1x1_bn(inp: int, oup: int) -> Module:
return nn.Sequential(nn.Conv2d(inp, oup, 1, 1, 0, bias=False), nn.BatchNorm2d(oup), nn.SiLU())
-def conv_nxn_bn(inp: int, oup: int, kernal_size: int = 3, stride: int = 1) -> nn.Module:
+def conv_nxn_bn(inp: int, oup: int, kernal_size: int = 3, stride: int = 1) -> Module:
return nn.Sequential(nn.Conv2d(inp, oup, kernal_size, stride, 1, bias=False), nn.BatchNorm2d(oup), nn.SiLU())
-class PreNorm(nn.Module):
- def __init__(self, dim: int, fn: nn.Module) -> None:
+class PreNorm(Module):
+ def __init__(self, dim: int, fn: Module) -> None:
super().__init__()
self.norm = nn.LayerNorm(dim)
self.fn = fn
- def forward(self, x: torch.Tensor, **kwargs) -> torch.Tensor:
+ def forward(self, x: Tensor, **kwargs: Dict[str, Any]) -> Tensor:
return self.fn(self.norm(x), **kwargs)
-class FeedForward(nn.Module):
+class FeedForward(Module):
def __init__(self, dim: int, hidden_dim: int, dropout: float = 0.0) -> None:
super().__init__()
self.net = nn.Sequential(
nn.Linear(dim, hidden_dim), nn.SiLU(), nn.Dropout(dropout), nn.Linear(hidden_dim, dim), nn.Dropout(dropout)
)
- def forward(self, x: torch.Tensor) -> torch.Tensor:
+ def forward(self, x: Tensor) -> Tensor:
return self.net(x)
-class Attention(nn.Module):
+class Attention(Module):
def __init__(self, dim: int, heads: int = 8, dim_head: int = 64, dropout: float = 0.0) -> None:
super().__init__()
inner_dim = dim_head * heads
@@ -47,7 +49,7 @@ class Attention(nn.Module):
self.to_out = nn.Sequential(nn.Linear(inner_dim, dim), nn.Dropout(dropout)) if project_out else nn.Identity()
- def forward(self, x: torch.Tensor) -> torch.Tensor:
+ def forward(self, x: Tensor) -> Tensor:
qkv = self.to_qkv(x).chunk(3, dim=-1)
b, p, n, hd = qkv[0].shape
@@ -60,7 +62,7 @@ class Attention(nn.Module):
return self.to_out(out)
-class Transformer(nn.Module):
+class Transformer(Module):
"""Transformer block described in ViT.
Paper: https://arxiv.org/abs/2010.11929
@@ -88,14 +90,14 @@ class Transformer(nn.Module):
)
)
- def forward(self, x: torch.Tensor) -> torch.Tensor:
+ def forward(self, x: Tensor) -> Tensor:
for attn, ff in self.layers:
x = attn(x) + x
x = ff(x) + x
return x
-class MV2Block(nn.Module):
+class MV2Block(Module):
"""MV2 block described in MobileNetV2.
Paper: https://arxiv.org/pdf/1801.04381
@@ -140,14 +142,14 @@ class MV2Block(nn.Module):
nn.BatchNorm2d(oup),
)
- def forward(self, x: torch.Tensor) -> torch.Tensor:
+ def forward(self, x: Tensor) -> Tensor:
if self.use_res_connect:
return x + self.conv(x)
else:
return self.conv(x)
-class MobileViTBlock(nn.Module):
+class MobileViTBlock(Module):
"""MobileViT block mentioned in MobileViT.
Args:
@@ -181,7 +183,7 @@ class MobileViTBlock(nn.Module):
self.conv3 = conv_1x1_bn(dim, channel)
self.conv4 = conv_nxn_bn(2 * channel, channel, kernel_size)
- def forward(self, x: torch.Tensor) -> torch.Tensor:
+ def forward(self, x: Tensor) -> Tensor:
y = x.clone()
# Local representations
@@ -211,7 +213,7 @@ class MobileViTBlock(nn.Module):
return x
-class MobileViT(nn.Module):
+class MobileViT(Module):
"""Module MobileViT. Default arguments is for MobileViT XXS.
Paper: https://arxiv.org/abs/2110.02178
@@ -274,7 +276,7 @@ class MobileViT(nn.Module):
self.conv2 = conv_1x1_bn(channels[-2], channels[-1])
- def forward(self, x: torch.Tensor) -> torch.Tensor:
+ def forward(self, x: Tensor) -> Tensor:
x = self.conv1(x)
x = self.mv2[0](x)
diff --git a/kornia/core/__init__.py b/kornia/core/__init__.py
index 5e5093490..7359d10e5 100644
--- a/kornia/core/__init__.py
+++ b/kornia/core/__init__.py
@@ -1,5 +1,6 @@
from ._backend import (
Device,
+ Dtype,
Module,
Parameter,
Tensor,
@@ -21,6 +22,7 @@ from ._backend import (
__all__ = [
"concatenate",
"Device",
+ "Dtype",
"Module",
"Tensor",
"tensor",
diff --git a/kornia/core/_backend.py b/kornia/core/_backend.py
index b0f53388c..1337ce795 100644
--- a/kornia/core/_backend.py
+++ b/kornia/core/_backend.py
@@ -29,5 +29,6 @@ as_tensor = torch.as_tensor
# random
rand = torch.rand
-# device
-Device = Union[str, device]
+# type alias
+Device = Union[str, device, None]
+Dtype = Union[torch.dtype, None]
diff --git a/kornia/core/check.py b/kornia/core/check.py
index 8c569103c..a437f999b 100644
--- a/kornia/core/check.py
+++ b/kornia/core/check.py
@@ -118,6 +118,7 @@ def KORNIA_CHECK_TYPE(x: object, typ: T, msg: str | None = None) -> TypeGuard[T]
>>> KORNIA_CHECK_TYPE("foo", str, "Invalid string")
True
"""
+ # TODO: Move to use typeguard here dropping support for JIT
if not isinstance(x, typ):
raise TypeError(f"Invalid type: {type(x)}.\n{msg}")
@@ -139,6 +140,7 @@ def KORNIA_CHECK_IS_TENSOR(x: object, msg: str | None = None) -> TypeGuard[Tenso
>>> KORNIA_CHECK_IS_TENSOR(x, "Invalid tensor")
True
"""
+ # TODO: Move to use typeguard here dropping support for JIT
if not isinstance(x, Tensor):
raise TypeError(f"Not a Tensor type. Got: {type(x)}.\n{msg}")
diff --git a/kornia/core/tensor_wrapper.py b/kornia/core/tensor_wrapper.py
index 56fb71f3d..232c63dda 100644
--- a/kornia/core/tensor_wrapper.py
+++ b/kornia/core/tensor_wrapper.py
@@ -2,7 +2,6 @@
# insipired by:
# https://github.com/pytorch/pytorch/blob/591dfffa38848de54b7f5f4e49260847024c9281/test/test_overrides.py#L748
import collections
-from typing import Any
import torch
from torch import Tensor
@@ -154,7 +153,7 @@ class TensorWrapper:
def __neg__(self):
return self.__unary_op__(Tensor.negative)
- def __unary_op__(self, func: Any, other=None):
+ def __unary_op__(self, func, other=None):
args = (self, other) if other is not None else (self,)
return self.__torch_function__(func, (type(self),), args)
diff --git a/kornia/enhance/adjust.py b/kornia/enhance/adjust.py
index 56898733e..b675f9c97 100644
--- a/kornia/enhance/adjust.py
+++ b/kornia/enhance/adjust.py
@@ -412,7 +412,7 @@ def adjust_contrast_with_mean_subtraction(image: Tensor, factor: Union[float, Te
return img_adjust
-def adjust_brightness(image: Tensor, factor: Union[float, Tensor], clip_output=True) -> Tensor:
+def adjust_brightness(image: Tensor, factor: Union[float, Tensor], clip_output: bool = True) -> Tensor:
r"""Adjust the brightness of an image tensor.
.. image:: _static/img/adjust_brightness.png
@@ -479,7 +479,7 @@ def adjust_brightness(image: Tensor, factor: Union[float, Tensor], clip_output=T
return img_adjust
-def adjust_brightness_accumulative(image: Tensor, factor: Union[float, Tensor], clip_output=True) -> Tensor:
+def adjust_brightness_accumulative(image: Tensor, factor: Union[float, Tensor], clip_output: bool = True) -> Tensor:
r"""Adjust the brightness accumulatively of an image tensor.
This implementation follows PIL convention.
@@ -742,13 +742,13 @@ def posterize(input: Tensor, bits: Union[int, Tensor]) -> Tensor:
# Ref: https://github.com/tensorflow/tpu/blob/master/models/official/efficientnet/autoaugment.py#L222
# Potential approach: implementing kornia.LUT with floating points
# https://github.com/albumentations-team/albumentations/blob/master/albumentations/augmentations/functional.py#L472
- def _left_shift(input: Tensor, shift: Tensor):
+ def _left_shift(input: Tensor, shift: Tensor) -> Tensor:
return ((input * 255).to(torch.uint8) * (2**shift)).to(input.dtype) / 255.0
- def _right_shift(input: Tensor, shift: Tensor):
+ def _right_shift(input: Tensor, shift: Tensor) -> Tensor:
return (input * 255).to(torch.uint8) / (2**shift).to(input.dtype) / 255.0
- def _posterize_one(input: Tensor, bits: Tensor):
+ def _posterize_one(input: Tensor, bits: Tensor) -> Tensor:
# Single bits value condition
if bits == 0:
return torch.zeros_like(input)
diff --git a/kornia/enhance/core.py b/kornia/enhance/core.py
index 31f577bd6..1adbd5052 100644
--- a/kornia/enhance/core.py
+++ b/kornia/enhance/core.py
@@ -87,7 +87,7 @@ class AddWeighted(Module):
Tensor alpha/beta/gamma have to be with shape broadcastable to src1 and src2 shapes.
"""
- def __init__(self, alpha, beta, gamma) -> None:
+ def __init__(self, alpha: Union[float, Tensor], beta: Union[float, Tensor], gamma: Union[float, Tensor]) -> None:
super().__init__()
self.alpha = alpha
self.beta = beta
diff --git a/kornia/enhance/zca.py b/kornia/enhance/zca.py
index a4ad4e188..ee455bf61 100644
--- a/kornia/enhance/zca.py
+++ b/kornia/enhance/zca.py
@@ -84,7 +84,7 @@ class ZCAWhitening(Module):
self.transform_matrix: Tensor
self.transform_inv: Optional[Tensor]
- def fit(self, x: Tensor):
+ def fit(self, x: Tensor) -> 'ZCAWhitening':
r"""Fit ZCA whitening matrices to the data.
Args:
diff --git a/kornia/feature/adalam/adalam.py b/kornia/feature/adalam/adalam.py
index cd1ecda35..427b12a4a 100644
--- a/kornia/feature/adalam/adalam.py
+++ b/kornia/feature/adalam/adalam.py
@@ -6,7 +6,7 @@ from typing import Optional, Tuple, Union
import torch
-from kornia.core import Tensor
+from kornia.core import Tensor, as_tensor
from kornia.core.check import KORNIA_CHECK_LAF, KORNIA_CHECK_SHAPE
from kornia.feature.laf import get_laf_center, get_laf_orientation, get_laf_scale
@@ -36,8 +36,8 @@ def match_adalam(
lafs1: Tensor,
lafs2: Tensor,
config: Optional[AdalamConfig] = None,
- hw1: Optional[Tensor] = None,
- hw2: Optional[Tensor] = None,
+ hw1: Optional[Tuple[int, int]] = None,
+ hw2: Optional[Tuple[int, int]] = None,
dm: Optional[Tensor] = None,
) -> Tuple[Tensor, Tensor]:
"""Function, which performs descriptor matching, followed by AdaLAM filtering (see :cite:`AdaLAM2020` for more
@@ -177,18 +177,18 @@ class AdalamFilter:
def match_and_filter(
self,
- k1,
- k2,
- d1,
- d2,
- im1shape=None,
- im2shape=None,
- o1=None,
- o2=None,
- s1=None,
- s2=None,
+ k1: Tensor,
+ k2: Tensor,
+ d1: Tensor,
+ d2: Tensor,
+ im1shape: Optional[Tuple[int, int]] = None,
+ im2shape: Optional[Tuple[int, int]] = None,
+ o1: Optional[Tensor] = None,
+ o2: Optional[Tensor] = None,
+ s1: Optional[Tensor] = None,
+ s2: Optional[Tensor] = None,
return_dist: bool = False,
- ):
+ ) -> Union[Tuple[Tensor, Tensor], Tensor]:
"""Standard matching and filtering with AdaLAM. This function:
- performs some elementary sanity check on the inputs;
@@ -206,12 +206,14 @@ class AdalamFilter:
Expected an array with shape (num_keypoints_in_source_image, descriptor_size).
d2: descriptors in the destination image.
Expected an array with shape (num_keypoints_in_destination_image, descriptor_size).
- im1shape: Shape of the source image. If None, it is inferred from keypoints max and min, at the cost of wasted runtime. So please provide it.
- Expected a tuple with (width, height) or (height, width) of source image
- im2shape: Shape of the destination image. If None, it is inferred from keypoints max and min, at the cost of wasted runtime. So please provide it.
- Expected a tuple with (width, height) or (height, width) of destination image
- o1/o2: keypoint orientations in degrees. They can be None if 'orientation_difference_threshold' in config is set to None.
- See documentation on 'orientation_difference_threshold' in the DEFAULT_CONFIG.
+ im1shape: Shape of the source image. If None, it is inferred from keypoints max and min, at the cost of
+ wasted runtime. So please provide it. Expected a tuple with (width, height) or (height, width)
+ of source image
+ im2shape: Shape of the destination image. If None, it is inferred from keypoints max and min, at the cost
+ of wasted runtime. So please provide it. Expected a tuple with (width, height) or (height, width)
+ of destination image
+ o1/o2: keypoint orientations in degrees. They can be None if 'orientation_difference_threshold' in config
+ is set to None. See documentation on 'orientation_difference_threshold' in the DEFAULT_CONFIG.
Expected an array with shape (num_keypoints_in_source/destination_image,)
s1/s2: keypoint scales. They can be None if 'scale_rate_threshold' in config is set to None.
See documentation on 'scale_rate_threshold' in the DEFAULT_CONFIG.
@@ -221,7 +223,7 @@ class AdalamFilter:
Returns:
Filtered putative matches.
A long tensor with shape (num_filtered_matches, 2) with indices of corresponding keypoints in k1 and k2.
- """ # noqa: E501
+ """
if s1 is None or s2 is None:
if self.config['scale_rate_threshold'] is not None:
raise AttributeError(
@@ -234,29 +236,33 @@ class AdalamFilter:
"Current configuration considers keypoint orientations for filtering, but orientations have not been provided.\n" # noqa: E501
"Please either provide orientations or set 'orientation_difference_threshold' to None to disable orientations filtering" # noqa: E501
)
- k1, k2, d1, d2, o1, o2, s1, s2 = self.__to_torch(k1, k2, d1, d2, o1, o2, s1, s2)
- if (len(d2) <= 1) or (len(d1) <= 1):
- idxs, dists = _no_match(d1)
+ _k1 = as_tensor(k1, device=self.config['device'], dtype=torch.float32)
+ _k2 = as_tensor(k2, device=self.config['device'], dtype=torch.float32)
+ _d1 = as_tensor(d1, device=self.config['device'], dtype=torch.float32)
+ _d2 = as_tensor(d2, device=self.config['device'], dtype=torch.float32)
+ _o1 = as_tensor(o1, device=self.config['device'], dtype=torch.float32)
+ _o2 = as_tensor(o2, device=self.config['device'], dtype=torch.float32)
+ _s1 = as_tensor(s1, device=self.config['device'], dtype=torch.float32)
+ _s2 = as_tensor(s2, device=self.config['device'], dtype=torch.float32)
+
+ if (len(_d2) <= 1) or (len(_d1) <= 1):
+ idxs, dists = _no_match(_d1)
if return_dist:
return idxs, dists
return idxs
- distmat = dist_matrix(d1, d2, is_normalized=False)
+
+ distmat = dist_matrix(_d1, _d2, is_normalized=False)
dd12, nn12 = torch.topk(distmat, k=2, dim=1, largest=False) # (n1, 2)
putative_matches = nn12[:, 0]
scores = dd12[:, 0] / dd12[:, 1].clamp_min_(1e-3)
+
if self.config['force_seed_mnn']:
dd21, nn21 = torch.min(distmat, dim=0) # (n2,)
- mnn = nn21[putative_matches] == torch.arange(k1.shape[0], device=self.config['device'])
+ mnn = nn21[putative_matches] == torch.arange(_k1.shape[0], device=self.config['device'])
else:
mnn = None
return self.filter_matches(
- k1, k2, putative_matches, scores, mnn, im1shape, im2shape, o1, o2, s1, s2, return_dist
- )
-
- def __to_torch(self, *args):
- return (
- a if a is None or torch.is_tensor(a) else torch.tensor(a, device=self.config['device'], dtype=torch.float32)
- for a in args
+ _k1, _k2, putative_matches, scores, mnn, im1shape, im2shape, _o1, _o2, _s1, _s2, return_dist
)
diff --git a/kornia/feature/adalam/core.py b/kornia/feature/adalam/core.py
index 3d710cccf..d5054f063 100644
--- a/kornia/feature/adalam/core.py
+++ b/kornia/feature/adalam/core.py
@@ -4,7 +4,7 @@ from typing import Optional, Tuple, Union
import torch
from typing_extensions import NotRequired, TypedDict
-from kornia.core import Device, Tensor, concatenate, tensor, where
+from kornia.core import Tensor, concatenate, tensor, where
from .ransac import ransac
from .utils import dist_matrix, orientation_diff
@@ -43,11 +43,11 @@ class AdalamConfig(TypedDict):
detected_scale_rate_threshold: NotRequired[int]
refit: NotRequired[bool]
force_seed_mnn: NotRequired[bool]
- device: NotRequired[Device]
+ device: NotRequired[torch.device]
mnn: NotRequired[Tensor]
-def _no_match(dm: Tensor):
+def _no_match(dm: Tensor) -> Tuple[Tensor, Tensor]:
"""Helper function, which output empty tensors.
Returns:
@@ -59,7 +59,9 @@ def _no_match(dm: Tensor):
return dists, idxs
-def select_seeds(dist1: Tensor, R1: Union[float, Tensor], scores1: Tensor, fnn12: Tensor, mnn: Optional[Tensor]):
+def select_seeds(
+ dist1: Tensor, R1: Union[float, Tensor], scores1: Tensor, fnn12: Tensor, mnn: Optional[Tensor]
+) -> Tuple[Tensor, Tensor]:
"""Select seed correspondences among the set of available matches.
dist1: Precomputed distance matrix between keypoints in image I_1
@@ -111,7 +113,7 @@ def extract_neighborhood_sets(
SCALE_RATE_THR: float,
SEARCH_EXP: float,
MIN_INLIERS: float,
-):
+) -> Tuple[Tensor, Tensor, Tensor, Tensor]:
"""Assign keypoints to seed points. This checks both the distance and the agreement of the local transformation
if available.
@@ -183,7 +185,7 @@ def extract_local_patterns(
im1seeds: Tensor,
im2seeds: Tensor,
scores: Tensor,
-):
+) -> Tuple[Tensor, Tensor, Tensor, Tensor, Tensor]:
"""Prepare local neighborhoods around each seed for the parallel RANSACs. This involves two steps: 1) Collect
all selected keypoints and refer them with respect to their seed point 2) Sort keypoints by score for the
progressive sampling to pick the best samples first.
@@ -233,12 +235,7 @@ def extract_local_patterns(
sorting_perm = torch.argsort(expanded_local_scores)
- im1loc = im1loc[sorting_perm]
- im2loc = im2loc[sorting_perm]
- tokp1 = tokp1[sorting_perm]
- tokp2 = tokp2[sorting_perm]
-
- return im1loc, im2loc, ransidx, tokp1, tokp2
+ return im1loc[sorting_perm], im2loc[sorting_perm], ransidx, tokp1[sorting_perm], tokp2[sorting_perm]
def adalam_core(
@@ -266,19 +263,21 @@ def adalam_core(
Expected a float32 tensor with shape (num_keypoints_in_destination_image, 2).
fn12: Initial set of putative matches to be filtered.
The current implementation assumes that these are unfiltered nearest neighbor matches,
- so it requires this to be a list of indices a_i such that the source keypoint i is associated to the destination keypoint a_i.
- For now to use AdaLAM on different inputs a workaround on the input format is required.
- Expected a long tensor with shape (num_keypoints_in_source_image,).
+ so it requires this to be a list of indices a_i such that the source keypoint i is associated to the
+ destination keypoint a_i. For now to use AdaLAM on different inputs a workaround on the input format is
+ required. Expected a long tensor with shape (num_keypoints_in_source_image,).
scores1: Confidence scores on the putative_matches. Usually holds Lowe's ratio scores.
- mnn: A mask indicating which putative matches are also mutual nearest neighbors. See documentation on 'force_seed_mnn' in the DEFAULT_CONFIG.
- If None, it disables the mutual nearest neighbor filtering on seed point selection.
- Expected a bool tensor with shape (num_keypoints_in_source_image,)
- im1shape: Shape of the source image. If None, it is inferred from keypoints max and min, at the cost of wasted runtime. So please provide it.
- Expected a tuple with (width, height) or (height, width) of source image
- im2shape: Shape of the destination image. If None, it is inferred from keypoints max and min, at the cost of wasted runtime. So please provide it.
- Expected a tuple with (width, height) or (height, width) of destination image
- o1/o2: keypoint orientations in degrees. They can be None if 'orientation_difference_threshold' in config is set to None.
- See documentation on 'orientation_difference_threshold' in the DEFAULT_CONFIG.
+ mnn: A mask indicating which putative matches are also mutual nearest neighbors. See documentation on
+ 'force_seed_mnn' in the DEFAULT_CONFIG. If None, it disables the mutual nearest neighbor filtering on seed
+ point selection. Expected a bool tensor with shape (num_keypoints_in_source_image,)
+ im1shape: Shape of the source image. If None, it is inferred from keypoints max and min, at the cost of wasted
+ runtime. So please provide it. Expected a tuple with (width, height) or (height, width) of source
+ image
+ im2shape: Shape of the destination image. If None, it is inferred from keypoints max and min, at the cost of
+ wasted runtime. So please provide it. Expected a tuple with (width, height) or (height, width) of
+ destination image
+ o1/o2: keypoint orientations in degrees. They can be None if 'orientation_difference_threshold' in config is
+ set to None. See documentation on 'orientation_difference_threshold' in the DEFAULT_CONFIG.
Expected a float32 tensor with shape (num_keypoints_in_source/destination_image,)
s1/s2: keypoint scales. They can be None if 'scale_rate_threshold' in config is set to None.
See documentation on 'scale_rate_threshold' in the DEFAULT_CONFIG.
@@ -288,7 +287,7 @@ def adalam_core(
Returns:
idxs: A long tensor with shape (num_filtered_matches, 2) with indices of corresponding keypoints in k1 and k2.
dists: inverse confidence ratio.
- """ # noqa: E501
+ """
AREA_RATIO = config['area_ratio']
SEARCH_EXP = config['search_expansion']
RANSAC_ITERS = config['ransac_iters']
@@ -366,7 +365,7 @@ def adalam_core(
# Run the parallel confidence-based RANSACs to perform local affine verification
inlier_idx, _, inl_confidence, inlier_counts = ransac(
- xsamples=im1loc, ysamples=im2loc, rdims=rdims, iters=RANSAC_ITERS, refit=REFIT, config=config
+ xsamples=im1loc, ysamples=im2loc, rdims=rdims, iters=RANSAC_ITERS, refit=REFIT, config=dict(config)
)
conf = inl_confidence[ransidx[inlier_idx]]
diff --git a/kornia/feature/adalam/ransac.py b/kornia/feature/adalam/ransac.py
index 4ad8e70ab..cc2d62e0f 100644
--- a/kornia/feature/adalam/ransac.py
+++ b/kornia/feature/adalam/ransac.py
@@ -1,4 +1,4 @@
-from typing import Tuple
+from typing import Any, Dict, Tuple
import torch
@@ -97,7 +97,9 @@ def sample_padded_inliers(
return padded_inlier_x, padded_inlier_y
-def ransac(xsamples, ysamples, rdims: Tensor, config, iters=128, refit=True):
+def ransac(
+ xsamples: Tensor, ysamples: Tensor, rdims: Tensor, config: Dict[str, Any], iters: int = 128, refit: bool = True
+) -> Tuple[Tensor, Tensor, Tensor, Tensor]:
DET_THR = config['detected_scale_rate_threshold']
MIN_CONFIDENCE = config['min_confidence']
dv: torch.device = config['device']
diff --git a/kornia/feature/adalam/utils.py b/kornia/feature/adalam/utils.py
index dcdbe42da..de647aef4 100644
--- a/kornia/feature/adalam/utils.py
+++ b/kornia/feature/adalam/utils.py
@@ -5,7 +5,7 @@ import torch
from kornia.core import Tensor
-def arange_sequence(ranges):
+def arange_sequence(ranges: Tensor) -> Tensor:
"""
returns a sequence of the ranges specified by the argument.
Example:
@@ -18,7 +18,7 @@ def arange_sequence(ranges):
return complete_ranges[complete_ranges < ranges.unsqueeze(-1)]
-def dist_matrix(d1, d2, is_normalized=False):
+def dist_matrix(d1: Tensor, d2: Tensor, is_normalized: bool = False) -> Tensor:
if is_normalized:
return 2 - 2.0 * d1 @ d2.t()
x_norm = (d1**2).sum(1).view(-1, 1)
@@ -29,14 +29,14 @@ def dist_matrix(d1, d2, is_normalized=False):
return distmat
-def orientation_diff(o1, o2):
+def orientation_diff(o1: Tensor, o2: Tensor) -> Tensor:
diff = o2 - o1
diff[diff < -180] += 360
diff[diff >= 180] -= 360
return diff
-def piecewise_arange(piecewise_idxer: Tensor):
+def piecewise_arange(piecewise_idxer: Tensor) -> Tensor:
"""
count repeated indices
Example:
@@ -111,7 +111,7 @@ def batch_2x2_ellipse(m):
return eigenvals, eigenvecs
-def draw_first_k_couples(k: int, rdims: Tensor, dv: torch.device):
+def draw_first_k_couples(k: int, rdims: Tensor, dv: torch.device) -> Tensor:
# exhaustive search over the first n samples:
# n(n+1)/2 = n2/2 + n/2 couples
# max n for which we can exhaustively sample with k couples:
diff --git a/kornia/feature/keynet.py b/kornia/feature/keynet.py
index bd19c64b5..301de5bed 100644
--- a/kornia/feature/keynet.py
+++ b/kornia/feature/keynet.py
@@ -97,7 +97,7 @@ def _KeyNetConvBlock(
stride: int = 1,
padding: int = 2,
dilation: int = 1,
-):
+) -> nn.Sequential:
"""Helper function for KeyNet.
Default learnable convolutional block for KeyNet.
diff --git a/kornia/feature/laf.py b/kornia/feature/laf.py
index 4bf828273..7739b2054 100644
--- a/kornia/feature/laf.py
+++ b/kornia/feature/laf.py
@@ -1,5 +1,5 @@
import math
-from typing import Optional, Union
+from typing import List, Optional, Tuple, Union
import torch
import torch.nn.functional as F
@@ -276,7 +276,7 @@ def laf_to_boundary_points(LAF: Tensor, n_pts: int = 50) -> Tensor:
return convert_points_from_homogeneous(pts_h.view(B, N, n_pts, 3))
-def get_laf_pts_to_draw(LAF: Tensor, img_idx: int = 0):
+def get_laf_pts_to_draw(LAF: Tensor, img_idx: int = 0) -> Tuple[List[int], List[int]]:
"""Return numpy array for drawing LAFs (local features).
Args:
@@ -301,7 +301,7 @@ def get_laf_pts_to_draw(LAF: Tensor, img_idx: int = 0):
KORNIA_CHECK_LAF(LAF)
pts = laf_to_boundary_points(LAF[img_idx : img_idx + 1])[0]
pts_np = pts.detach().permute(1, 0, 2).cpu().numpy()
- return (pts_np[..., 0], pts_np[..., 1])
+ return (pts_np[..., 0].tolist(), pts_np[..., 1].tolist())
def denormalize_laf(LAF: Tensor, images: Tensor) -> Tensor:
@@ -498,7 +498,7 @@ def laf_is_inside_image(laf: Tensor, images: Tensor, border: int = 0) -> Tensor:
return good_lafs_mask
-def laf_to_three_points(laf: Tensor):
+def laf_to_three_points(laf: Tensor) -> Tensor:
"""Convert local affine frame(LAF) to alternative representation: coordinates of LAF center, LAF-x unit vector,
LAF-y unit vector.
@@ -513,7 +513,7 @@ def laf_to_three_points(laf: Tensor):
return three_pts
-def laf_from_three_points(threepts: Tensor):
+def laf_from_three_points(threepts: Tensor) -> Tensor:
"""Convert three points to local affine frame.
Order is (0,0), (0, 1), (1, 0).
diff --git a/kornia/feature/loftr/utils/coarse_matching.py b/kornia/feature/loftr/utils/coarse_matching.py
index 534953906..d59bc69d9 100644
--- a/kornia/feature/loftr/utils/coarse_matching.py
+++ b/kornia/feature/loftr/utils/coarse_matching.py
@@ -1,11 +1,15 @@
+from typing import Any, Dict, Optional, Union
+
import torch
import torch.nn as nn
import torch.nn.functional as F
+from kornia.core import Module, Tensor
+
INF = 1e9
-def mask_border(m, b: int, v):
+def mask_border(m: Tensor, b: int, v: Union[Tensor, float, int, bool]) -> None:
"""Mask borders with value
Args:
m (torch.Tensor): [N, H0, W0, H1, W1]
@@ -25,7 +29,9 @@ def mask_border(m, b: int, v):
m[:, :, :, :, -b:] = v
-def mask_border_with_padding(m, bd, v, p_m0, p_m1):
+def mask_border_with_padding(
+ m: Tensor, bd: int, v: Union[Tensor, float, int, bool], p_m0: Tensor, p_m1: Tensor
+) -> None:
if bd <= 0:
return
@@ -43,7 +49,7 @@ def mask_border_with_padding(m, bd, v, p_m0, p_m1):
m[b_idx, :, :, :, w1 - bd :] = v
-def compute_max_candidates(p_m0, p_m1):
+def compute_max_candidates(p_m0: Tensor, p_m1: Tensor) -> Tensor:
"""Compute the max candidates of all pairs within a batch.
Args:
@@ -55,8 +61,8 @@ def compute_max_candidates(p_m0, p_m1):
return max_cand
-class CoarseMatching(nn.Module):
- def __init__(self, config):
+class CoarseMatching(Module):
+ def __init__(self, config: Dict[str, Any]) -> None:
super().__init__()
self.config = config
# general config
@@ -82,7 +88,14 @@ class CoarseMatching(nn.Module):
else:
raise NotImplementedError()
- def forward(self, feat_c0, feat_c1, data, mask_c0=None, mask_c1=None):
+ def forward(
+ self,
+ feat_c0: Tensor,
+ feat_c1: Tensor,
+ data: Dict[str, Tensor],
+ mask_c0: Optional[Tensor] = None,
+ mask_c1: Optional[Tensor] = None,
+ ) -> None:
"""
Args:
feat0 (torch.Tensor): [N, L, C]
@@ -108,14 +121,14 @@ class CoarseMatching(nn.Module):
if self.match_type == 'dual_softmax':
sim_matrix = torch.einsum("nlc,nsc->nls", feat_c0, feat_c1) / self.temperature
- if mask_c0 is not None:
+ if mask_c0 is not None and mask_c1 is not None:
sim_matrix.masked_fill_(~(mask_c0[..., None] * mask_c1[:, None]).bool(), -INF)
conf_matrix = F.softmax(sim_matrix, 1) * F.softmax(sim_matrix, 2)
elif self.match_type == 'sinkhorn':
# sinkhorn, dustbin included
sim_matrix = torch.einsum("nlc,nsc->nls", feat_c0, feat_c1)
- if mask_c0 is not None:
+ if mask_c0 is not None and mask_c1 is not None:
sim_matrix[:, :L, :S].masked_fill_(~(mask_c0[..., None] * mask_c1[:, None]).bool(), -INF)
# build uniform prior & use sinkhorn
@@ -139,7 +152,7 @@ class CoarseMatching(nn.Module):
data.update(**self.get_coarse_match(conf_matrix, data))
@torch.no_grad()
- def get_coarse_match(self, conf_matrix, data):
+ def get_coarse_match(self, conf_matrix: Tensor, data: Dict[str, Tensor]) -> Dict[str, Tensor]:
"""
Args:
conf_matrix (torch.Tensor): [N, L, S]
diff --git a/kornia/feature/matching.py b/kornia/feature/matching.py
index b737e89d1..c768ae60e 100644
--- a/kornia/feature/matching.py
+++ b/kornia/feature/matching.py
@@ -1,9 +1,8 @@
from typing import Dict, Optional, Tuple
import torch
-import torch.nn as nn
-from kornia.core import Tensor
+from kornia.core import Module, Tensor, concatenate
from kornia.core.check import KORNIA_CHECK_DM_DESC, KORNIA_CHECK_SHAPE
from kornia.feature.laf import get_laf_center
from kornia.testing import is_mps_tensor_safe
@@ -11,7 +10,7 @@ from kornia.testing import is_mps_tensor_safe
from .adalam import get_adalam_default_config, match_adalam
-def _cdist(d1: torch.Tensor, d2: torch.Tensor) -> torch.Tensor:
+def _cdist(d1: Tensor, d2: Tensor) -> Tensor:
r"""Manual `torch.cdist` for M1."""
if (not is_mps_tensor_safe(d1)) and (not is_mps_tensor_safe(d2)):
return torch.cdist(d1, d2)
@@ -27,7 +26,7 @@ def _get_default_fginn_params():
return config
-def _get_lazy_distance_matrix(desc1: Tensor, desc2: Tensor, dm_: Optional[Tensor] = None):
+def _get_lazy_distance_matrix(desc1: Tensor, desc2: Tensor, dm_: Optional[Tensor] = None) -> Tensor:
"""Helper function, which checks validity of provided distance matrix, or calculates L2-distance matrix dm is
not provided.
@@ -45,7 +44,7 @@ def _get_lazy_distance_matrix(desc1: Tensor, desc2: Tensor, dm_: Optional[Tensor
return dm
-def _no_match(dm: Tensor):
+def _no_match(dm: Tensor) -> Tuple[Tensor, Tensor]:
"""Helper function, which output empty tensors.
Returns:
@@ -76,10 +75,10 @@ def match_nn(desc1: Tensor, desc2: Tensor, dm: Optional[Tensor] = None) -> Tuple
KORNIA_CHECK_SHAPE(desc2, ["B", "DIM"])
if (len(desc1) == 0) or (len(desc2) == 0):
return _no_match(desc1)
- distance_matrix: Tensor = _get_lazy_distance_matrix(desc1, desc2, dm)
+ distance_matrix = _get_lazy_distance_matrix(desc1, desc2, dm)
match_dists, idxs_in_2 = torch.min(distance_matrix, dim=1)
- idxs_in1: Tensor = torch.arange(0, idxs_in_2.size(0), device=idxs_in_2.device)
- matches_idxs: Tensor = torch.cat([idxs_in1.view(-1, 1), idxs_in_2.view(-1, 1)], dim=1)
+ idxs_in1 = torch.arange(0, idxs_in_2.size(0), device=idxs_in_2.device)
+ matches_idxs = concatenate([idxs_in1.view(-1, 1), idxs_in_2.view(-1, 1)], 1)
return match_dists.view(-1, 1), matches_idxs.view(-1, 2)
@@ -111,11 +110,11 @@ def match_mnn(desc1: Tensor, desc2: Tensor, dm: Optional[Tensor] = None) -> Tupl
if distance_matrix.size(0) <= distance_matrix.size(1):
mutual_nns = minsize_idxs == idxs_in_1[idxs_in_2][:ms]
- matches_idxs = torch.cat([minsize_idxs.view(-1, 1), idxs_in_2.view(-1, 1)], dim=1)[mutual_nns]
+ matches_idxs = concatenate([minsize_idxs.view(-1, 1), idxs_in_2.view(-1, 1)], 1)[mutual_nns]
match_dists = match_dists[mutual_nns]
else:
mutual_nns = minsize_idxs == idxs_in_2[idxs_in_1][:ms]
- matches_idxs = torch.cat([idxs_in_1.view(-1, 1), minsize_idxs.view(-1, 1)], dim=1)[mutual_nns]
+ matches_idxs = concatenate([idxs_in_1.view(-1, 1), minsize_idxs.view(-1, 1)], 1)[mutual_nns]
match_dists = match_dists2[mutual_nns]
return match_dists.view(-1, 1), matches_idxs.view(-1, 2)
@@ -153,7 +152,7 @@ def match_snn(desc1: Tensor, desc2: Tensor, th: float = 0.8, dm: Optional[Tensor
return _no_match(distance_matrix)
idxs_in1 = torch.arange(0, idxs_in_2.size(0), device=distance_matrix.device)[mask]
idxs_in_2 = idxs_in_2[:, 0][mask]
- matches_idxs = torch.cat([idxs_in1.view(-1, 1), idxs_in_2.view(-1, 1)], dim=1)
+ matches_idxs = concatenate([idxs_in1.view(-1, 1), idxs_in_2.view(-1, 1)], 1)
return match_dists.view(-1, 1), matches_idxs.view(-1, 2)
@@ -278,7 +277,7 @@ def match_fginn(
return _no_match(distance_matrix)
idxs_in1 = torch.arange(0, idxs_in_2.size(0), device=distance_matrix.device)[mask]
idxs_in_2 = idxs_in_2[mask]
- matches_idxs = torch.cat([idxs_in1.view(-1, 1), idxs_in_2.view(-1, 1)], dim=1)
+ matches_idxs = concatenate([idxs_in1.view(-1, 1), idxs_in_2.view(-1, 1)], 1)
match_dists, matches_idxs = match_dists.view(-1, 1), matches_idxs.view(-1, 2)
if not mutual: # returning 1-way matches
@@ -288,7 +287,7 @@ def match_fginn(
return match_dists[good_mask], matches_idxs[good_mask]
-class DescriptorMatcher(nn.Module):
+class DescriptorMatcher(Module):
"""Module version of matching functions.
See :func:`~kornia.feature.match_nn`, :func:`~kornia.feature.match_snn`,
@@ -335,7 +334,7 @@ class DescriptorMatcher(nn.Module):
return out
-class GeometryAwareDescriptorMatcher(nn.Module):
+class GeometryAwareDescriptorMatcher(Module):
"""Module version of matching functions.
See :func:`~kornia.feature.match_nn`, :func:`~kornia.feature.match_snn`,
diff --git a/kornia/feature/mkd.py b/kornia/feature/mkd.py
index 2030df57d..bf6efe50e 100644
--- a/kornia/feature/mkd.py
+++ b/kornia/feature/mkd.py
@@ -219,7 +219,7 @@ class EmbedGradients(nn.Module):
return f"{self.__class__.__name__}(patch_size={self.patch_size}, relative={self.relative})"
-def spatial_kernel_embedding(kernel_type, grids: Dict[str, Tensor]) -> Tensor:
+def spatial_kernel_embedding(kernel_type: str, grids: Dict[str, Tensor]) -> Tensor:
r"""Compute embeddings for cartesian and polar parametrizations."""
factors = {"phi": 1.0, "rho": pi / sqrt2, "x": pi / 2, "y": pi / 2}
if kernel_type == 'cart':
diff --git a/kornia/feature/responses.py b/kornia/feature/responses.py
index c6797b5cc..6578195d7 100644
--- a/kornia/feature/responses.py
+++ b/kornia/feature/responses.py
@@ -7,7 +7,7 @@ from kornia.core.check import KORNIA_CHECK_SHAPE
from kornia.filters import gaussian_blur2d, spatial_gradient
-def _get_kernel_size(sigma: float):
+def _get_kernel_size(sigma: Union[float, int]) -> int:
ksize = int(2.0 * 4.0 * sigma + 1.0)
# matches OpenCV, but may cause padding problem for small images
@@ -324,7 +324,7 @@ class CornerHarris(Module):
"""
k: Tensor
- def __init__(self, k: Union[float, Tensor], grads_mode='sobel') -> None:
+ def __init__(self, k: Union[float, Tensor], grads_mode: str = 'sobel') -> None:
super().__init__()
if isinstance(k, float):
self.register_buffer('k', tensor(k))
@@ -346,7 +346,7 @@ class CornerGFTT(Module):
See :func:`~kornia.feature.gfft_response` for details.
"""
- def __init__(self, grads_mode='sobel') -> None:
+ def __init__(self, grads_mode: str = 'sobel') -> None:
super().__init__()
self.grads_mode: str = grads_mode
return
@@ -364,7 +364,7 @@ class BlobHessian(Module):
See :func:`~kornia.feature.hessian_response` for details.
"""
- def __init__(self, grads_mode='sobel') -> None:
+ def __init__(self, grads_mode: str = 'sobel') -> None:
super().__init__()
self.grads_mode: str = grads_mode
return
diff --git a/kornia/feature/scale_space_detector.py b/kornia/feature/scale_space_detector.py
index aed8a4240..d8c4e9efc 100644
--- a/kornia/feature/scale_space_detector.py
+++ b/kornia/feature/scale_space_detector.py
@@ -87,8 +87,8 @@ class ScaleSpaceDetector(Module):
ori_module: Module = PassLAF(),
aff_module: Module = PassLAF(),
minima_are_also_good: bool = False,
- scale_space_response=False,
- ):
+ scale_space_response: bool = False,
+ ) -> None:
super().__init__()
self.mr_size = mr_size
self.num_features = num_features
diff --git a/kornia/feature/sold2/sold2_detector.py b/kornia/feature/sold2/sold2_detector.py
index 533c58368..a29d1f512 100644
--- a/kornia/feature/sold2/sold2_detector.py
+++ b/kornia/feature/sold2/sold2_detector.py
@@ -154,10 +154,10 @@ class LineSegmentDetectionModule:
use_candidate_suppression: bool = False,
nms_dist_tolerance: float = 3.0,
use_heatmap_refinement: bool = False,
- heatmap_refine_cfg=None,
+ heatmap_refine_cfg: Optional[Dict[str, Any]] = None,
use_junction_refinement: bool = False,
- junction_refine_cfg=None,
- ):
+ junction_refine_cfg: Optional[Dict[str, Any]] = None,
+ ) -> None:
# Line detection parameters
self.detect_thresh = detect_thresh
@@ -197,7 +197,7 @@ class LineSegmentDetectionModule:
device = junctions.device
# Perform the heatmap refinement
- if self.use_heatmap_refinement:
+ if self.use_heatmap_refinement and isinstance(self.heatmap_refine_cfg, dict):
if self.heatmap_refine_cfg["mode"] == "global":
heatmap = self.refine_heatmap(
heatmap, self.heatmap_refine_cfg["ratio"], self.heatmap_refine_cfg["valid_thresh"]
@@ -393,6 +393,8 @@ class LineSegmentDetectionModule:
) -> Tuple[Tensor, Tensor]:
"""Refine the line endpoints in a similar way as in LSD."""
# Fetch refinement parameters
+ if not isinstance(self.junction_refine_cfg, dict):
+ raise TypeError(f'Expected to have a dict of config for junction. Gotcha {type(self.junction_refine_cfg)}')
num_perturbs = self.junction_refine_cfg["num_perturbs"]
perturb_interval = self.junction_refine_cfg["perturb_interval"]
side_perturbs = (num_perturbs - 1) // 2
diff --git a/kornia/filters/blur_pool.py b/kornia/filters/blur_pool.py
index d7cfabcc7..1b2083422 100644
--- a/kornia/filters/blur_pool.py
+++ b/kornia/filters/blur_pool.py
@@ -126,7 +126,7 @@ class EdgeAwareBlurPool2D(Module):
)
-def blur_pool2d(input: Tensor, kernel_size: tuple[int, int] | int, stride: int = 2):
+def blur_pool2d(input: Tensor, kernel_size: tuple[int, int] | int, stride: int = 2) -> Tensor:
r"""Compute blurs and downsample a given feature map.
.. image:: _static/img/blur_pool2d.png
@@ -210,7 +210,7 @@ def max_blur_pool2d(
return _max_blur_pool_by_kernel2d(input, kernel, stride, max_pool_size, ceil_mode)
-def _blur_pool_by_kernel2d(input: Tensor, kernel: Tensor, stride: int):
+def _blur_pool_by_kernel2d(input: Tensor, kernel: Tensor, stride: int) -> Tensor:
"""Compute blur_pool by a given :math:`CxC_{out}xNxN` kernel."""
KORNIA_CHECK(
len(kernel.shape) == 4 and kernel.shape[-2] == kernel.shape[-1],
@@ -221,13 +221,14 @@ def _blur_pool_by_kernel2d(input: Tensor, kernel: Tensor, stride: int):
return F.conv2d(input, kernel, padding=padding, stride=stride, groups=input.shape[1])
-def _max_blur_pool_by_kernel2d(input: Tensor, kernel: Tensor, stride: int, max_pool_size: int, ceil_mode: bool):
+def _max_blur_pool_by_kernel2d(
+ input: Tensor, kernel: Tensor, stride: int, max_pool_size: int, ceil_mode: bool
+) -> Tensor:
"""Compute max_blur_pool by a given :math:`CxC_(out, None)xNxN` kernel."""
KORNIA_CHECK(
len(kernel.shape) == 4 and kernel.shape[-2] == kernel.shape[-1],
f"Invalid kernel shape. Expect CxC_outxNxN, Got {kernel.shape}",
)
-
# compute local maxima
input = F.max_pool2d(input, kernel_size=max_pool_size, padding=0, stride=1, ceil_mode=ceil_mode)
# blur and downsample
diff --git a/kornia/filters/dexined.py b/kornia/filters/dexined.py
index 6338e0fd5..bc6e9d973 100644
--- a/kornia/filters/dexined.py
+++ b/kornia/filters/dexined.py
@@ -119,7 +119,7 @@ class UpConvBlock(Module):
in_features = out_features
return layers
- def compute_out_features(self, idx: int, up_scale: int):
+ def compute_out_features(self, idx: int, up_scale: int) -> int:
return 1 if idx == up_scale - 1 else self.constant_features
def forward(self, x: Tensor, out_shape: list[int]) -> Tensor:
@@ -211,7 +211,7 @@ class DexiNed(Module):
else:
self.apply(weight_init)
- def load_from_file(self, path_file: str):
+ def load_from_file(self, path_file: str) -> None:
# use torch.hub to load pretrained model
pretrained_dict = torch.hub.load_state_dict_from_url(path_file, map_location=map_location_to_cpu)
self.load_state_dict(pretrained_dict, strict=True)
diff --git a/kornia/filters/kernels.py b/kornia/filters/kernels.py
index c09cb68ec..ad272fb2a 100644
--- a/kornia/filters/kernels.py
+++ b/kornia/filters/kernels.py
@@ -6,12 +6,12 @@ from typing import Any
import torch
-from kornia.core import Device, Tensor, concatenate, stack, tensor, where, zeros, zeros_like
+from kornia.core import Device, Dtype, Tensor, concatenate, stack, tensor, where, zeros, zeros_like
from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SHAPE, KORNIA_CHECK_TYPE
from kornia.utils import deprecated
-def _check_kernel_size(kernel_size: tuple[int, ...] | int, min_value: int = 0, allow_even: bool = False):
+def _check_kernel_size(kernel_size: tuple[int, ...] | int, min_value: int = 0, allow_even: bool = False) -> None:
if isinstance(kernel_size, int):
kernel_size = (kernel_size,)
@@ -61,7 +61,7 @@ def normalize_kernel2d(input: Tensor) -> Tensor:
def gaussian(
- window_size: int, sigma: Tensor | float, *, device: Device | None = None, dtype: torch.dtype | None = None
+ window_size: int, sigma: Tensor | float, *, device: Device | None = None, dtype: Dtype | None = None
) -> Tensor:
"""Compute the gaussian values based on the window and sigma values.
@@ -92,7 +92,7 @@ def gaussian(
def gaussian_discrete_erf(
- window_size: int, sigma: Tensor | float, *, device: Device | None = None, dtype: torch.dtype | None = None
+ window_size: int, sigma: Tensor | float, *, device: Device | None = None, dtype: Dtype | None = None
) -> Tensor:
r"""Discrete Gaussian by interpolating the error function.
@@ -219,7 +219,7 @@ def _modified_bessel_i(n: int, x: Tensor) -> Tensor:
def gaussian_discrete(
- window_size: int, sigma: Tensor | float, *, device: Device | None = None, dtype: torch.dtype | None = None
+ window_size: int, sigma: Tensor | float, *, device: Device | None = None, dtype: Dtype | None = None
) -> Tensor:
r"""Discrete Gaussian kernel based on the modified Bessel functions.
@@ -252,7 +252,7 @@ def gaussian_discrete(
return out / out.sum(-1, keepdim=True)
-def laplacian_1d(window_size: int, *, device: Device | None = None, dtype: torch.dtype = torch.float32) -> Tensor:
+def laplacian_1d(window_size: int, *, device: Device | None = None, dtype: Dtype = torch.float32) -> Tensor:
"""One could also use the Laplacian of Gaussian formula to design the filter."""
# TODO: add default dtype as None when kornia relies on torch > 1.12
filter_1d = torch.ones(window_size, device=device, dtype=dtype)
@@ -262,7 +262,7 @@ def laplacian_1d(window_size: int, *, device: Device | None = None, dtype: torch
def get_box_kernel2d(
- kernel_size: tuple[int, int] | int, *, device: Device | None = None, dtype: torch.dtype | None = None
+ kernel_size: tuple[int, int] | int, *, device: Device | None = None, dtype: Dtype | None = None
) -> Tensor:
r"""Utility function that returns a box filter."""
kx, ky = _unpack_2d_ks(kernel_size)
@@ -271,7 +271,7 @@ def get_box_kernel2d(
def get_binary_kernel2d(
- window_size: tuple[int, int] | int, *, device: Device | None = None, dtype: torch.dtype = torch.float32
+ window_size: tuple[int, int] | int, *, device: Device | None = None, dtype: Dtype = torch.float32
) -> Tensor:
"""Create a binary kernel to extract the patches.
@@ -289,12 +289,12 @@ def get_binary_kernel2d(
return kernel.view(window_range, 1, kx, ky)
-def get_sobel_kernel_3x3(*, device: Device | None = None, dtype: torch.dtype | None = None) -> Tensor:
+def get_sobel_kernel_3x3(*, device: Device | None = None, dtype: Dtype | None = None) -> Tensor:
"""Utility function that returns a sobel kernel of 3x3."""
return tensor([[-1.0, 0.0, 1.0], [-2.0, 0.0, 2.0], [-1.0, 0.0, 1.0]], device=device, dtype=dtype)
-def get_sobel_kernel_5x5_2nd_order(*, device: Device | None = None, dtype: torch.dtype | None = None) -> Tensor:
+def get_sobel_kernel_5x5_2nd_order(*, device: Device | None = None, dtype: Dtype | None = None) -> Tensor:
"""Utility function that returns a 2nd order sobel kernel of 5x5."""
return tensor(
[
@@ -309,7 +309,7 @@ def get_sobel_kernel_5x5_2nd_order(*, device: Device | None = None, dtype: torch
)
-def _get_sobel_kernel_5x5_2nd_order_xy(*, device: Device | None = None, dtype: torch.dtype | None = None) -> Tensor:
+def _get_sobel_kernel_5x5_2nd_order_xy(*, device: Device | None = None, dtype: Dtype | None = None) -> Tensor:
"""Utility function that returns a 2nd order sobel kernel of 5x5."""
return tensor(
[
@@ -324,12 +324,12 @@ def _get_sobel_kernel_5x5_2nd_order_xy(*, device: Device | None = None, dtype: t
)
-def get_diff_kernel_3x3(*, device: Device | None = None, dtype: torch.dtype | None = None) -> Tensor:
+def get_diff_kernel_3x3(*, device: Device | None = None, dtype: Dtype | None = None) -> Tensor:
"""Utility function that returns a first order derivative kernel of 3x3."""
return tensor([[-0.0, 0.0, 0.0], [-1.0, 0.0, 1.0], [-0.0, 0.0, 0.0]], device=device, dtype=dtype)
-def get_diff_kernel3d(device: Device | None = None, dtype: torch.dtype | None = None) -> Tensor:
+def get_diff_kernel3d(device: Device | None = None, dtype: Dtype | None = None) -> Tensor:
"""Utility function that returns a first order derivative kernel of 3x3x3."""
kernel = tensor(
[
@@ -355,7 +355,7 @@ def get_diff_kernel3d(device: Device | None = None, dtype: torch.dtype | None =
return kernel[:, None, ...]
-def get_diff_kernel3d_2nd_order(device: Device | None = None, dtype: torch.dtype | None = None) -> Tensor:
+def get_diff_kernel3d_2nd_order(device: Device | None = None, dtype: Dtype | None = None) -> Tensor:
"""Utility function that returns a first order derivative kernel of 3x3x3."""
kernel = tensor(
[
@@ -396,26 +396,26 @@ def get_diff_kernel3d_2nd_order(device: Device | None = None, dtype: torch.dtype
return kernel[:, None, ...]
-def get_sobel_kernel2d(*, device: Device | None = None, dtype: torch.dtype | None = None) -> Tensor:
+def get_sobel_kernel2d(*, device: Device | None = None, dtype: Dtype | None = None) -> Tensor:
kernel_x = get_sobel_kernel_3x3(device=device, dtype=dtype)
kernel_y = kernel_x.transpose(0, 1)
return stack([kernel_x, kernel_y])
-def get_diff_kernel2d(*, device: Device | None = None, dtype: torch.dtype | None = None) -> Tensor:
+def get_diff_kernel2d(*, device: Device | None = None, dtype: Dtype | None = None) -> Tensor:
kernel_x = get_diff_kernel_3x3(device=device, dtype=dtype)
kernel_y = kernel_x.transpose(0, 1)
return stack([kernel_x, kernel_y])
-def get_sobel_kernel2d_2nd_order(*, device: Device | None = None, dtype: torch.dtype | None = None) -> Tensor:
+def get_sobel_kernel2d_2nd_order(*, device: Device | None = None, dtype: Dtype | None = None) -> Tensor:
gxx = get_sobel_kernel_5x5_2nd_order(device=device, dtype=dtype)
gyy = gxx.transpose(0, 1)
gxy = _get_sobel_kernel_5x5_2nd_order_xy(device=device, dtype=dtype)
return stack([gxx, gxy, gyy])
-def get_diff_kernel2d_2nd_order(*, device: Device | None = None, dtype: torch.dtype | None = None) -> Tensor:
+def get_diff_kernel2d_2nd_order(*, device: Device | None = None, dtype: Dtype | None = None) -> Tensor:
gxx = tensor([[0.0, 0.0, 0.0], [1.0, -2.0, 1.0], [0.0, 0.0, 0.0]], device=device, dtype=dtype)
gyy = gxx.transpose(0, 1)
gxy = tensor([[-1.0, 0.0, 1.0], [0.0, 0.0, 0.0], [1.0, 0.0, -1.0]], device=device, dtype=dtype)
@@ -423,7 +423,7 @@ def get_diff_kernel2d_2nd_order(*, device: Device | None = None, dtype: torch.dt
def get_spatial_gradient_kernel2d(
- mode: str, order: int, *, device: Device | None = None, dtype: torch.dtype | None = None
+ mode: str, order: int, *, device: Device | None = None, dtype: Dtype | None = None
) -> Tensor:
r"""Function that returns kernel for 1st or 2nd order image gradients, using one of the following operators:
@@ -447,7 +447,7 @@ def get_spatial_gradient_kernel2d(
def get_spatial_gradient_kernel3d(
- mode: str, order: int, device: Device | None = None, dtype: torch.dtype | None = None
+ mode: str, order: int, device: Device | None = None, dtype: Dtype | None = None
) -> Tensor:
r"""Function that returns kernel for 1st or 2nd order scale pyramid gradients, using one of the following
operators: sobel, diff."""
@@ -470,7 +470,7 @@ def get_gaussian_kernel1d(
force_even: bool = False,
*,
device: Device | None = None,
- dtype: torch.dtype | None = None,
+ dtype: Dtype | None = None,
) -> Tensor:
r"""Function that returns Gaussian filter coefficients.
Args:
@@ -503,7 +503,7 @@ def get_gaussian_discrete_kernel1d(
force_even: bool = False,
*,
device: Device | None = None,
- dtype: torch.dtype | None = None,
+ dtype: Dtype | None = None,
) -> Tensor:
r"""Function that returns Gaussian filter coefficients based on the modified Bessel functions. Adapted from:
https://github.com/Project-MONAI/MONAI/blob/master/monai/networks/layers/convutils.py.
@@ -537,7 +537,7 @@ def get_gaussian_erf_kernel1d(
force_even: bool = False,
*,
device: Device | None = None,
- dtype: torch.dtype | None = None,
+ dtype: Dtype | None = None,
) -> Tensor:
r"""Function that returns Gaussian filter coefficients by interpolating the error function, adapted from:
https://github.com/Project-MONAI/MONAI/blob/master/monai/networks/layers/convutils.py.
@@ -571,7 +571,7 @@ def get_gaussian_kernel2d(
force_even: bool = False,
*,
device: Device | None = None,
- dtype: torch.dtype | None = None,
+ dtype: Dtype | None = None,
) -> Tensor:
r"""Function that returns Gaussian filter matrix coefficients.
Args:
@@ -623,7 +623,7 @@ def get_gaussian_kernel3d(
force_even: bool = False,
*,
device: Device | None = None,
- dtype: torch.dtype | None = None,
+ dtype: Dtype | None = None,
) -> Tensor:
r"""Function that returns Gaussian filter matrix coefficients.
Args:
@@ -675,9 +675,7 @@ def get_gaussian_kernel3d(
return kernel_3d
-def get_laplacian_kernel1d(
- kernel_size: int, *, device: Device | None = None, dtype: torch.dtype = torch.float32
-) -> Tensor:
+def get_laplacian_kernel1d(kernel_size: int, *, device: Device | None = None, dtype: Dtype = torch.float32) -> Tensor:
r"""Function that returns the coefficients of a 1D Laplacian filter.
Args:
kernel_size: filter size. It should be odd and positive.
@@ -701,7 +699,7 @@ def get_laplacian_kernel1d(
def get_laplacian_kernel2d(
- kernel_size: tuple[int, int] | int, *, device: Device | None = None, dtype: torch.dtype = torch.float32
+ kernel_size: tuple[int, int] | int, *, device: Device | None = None, dtype: Dtype = torch.float32
) -> Tensor:
r"""Function that returns Gaussian filter matrix coefficients.
Args:
@@ -738,11 +736,7 @@ def get_laplacian_kernel2d(
def get_pascal_kernel_2d(
- kernel_size: tuple[int, int] | int,
- norm: bool = True,
- *,
- device: Device | None = None,
- dtype: torch.dtype | None = None,
+ kernel_size: tuple[int, int] | int, norm: bool = True, *, device: Device | None = None, dtype: Dtype | None = None
) -> Tensor:
"""Generate pascal filter kernel by kernel size.
Args:
@@ -778,7 +772,7 @@ def get_pascal_kernel_2d(
def get_pascal_kernel_1d(
- kernel_size: int, norm: bool = False, *, device: Device | None = None, dtype: torch.dtype | None = None
+ kernel_size: int, norm: bool = False, *, device: Device | None = None, dtype: Dtype | None = None
) -> Tensor:
"""Generate Yang Hui triangle (Pascal's triangle) by a given number.
Args:
@@ -822,7 +816,7 @@ def get_pascal_kernel_1d(
return out
-def get_canny_nms_kernel(device: Device | None = None, dtype: torch.dtype | None = None) -> Tensor:
+def get_canny_nms_kernel(device: Device | None = None, dtype: Dtype | None = None) -> Tensor:
"""Utility function that returns 3x3 kernels for the Canny Non-maximal suppression."""
return tensor(
[
@@ -840,7 +834,7 @@ def get_canny_nms_kernel(device: Device | None = None, dtype: torch.dtype | None
)
-def get_hysteresis_kernel(device: Device | None = None, dtype: torch.dtype | None = None) -> Tensor:
+def get_hysteresis_kernel(device: Device | None = None, dtype: Dtype | None = None) -> Tensor:
"""Utility function that returns the 3x3 kernels for the Canny hysteresis."""
return tensor(
[
@@ -858,7 +852,7 @@ def get_hysteresis_kernel(device: Device | None = None, dtype: torch.dtype | Non
)
-def get_hanning_kernel1d(kernel_size: int, device: Device | None = None, dtype: torch.dtype | None = None) -> Tensor:
+def get_hanning_kernel1d(kernel_size: int, device: Device | None = None, dtype: Dtype | None = None) -> Tensor:
r"""Returns Hanning (also known as Hann) kernel, used in signal processing and KCF tracker.
.. math:: w(n) = 0.5 - 0.5cos\\left(\\frac{2\\pi{n}}{M-1}\\right)
@@ -885,7 +879,7 @@ def get_hanning_kernel1d(kernel_size: int, device: Device | None = None, dtype:
def get_hanning_kernel2d(
- kernel_size: tuple[int, int] | int, device: Device | None = None, dtype: torch.dtype | None = None
+ kernel_size: tuple[int, int] | int, device: Device | None = None, dtype: Dtype | None = None
) -> Tensor:
"""Returns 2d Hanning kernel, used in signal processing and KCF tracker.
Args:
diff --git a/kornia/filters/motion.py b/kornia/filters/motion.py
index 1c979403f..107023f0e 100644
--- a/kornia/filters/motion.py
+++ b/kornia/filters/motion.py
@@ -52,7 +52,7 @@ class MotionBlur(Module):
f'angle={self.angle}, direction={self.direction}, border_type={self.border_type})'
)
- def forward(self, x: Tensor):
+ def forward(self, x: Tensor) -> Tensor:
return motion_blur(x, self.kernel_size, self.angle, self.direction, self.border_type)
@@ -112,7 +112,7 @@ class MotionBlur3D(Module):
f'angle={self.angle}, direction={self.direction}, border_type={self.border_type})'
)
- def forward(self, x: Tensor):
+ def forward(self, x: Tensor) -> Tensor:
return motion_blur3d(x, self.kernel_size, self.angle, self.direction, self.border_type)
diff --git a/kornia/geometry/boxes.py b/kornia/geometry/boxes.py
index 6190faf9f..833055af9 100644
--- a/kornia/geometry/boxes.py
+++ b/kornia/geometry/boxes.py
@@ -216,12 +216,12 @@ class Boxes:
self._data = boxes
self._mode = mode
- def __getitem__(self, key) -> Boxes:
+ def __getitem__(self, key: slice | int | Tensor) -> Boxes:
new_box = type(self)(self._data[key], False)
new_box._mode = self._mode
return new_box
- def __setitem__(self, key, value: Boxes) -> Boxes:
+ def __setitem__(self, key: slice | int | Tensor, value: Boxes) -> Boxes:
self._data[key] = value._data
return self
@@ -733,12 +733,12 @@ class Boxes3D:
self._data = boxes
self._mode = mode
- def __getitem__(self, key) -> Boxes3D:
+ def __getitem__(self, key: slice | int | Tensor) -> Boxes3D:
new_box = Boxes3D(self._data[key], False, mode="xyzxyz_plus")
new_box._mode = self._mode
return new_box
- def __setitem__(self, key, value: Boxes3D) -> Boxes3D:
+ def __setitem__(self, key: slice | int | Tensor, value: Boxes3D) -> Boxes3D:
self._data[key] = value._data
return self
diff --git a/kornia/geometry/camera/pinhole.py b/kornia/geometry/camera/pinhole.py
index b065354e4..cfda3b6be 100644
--- a/kornia/geometry/camera/pinhole.py
+++ b/kornia/geometry/camera/pinhole.py
@@ -1,4 +1,4 @@
-from typing import Iterable, List
+from typing import Iterable, List, Union
import torch
@@ -153,7 +153,7 @@ class PinholeCamera:
return self.extrinsics[..., 0, -1]
@tx.setter
- def tx(self, value) -> 'PinholeCamera':
+ def tx(self, value: Union[Tensor, float, int]) -> 'PinholeCamera':
r"""Set the x-coordinate of the translation vector with the given value."""
self.extrinsics[..., 0, -1] = value
return self
@@ -168,7 +168,7 @@ class PinholeCamera:
return self.extrinsics[..., 1, -1]
@ty.setter
- def ty(self, value) -> 'PinholeCamera':
+ def ty(self, value: Union[Tensor, float, int]) -> 'PinholeCamera':
r"""Set the y-coordinate of the translation vector with the given value."""
self.extrinsics[..., 1, -1] = value
return self
@@ -183,7 +183,7 @@ class PinholeCamera:
return self.extrinsics[..., 2, -1]
@tz.setter
- def tz(self, value) -> 'PinholeCamera':
+ def tz(self, value: Union[Tensor, float, int]) -> 'PinholeCamera':
r"""Set the y-coordinate of the translation vector with the given value."""
self.extrinsics[..., 2, -1] = value
return self
@@ -240,7 +240,7 @@ class PinholeCamera:
"""
return self.intrinsics.inverse()
- def scale(self, scale_factor) -> 'PinholeCamera':
+ def scale(self, scale_factor: Tensor) -> 'PinholeCamera':
r"""Scale the pinhole model.
Args:
@@ -262,7 +262,7 @@ class PinholeCamera:
width: Tensor = scale_factor * self.width.clone()
return PinholeCamera(intrinsics, self.extrinsics, height, width)
- def scale_(self, scale_factor) -> 'PinholeCamera':
+ def scale_(self, scale_factor: Union[float, int, Tensor]) -> 'PinholeCamera':
r"""Scale the pinhole model in-place.
Args:
@@ -307,7 +307,7 @@ class PinholeCamera:
P = self.intrinsics @ self.extrinsics
return convert_points_from_homogeneous(transform_points(P, point_3d))
- def unproject(self, point_2d: Tensor, depth: Tensor):
+ def unproject(self, point_2d: Tensor, depth: Tensor) -> Tensor:
r"""Unproject a 2d point in 3d.
Transform coordinates in the pixel frame to the world frame.
@@ -343,8 +343,20 @@ class PinholeCamera:
# NOTE: just for test. Decide if we keep it.
@classmethod
def from_parameters(
- self, fx, fy, cx, cy, height, width, tx, ty, tz, batch_size, device: Device, dtype: torch.dtype
- ):
+ self,
+ fx: Tensor,
+ fy: Tensor,
+ cx: Tensor,
+ cy: Tensor,
+ height: int,
+ width: int,
+ tx: Tensor,
+ ty: Tensor,
+ tz: Tensor,
+ batch_size: int,
+ device: Device,
+ dtype: torch.dtype,
+ ) -> 'PinholeCamera':
# create the camera matrix
intrinsics = torch.zeros(batch_size, 4, 4, device=device, dtype=dtype)
intrinsics[..., 0, 0] += fx
diff --git a/kornia/geometry/camera/stereo.py b/kornia/geometry/camera/stereo.py
index 5be257243..1b027e1bd 100644
--- a/kornia/geometry/camera/stereo.py
+++ b/kornia/geometry/camera/stereo.py
@@ -1,3 +1,5 @@
+from typing import Any
+
import torch
from kornia.core import Tensor, stack, zeros
@@ -6,7 +8,7 @@ from kornia.utils.grid import create_meshgrid
class StereoException(Exception):
- def __init__(self, msg: str, *args, **kwargs):
+ def __init__(self, msg: str, *args: Any, **kwargs: Any) -> None:
r"""Custom exception for the :module:`~kornia.geometry.camera.stereo` module.
Adds a general helper module redirecting the user to the proper documentation site.
@@ -46,7 +48,7 @@ class StereoCamera:
self._Q_matrix = self._init_Q_matrix()
@staticmethod
- def _check_stereo_camera(rectified_left_camera: Tensor, rectified_right_camera: Tensor):
+ def _check_stereo_camera(rectified_left_camera: Tensor, rectified_right_camera: Tensor) -> None:
r"""Utility function to ensure user specified correct camera matrices.
Args:
@@ -221,7 +223,7 @@ class StereoCamera:
return reproject_disparity_to_3D(disparity_tensor, self.Q)
-def _check_disparity_tensor(disparity_tensor: Tensor):
+def _check_disparity_tensor(disparity_tensor: Tensor) -> None:
r"""Utility function to ensure correct user provided correct disparity tensor.
Args:
@@ -248,7 +250,7 @@ def _check_disparity_tensor(disparity_tensor: Tensor):
)
-def _check_Q_matrix(Q_matrix: Tensor):
+def _check_Q_matrix(Q_matrix: Tensor) -> None:
r"""Utility function to ensure Q matrix is of correct form.
Args:
diff --git a/kornia/geometry/conversions.py b/kornia/geometry/conversions.py
index ba7e875ba..85a13db65 100644
--- a/kornia/geometry/conversions.py
+++ b/kornia/geometry/conversions.py
@@ -1242,7 +1242,7 @@ def normalize_homography3d(
return dst_norm_trans_src_norm
-def normalize_points_with_intrinsics(point_2d: Tensor, camera_matrix: Tensor):
+def normalize_points_with_intrinsics(point_2d: Tensor, camera_matrix: Tensor) -> Tensor:
"""Normalizes points with intrinsics. Useful for conversion of keypoints to be used with essential matrix.
Args:
@@ -1284,7 +1284,7 @@ def normalize_points_with_intrinsics(point_2d: Tensor, camera_matrix: Tensor):
return xy
-def denormalize_points_with_intrinsics(point_2d_norm: Tensor, camera_matrix: Tensor):
+def denormalize_points_with_intrinsics(point_2d_norm: Tensor, camera_matrix: Tensor) -> Tensor:
"""Normalizes points with intrinsics. Useful for conversion of keypoints to be used with essential matrix.
Args:
diff --git a/kornia/geometry/depth.py b/kornia/geometry/depth.py
index 58417b9f6..b90c83100 100644
--- a/kornia/geometry/depth.py
+++ b/kornia/geometry/depth.py
@@ -347,7 +347,7 @@ def depth_warp(
height: int,
width: int,
align_corners: bool = True,
-):
+) -> Tensor:
r"""Function that warps a tensor from destination frame to reference given the depth in the reference frame.
See :class:`~kornia.geometry.warp.DepthWarper` for details.
diff --git a/kornia/geometry/keypoints.py b/kornia/geometry/keypoints.py
index fbc27f04a..e3a6b2c5c 100644
--- a/kornia/geometry/keypoints.py
+++ b/kornia/geometry/keypoints.py
@@ -38,11 +38,11 @@ class Keypoints:
self._data = keypoints
- def __getitem__(self, key) -> "Keypoints":
+ def __getitem__(self, key: Union[slice, int, Tensor]) -> "Keypoints":
new_obj = type(self)(self._data[key], False)
return new_obj
- def __setitem__(self, key, value: "Keypoints") -> "Keypoints":
+ def __setitem__(self, key: Union[slice, int, Tensor], value: "Keypoints") -> "Keypoints":
self._data[key] = value._data
return self
@@ -225,20 +225,20 @@ class Keypoints3D:
self._data = keypoints
- def __getitem__(self, key) -> "Keypoints3D":
+ def __getitem__(self, key: Union[slice, int, Tensor]) -> "Keypoints3D":
new_obj = type(self)(self._data[key], False)
return new_obj
- def __setitem__(self, key, value: "Keypoints3D") -> "Keypoints3D":
+ def __setitem__(self, key: Union[slice, int, Tensor], value: "Keypoints3D") -> "Keypoints3D":
self._data[key] = value._data
return self
@property
- def shape(self):
+ def shape(self) -> torch.Size:
return self.data.shape
@property
- def data(self):
+ def data(self) -> Tensor:
return self._data
def pad(self, padding_size: Tensor) -> "Keypoints3D":
diff --git a/kornia/geometry/liegroup/se2.py b/kornia/geometry/liegroup/se2.py
index 0c79bcffd..dd3450cb2 100644
--- a/kornia/geometry/liegroup/se2.py
+++ b/kornia/geometry/liegroup/se2.py
@@ -1,8 +1,21 @@
# kornia.geometry.se2 module inspired by Sophus-sympy.
# https://github.com/strasdat/Sophus/blob/master/sympy/sophus/se2.py
-from typing import Optional, Tuple, overload
-
-from kornia.core import Module, Parameter, Tensor, concatenate, pad, rand, stack, tensor, where, zeros_like
+from typing import Optional, Tuple, Union, overload
+
+from kornia.core import (
+ Device,
+ Dtype,
+ Module,
+ Parameter,
+ Tensor,
+ concatenate,
+ pad,
+ rand,
+ stack,
+ tensor,
+ where,
+ 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.so2 import So2
@@ -55,7 +68,7 @@ class Se2(Module):
def __repr__(self) -> str:
return f"rotation: {self.r}\ntranslation: {self.t}"
- def __getitem__(self, idx) -> 'Se2':
+ def __getitem__(self, idx: Union[int, slice]) -> 'Se2':
return Se2(self._rotation[idx], self._translation[idx])
@overload
@@ -116,7 +129,7 @@ class Se2(Module):
return self._translation
@staticmethod
- def exp(v) -> 'Se2':
+ def exp(v: Tensor) -> 'Se2':
"""Converts elements of lie algebra to elements of lie group.
Args:
@@ -186,7 +199,7 @@ class Se2(Module):
return pad(col0, (0, 1))
@staticmethod
- def vee(omega) -> Tensor:
+ def vee(omega: Tensor) -> Tensor:
"""Converts elements from lie algebra to vector space.
Args:
@@ -208,7 +221,7 @@ class Se2(Module):
return concatenate((upsilon, theta[..., None]), -1)
@classmethod
- def identity(cls, batch_size: Optional[int] = None, device=None, dtype=None) -> 'Se2':
+ def identity(cls, batch_size: Optional[int] = None, device: Optional[Device] = None, dtype: Dtype = None) -> 'Se2':
"""Create a Se2 group representing an identity rotation and zero translation.
Args:
@@ -262,7 +275,7 @@ class Se2(Module):
return Se2(r_inv, t_inv)
@classmethod
- def random(cls, batch_size: Optional[int] = None, device=None, dtype=None) -> 'Se2':
+ def random(cls, batch_size: Optional[int] = None, device: Optional[Device] = None, dtype: Dtype = None) -> 'Se2':
"""Create a Se2 group representing a random transformation.
Args:
diff --git a/kornia/geometry/liegroup/se3.py b/kornia/geometry/liegroup/se3.py
index 784b22bb9..9a1782457 100644
--- a/kornia/geometry/liegroup/se3.py
+++ b/kornia/geometry/liegroup/se3.py
@@ -1,8 +1,22 @@
# kornia.geometry.so3 module inspired by Sophus-sympy.
# https://github.com/strasdat/Sophus/blob/master/sympy/sophus/se3.py
-from typing import Optional, Tuple
-
-from kornia.core import Module, Parameter, Tensor, concatenate, eye, pad, rand, stack, tensor, where, zeros_like
+from typing import Optional, Tuple, Union
+
+from kornia.core import (
+ Device,
+ Dtype,
+ Module,
+ Parameter,
+ Tensor,
+ concatenate,
+ eye,
+ pad,
+ rand,
+ stack,
+ tensor,
+ where,
+ zeros_like,
+)
from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_SAME_DEVICES, KORNIA_CHECK_TYPE
from kornia.geometry.liegroup.so3 import So3
from kornia.geometry.linalg import batched_dot_product
@@ -56,7 +70,7 @@ class Se3(Module):
def __repr__(self) -> str:
return f"rotation: {self.r}\ntranslation: {self.t}"
- def __getitem__(self, idx) -> 'Se3':
+ def __getitem__(self, idx: Union[int, slice]) -> 'Se3':
return Se3(self._rotation[idx], self._translation[idx])
def __mul__(self, right: "Se3") -> "Se3":
@@ -109,7 +123,7 @@ class Se3(Module):
return self._translation
@staticmethod
- def exp(v) -> 'Se3':
+ def exp(v: Tensor) -> 'Se3':
"""Converts elements of lie algebra to elements of lie group.
Args:
@@ -162,7 +176,7 @@ class Se3(Module):
return concatenate((t, omega), -1)
@staticmethod
- def hat(v) -> Tensor:
+ def hat(v: Tensor) -> Tensor:
"""Converts elements from vector space to lie algebra.
Args:
@@ -186,7 +200,7 @@ class Se3(Module):
return pad(rt, (0, 0, 0, 1)) # add zeros bottom
@staticmethod
- def vee(omega) -> Tensor:
+ def vee(omega: Tensor) -> Tensor:
"""Converts elements from lie algebra to vector space.
Args:
@@ -207,7 +221,7 @@ class Se3(Module):
return concatenate((head, tail), -1)
@classmethod
- def identity(cls, batch_size: Optional[int] = None, device=None, dtype=None) -> 'Se3':
+ def identity(cls, batch_size: Optional[int] = None, device: Optional[Device] = None, dtype: Dtype = None) -> 'Se3':
"""Create a Se3 group representing an identity rotation and zero translation.
Args:
@@ -222,7 +236,7 @@ class Se3(Module):
Parameter containing:
tensor([0., 0., 0.], requires_grad=True)
"""
- t: Tensor = tensor([0.0, 0.0, 0.0], device=device, dtype=dtype)
+ t = tensor([0.0, 0.0, 0.0], device=device, dtype=dtype)
if batch_size is not None:
t = t.repeat(batch_size, 1)
@@ -261,7 +275,7 @@ class Se3(Module):
return Se3(r_inv, r_inv * (-1 * self.t))
@classmethod
- def random(cls, batch_size: Optional[int] = None, device=None, dtype=None) -> 'Se3':
+ def random(cls, batch_size: Optional[int] = None, device: Optional[Device] = None, dtype: Dtype = None) -> 'Se3':
"""Create a Se3 group representing a random transformation.
Args:
diff --git a/kornia/geometry/liegroup/so2.py b/kornia/geometry/liegroup/so2.py
index a00539c08..4cf862dcf 100644
--- a/kornia/geometry/liegroup/so2.py
+++ b/kornia/geometry/liegroup/so2.py
@@ -1,8 +1,8 @@
# kornia.geometry.so2 module inspired by Sophus-sympy.
# https://github.com/strasdat/Sophus/blob/master/sympy/sophus/so2.py
-from typing import Optional, overload
+from typing import Optional, Union, overload
-from kornia.core import Module, Parameter, Tensor, complex, rand, stack, tensor, zeros_like
+from kornia.core import Device, Dtype, Module, Parameter, Tensor, complex, rand, stack, tensor, zeros_like
from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR
from kornia.geometry.liegroup._utils import (
check_so2_matrix_shape,
@@ -53,7 +53,7 @@ class So2(Module):
def __repr__(self) -> str:
return f"{self.z}"
- def __getitem__(self, idx: int) -> 'So2':
+ def __getitem__(self, idx: Union[int, slice]) -> 'So2':
return So2(self._z[idx])
@overload
@@ -192,7 +192,7 @@ class So2(Module):
return cls(z)
@classmethod
- def identity(cls, batch_size: Optional[int] = None, device=None, dtype=None) -> 'So2':
+ def identity(cls, batch_size: Optional[int] = None, device: Optional[Device] = None, dtype: Dtype = None) -> 'So2':
"""Create a So2 group representing an identity rotation.
Args:
@@ -224,7 +224,7 @@ class So2(Module):
return So2(1 / self.z)
@classmethod
- def random(cls, batch_size: Optional[int] = None, device=None, dtype=None) -> 'So2':
+ def random(cls, batch_size: Optional[int] = None, device: Optional[Device] = None, dtype: Dtype = None) -> 'So2':
"""Create a So2 group representing a random rotation.
Args:
diff --git a/kornia/geometry/liegroup/so3.py b/kornia/geometry/liegroup/so3.py
index 40aaea62b..615f15056 100644
--- a/kornia/geometry/liegroup/so3.py
+++ b/kornia/geometry/liegroup/so3.py
@@ -1,8 +1,8 @@
# kornia.geometry.so3 module inspired by Sophus-sympy.
# https://github.com/strasdat/Sophus/blob/master/sympy/sophus/so3.py
-from typing import Optional
+from typing import Optional, Union
-from kornia.core import Module, Tensor, concatenate, stack, tensor, where, zeros, zeros_like
+from kornia.core import Device, Dtype, Module, Tensor, concatenate, stack, tensor, where, zeros, zeros_like
from kornia.core.check import KORNIA_CHECK_TYPE
from kornia.geometry.linalg import batched_dot_product
from kornia.geometry.quaternion import Quaternion
@@ -48,7 +48,7 @@ class So3(Module):
def __repr__(self) -> str:
return f"{self.q}"
- def __getitem__(self, idx) -> 'So3':
+ def __getitem__(self, idx: Union[int, slice]) -> 'So3':
return So3(self._q[idx])
def __mul__(self, right):
@@ -77,7 +77,7 @@ class So3(Module):
return self._q
@staticmethod
- def exp(v) -> 'So3':
+ def exp(v: Tensor) -> 'So3':
"""Converts elements of lie algebra to elements of lie group.
See more: https://vision.in.tum.de/_media/members/demmeln/nurlanov2021so3log.pdf
@@ -125,7 +125,7 @@ class So3(Module):
return omega
@staticmethod
- def hat(v) -> Tensor:
+ def hat(v: Tensor) -> Tensor:
"""Converts elements from vector space to lie algebra. Returns matrix of shape :math:`(B,3,3)`.
Args:
@@ -148,7 +148,7 @@ class So3(Module):
return stack((row0, row1, row2), -2)
@staticmethod
- def vee(omega) -> Tensor:
+ def vee(omega: Tensor) -> Tensor:
r"""Converts elements from lie algebra to vector space. Returns vector of shape :math:`(B,3)`.
.. math::
@@ -220,7 +220,7 @@ class So3(Module):
return cls(Quaternion.from_matrix(matrix))
@classmethod
- def identity(cls, batch_size: Optional[int] = None, device=None, dtype=None) -> 'So3':
+ def identity(cls, batch_size: Optional[int] = None, device: Optional[Device] = None, dtype: Dtype = None) -> 'So3':
"""Create a So3 group representing an identity rotation.
Args:
@@ -252,7 +252,7 @@ class So3(Module):
return So3(self.q.conj())
@classmethod
- def random(cls, batch_size: Optional[int] = None, device=None, dtype=None) -> 'So3':
+ def random(cls, batch_size: Optional[int] = None, device: Optional[Device] = None, dtype: Dtype = None) -> 'So3':
"""Create a So3 group representing a random rotation.
Args:
diff --git a/kornia/geometry/line.py b/kornia/geometry/line.py
index 627b7ec59..c120de2c0 100644
--- a/kornia/geometry/line.py
+++ b/kornia/geometry/line.py
@@ -46,7 +46,7 @@ class ParametrizedLine(Module):
def __repr__(self) -> str:
return str(self)
- def __getitem__(self, idx) -> Tensor:
+ def __getitem__(self, idx: int) -> Tensor:
return self.origin if idx == 0 else self.direction
def __iter__(self):
@@ -67,7 +67,7 @@ class ParametrizedLine(Module):
return self.direction.shape[-1]
@classmethod
- def through(cls, p0, p1) -> "ParametrizedLine":
+ def through(cls, p0: Tensor, p1: Tensor) -> "ParametrizedLine":
"""Constructs a parametrized line going from a point :math:`p0` to :math:`p1`.
Args:
diff --git a/kornia/geometry/quaternion.py b/kornia/geometry/quaternion.py
index cbb5d623d..c8aec96a3 100644
--- a/kornia/geometry/quaternion.py
+++ b/kornia/geometry/quaternion.py
@@ -5,7 +5,7 @@
from math import pi
from typing import Optional, Tuple, Union
-from kornia.core import Module, Parameter, Tensor, concatenate, rand, stack, tensor, where
+from kornia.core import Device, Dtype, Module, Parameter, Tensor, concatenate, rand, stack, tensor, where
from kornia.core.check import KORNIA_CHECK_TYPE
from kornia.geometry.conversions import (
QuaternionCoeffOrder,
@@ -72,7 +72,7 @@ class Quaternion(Module):
def __repr__(self) -> str:
return f"{self.data}"
- def __getitem__(self, idx) -> 'Quaternion':
+ def __getitem__(self, idx: Union[int, slice]) -> 'Quaternion':
return Quaternion(self.data[idx])
def __neg__(self) -> 'Quaternion':
@@ -274,7 +274,9 @@ class Quaternion(Module):
return cls(angle_axis_to_quaternion(axis_angle, order=QuaternionCoeffOrder.WXYZ))
@classmethod
- def identity(cls, batch_size: Optional[int] = None, device=None, dtype=None) -> 'Quaternion':
+ def identity(
+ cls, batch_size: Optional[int] = None, device: Optional[Device] = None, dtype: Dtype = None
+ ) -> 'Quaternion':
"""Create a quaternion representing an identity rotation.
Args:
@@ -286,7 +288,7 @@ class Quaternion(Module):
Parameter containing:
tensor([1., 0., 0., 0.], requires_grad=True)
"""
- data: Tensor = tensor([1.0, 0.0, 0.0, 0.0], device=device, dtype=dtype)
+ data = tensor([1.0, 0.0, 0.0, 0.0], device=device, dtype=dtype)
if batch_size is not None:
data = data.repeat(batch_size, 1)
return cls(data)
@@ -312,7 +314,9 @@ class Quaternion(Module):
# TODO: update signature
# def random(cls, shape: Optional[List] = None, device = None, dtype = None) -> 'Quaternion':
@classmethod
- def random(cls, batch_size: Optional[int] = None, device=None, dtype=None) -> 'Quaternion':
+ def random(
+ cls, batch_size: Optional[int] = None, device: Optional[Device] = None, dtype: Dtype = None
+ ) -> 'Quaternion':
"""Create a random unit quaternion of shape :math:`(B, 4)`.
Uniformly distributed across the rotation space as per: http://planning.cs.uiuc.edu/node198.html
diff --git a/kornia/geometry/subpix/dsnt.py b/kornia/geometry/subpix/dsnt.py
index 116cc3bbe..911364c1a 100644
--- a/kornia/geometry/subpix/dsnt.py
+++ b/kornia/geometry/subpix/dsnt.py
@@ -6,6 +6,7 @@ from typing import Tuple
import torch
import torch.nn.functional as F
+from kornia.core import Tensor, concatenate
from kornia.testing import check_is_tensor
from kornia.utils.grid import create_meshgrid
@@ -16,7 +17,7 @@ def _validate_batched_image_tensor_input(tensor):
raise ValueError(f"Invalid input shape, we expect BxCxHxW. Got: {tensor.shape}")
-def spatial_softmax2d(input: torch.Tensor, temperature: torch.Tensor = torch.tensor(1.0)) -> torch.Tensor:
+def spatial_softmax2d(input: Tensor, temperature: Tensor = torch.tensor(1.0)) -> Tensor:
r"""Apply the Softmax function over features in each image channel.
Note that this function behaves differently to :py:class:`torch.nn.Softmax2d`, which
@@ -43,14 +44,14 @@ def spatial_softmax2d(input: torch.Tensor, temperature: torch.Tensor = torch.ten
batch_size, channels, height, width = input.shape
temperature = temperature.to(device=input.device, dtype=input.dtype)
- x: torch.Tensor = input.view(batch_size, channels, -1)
+ x = input.view(batch_size, channels, -1)
- x_soft: torch.Tensor = F.softmax(x * temperature, dim=-1)
+ x_soft = F.softmax(x * temperature, dim=-1)
return x_soft.view(batch_size, channels, height, width)
-def spatial_expectation2d(input: torch.Tensor, normalized_coordinates: bool = True) -> torch.Tensor:
+def spatial_expectation2d(input: Tensor, normalized_coordinates: bool = True) -> Tensor:
r"""Compute the expectation of coordinate values using spatial probabilities.
The input heatmap is assumed to represent a valid spatial probability distribution,
@@ -77,30 +78,28 @@ def spatial_expectation2d(input: torch.Tensor, normalized_coordinates: bool = Tr
batch_size, channels, height, width = input.shape
# Create coordinates grid.
- grid: torch.Tensor = create_meshgrid(height, width, normalized_coordinates, input.device)
+ grid = create_meshgrid(height, width, normalized_coordinates, input.device)
grid = grid.to(input.dtype)
- pos_x: torch.Tensor = grid[..., 0].reshape(-1)
- pos_y: torch.Tensor = grid[..., 1].reshape(-1)
+ pos_x = grid[..., 0].reshape(-1)
+ pos_y = grid[..., 1].reshape(-1)
- input_flat: torch.Tensor = input.view(batch_size, channels, -1)
+ input_flat = input.view(batch_size, channels, -1)
# Compute the expectation of the coordinates.
- expected_y: torch.Tensor = torch.sum(pos_y * input_flat, -1, keepdim=True)
- expected_x: torch.Tensor = torch.sum(pos_x * input_flat, -1, keepdim=True)
+ expected_y = torch.sum(pos_y * input_flat, -1, keepdim=True)
+ expected_x = torch.sum(pos_x * input_flat, -1, keepdim=True)
- output: torch.Tensor = torch.cat([expected_x, expected_y], -1)
+ output = concatenate([expected_x, expected_y], -1)
return output.view(batch_size, channels, 2) # BxNx2
-def _safe_zero_division(numerator: torch.Tensor, denominator: torch.Tensor, eps: float = 1e-32) -> torch.Tensor:
+def _safe_zero_division(numerator: Tensor, denominator: Tensor, eps: float = 1e-32) -> Tensor:
return numerator / torch.clamp(denominator, min=eps)
-def render_gaussian2d(
- mean: torch.Tensor, std: torch.Tensor, size: Tuple[int, int], normalized_coordinates: bool = True
-):
+def render_gaussian2d(mean: Tensor, std: Tensor, size: Tuple[int, int], normalized_coordinates: bool = True) -> Tensor:
r"""Render the PDF of a 2D Gaussian distribution.
Args:
@@ -120,10 +119,10 @@ def render_gaussian2d(
height, width = size
# Create coordinates grid.
- grid: torch.Tensor = create_meshgrid(height, width, normalized_coordinates, mean.device)
+ grid = create_meshgrid(height, width, normalized_coordinates, mean.device)
grid = grid.to(mean.dtype)
- pos_x: torch.Tensor = grid[..., 0].view(height, width)
- pos_y: torch.Tensor = grid[..., 1].view(height, width)
+ pos_x = grid[..., 0].view(height, width)
+ pos_y = grid[..., 1].view(height, width)
# Gaussian PDF = exp(-(x - \mu)^2 / (2 \sigma^2))
# = exp(dists * ks),
diff --git a/kornia/geometry/subpix/spatial_soft_argmax.py b/kornia/geometry/subpix/spatial_soft_argmax.py
index 60038d4fa..a2a15be3c 100644
--- a/kornia/geometry/subpix/spatial_soft_argmax.py
+++ b/kornia/geometry/subpix/spatial_soft_argmax.py
@@ -159,7 +159,7 @@ class ConvSoftArgmax2d(Module):
f"output_value={self.output_value})"
)
- def forward(self, x: Tensor):
+ def forward(self, x: Tensor) -> Union[Tensor, Tuple[Tensor, Tensor]]:
return conv_soft_argmax2d(
x,
self.kernel_size,
@@ -213,7 +213,7 @@ class ConvSoftArgmax3d(Module):
f"output_value={self.output_value})"
)
- def forward(self, x: Tensor):
+ def forward(self, x: Tensor) -> Union[Tensor, Tuple[Tensor, Tensor]]:
return conv_soft_argmax3d(
x,
self.kernel_size,
@@ -620,5 +620,5 @@ class ConvQuadInterp3d(Module):
def __repr__(self) -> str:
return f"{self.__class__.__name__}(strict_maxima_bonus={self.strict_maxima_bonus})"
- def forward(self, x: Tensor):
+ def forward(self, x: Tensor) -> Tuple[Tensor, Tensor]:
return conv_quad_interp3d(x, self.strict_maxima_bonus, self.eps)
diff --git a/kornia/geometry/transform/elastic_transform.py b/kornia/geometry/transform/elastic_transform.py
index 4d3c15538..72e2405ec 100644
--- a/kornia/geometry/transform/elastic_transform.py
+++ b/kornia/geometry/transform/elastic_transform.py
@@ -1,8 +1,9 @@
-from typing import Tuple
+from typing import Tuple, Union
-import torch
import torch.nn.functional as F
+from kornia.core import Tensor, concatenate, tensor
+from kornia.core.check import KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SHAPE
from kornia.filters import filter2d
from kornia.filters.kernels import get_gaussian_kernel2d
from kornia.utils import create_meshgrid
@@ -11,15 +12,15 @@ __all__ = ["elastic_transform2d"]
def elastic_transform2d(
- image: torch.Tensor,
- noise: torch.Tensor,
+ image: Tensor,
+ noise: Tensor,
kernel_size: Tuple[int, int] = (63, 63),
- sigma: Tuple[float, float] = (32.0, 32.0),
- alpha: Tuple[float, float] = (1.0, 1.0),
+ sigma: Union[Tuple[float, float], Tensor] = (32.0, 32.0),
+ alpha: Union[Tuple[float, float], Tensor] = (1.0, 1.0),
align_corners: bool = False,
mode: str = 'bilinear',
padding_mode: str = 'zeros',
-) -> torch.Tensor:
+) -> Tensor:
r"""Apply elastic transform of images as described in :cite:`Simard2003BestPF`.
.. image:: _static/img/elastic_transform2d.png
@@ -38,10 +39,6 @@ def elastic_transform2d(
mode: Interpolation mode used by ```grid_sample```. Either ``'bilinear'`` or ``'nearest'``.
padding_mode: The padding used by ```grid_sample```. Either ``'zeros'``, ``'border'`` or ``'refection'``.
- .. note:
- ```sigma``` and ```alpha``` can also be a ``torch.Tensor``. However, you could not torchscript
- this function with tensor until PyTorch 1.8 is released.
-
Returns:
the elastically transformed input image with shape :math:`(B,C,H,W)`.
@@ -63,37 +60,38 @@ def elastic_transform2d(
>>> image_hat = elastic_transform2d(image, noise, (3, 3), alpha=alpha)
>>> image_hat.mean().backward()
"""
- if not isinstance(image, torch.Tensor):
- raise TypeError(f"Input image is not torch.Tensor. Got {type(image)}")
-
- if not isinstance(noise, torch.Tensor):
- raise TypeError(f"Input noise is not torch.Tensor. Got {type(noise)}")
-
- if not len(image.shape) == 4:
- raise ValueError(f"Invalid image shape, we expect BxCxHxW. Got: {image.shape}")
-
- if not len(noise.shape) == 4 or noise.shape[1] != 2:
- raise ValueError(f"Invalid noise shape, we expect Bx2xHxW. Got: {noise.shape}")
+ KORNIA_CHECK_IS_TENSOR(image)
+ KORNIA_CHECK_IS_TENSOR(noise)
+ KORNIA_CHECK_SHAPE(image, ['B', 'C', 'H', 'W'])
+ KORNIA_CHECK_SHAPE(noise, ['B', 'C', 'H', 'W'])
device, dtype = image.device, image.dtype
- if isinstance(sigma, tuple):
- sigma_t = torch.tensor(sigma, device=device, dtype=dtype)
- elif isinstance(sigma, torch.Tensor):
- sigma_t = sigma.to(device=device, dtype=dtype)
+ # if isinstance(sigma, tuple):
+ # sigma_t = tensor(sigma, device=device, dtype=dtype)
+ if isinstance(sigma, Tensor):
+ sigma = sigma.expand(2)[None, ...]
+ # sigma = sigma.to(device=device, dtype=dtype)
# Get Gaussian kernel for 'y' and 'x' displacement
- kernel_x: torch.Tensor = get_gaussian_kernel2d(kernel_size, sigma_t[0].expand(2).unsqueeze(0))
- kernel_y: torch.Tensor = get_gaussian_kernel2d(kernel_size, sigma_t[1].expand(2).unsqueeze(0))
+ kernel_x = get_gaussian_kernel2d(kernel_size, sigma) # _t[0].expand(2).unsqueeze(0))
+ kernel_y = get_gaussian_kernel2d(kernel_size, sigma) # _t[1].expand(2).unsqueeze(0))
+
+ if isinstance(alpha, Tensor):
+ alpha_x = alpha[0]
+ alpha_y = alpha[1]
+ else:
+ alpha_x = tensor(alpha[0], device=device, dtype=dtype)
+ alpha_y = tensor(alpha[1], device=device, dtype=dtype)
# Convolve over a random displacement matrix and scale them with 'alpha'
- disp_x: torch.Tensor = noise[:, :1]
- disp_y: torch.Tensor = noise[:, 1:]
+ disp_x = noise[:, :1]
+ disp_y = noise[:, 1:]
- disp_x = filter2d(disp_x, kernel=kernel_y, border_type='constant') * alpha[0]
- disp_y = filter2d(disp_y, kernel=kernel_x, border_type='constant') * alpha[1]
+ disp_x = filter2d(disp_x, kernel=kernel_y, border_type='constant') * alpha_x
+ disp_y = filter2d(disp_y, kernel=kernel_x, border_type='constant') * alpha_y
# stack and normalize displacement
- disp = torch.cat([disp_x, disp_y], dim=1).permute(0, 2, 3, 1)
+ disp = concatenate([disp_x, disp_y], 1).permute(0, 2, 3, 1)
# Warp image based on displacement matrix
_, _, h, w = image.shape
diff --git a/kornia/geometry/transform/homography_warper.py b/kornia/geometry/transform/homography_warper.py
index 8c126d15e..6f44153cc 100644
--- a/kornia/geometry/transform/homography_warper.py
+++ b/kornia/geometry/transform/homography_warper.py
@@ -1,17 +1,34 @@
from __future__ import annotations
-import torch
-import torch.nn as nn
+from abc import abstractmethod
+from typing import Any
+
import torch.nn.functional as F
+from kornia.core import Module, Tensor
from kornia.utils import create_meshgrid
from .imgwarp import homography_warp, warp_grid
-__all__ = ["HomographyWarper"]
+__all__ = ["HomographyWarper", "BaseWarper"]
+
+
+class BaseWarper(Module):
+ def __init__(self, height: int, width: int, *args: Any, **kwargs: Any) -> None:
+ super().__init__(*args, **kwargs)
+ self.height = height
+ self.width = width
+
+ @abstractmethod
+ def forward(self, patch_src: Tensor, src_homo_dst: Tensor | None = None) -> Tensor:
+ ...
+
+ @abstractmethod
+ def precompute_warp_grid(self, src_homo_dst: Tensor) -> None:
+ ...
-class HomographyWarper(nn.Module):
+class HomographyWarper(BaseWarper):
r"""Warp tensors by homographies.
.. math::
@@ -27,7 +44,7 @@ class HomographyWarper(nn.Module):
normalized_coordinates: whether to use a grid with normalized coordinates.
align_corners: interpolation flag.
"""
- _warped_grid: torch.Tensor | None
+ _warped_grid: Tensor | None
def __init__(
self,
@@ -38,20 +55,18 @@ class HomographyWarper(nn.Module):
normalized_coordinates: bool = True,
align_corners: bool = False,
) -> None:
- super().__init__()
- self.width: int = width
- self.height: int = height
- self.mode: str = mode
- self.padding_mode: str = padding_mode
- self.normalized_coordinates: bool = normalized_coordinates
- self.align_corners: bool = align_corners
+ super().__init__(height, width)
+ self.mode = mode
+ self.padding_mode = padding_mode
+ self.normalized_coordinates = normalized_coordinates
+ self.align_corners = align_corners
# create base grid to compute the flow
- self.grid: torch.Tensor = create_meshgrid(height, width, normalized_coordinates=normalized_coordinates)
+ self.grid = create_meshgrid(height, width, normalized_coordinates=normalized_coordinates)
# initialice the warped destination grid
self._warped_grid = None
- def precompute_warp_grid(self, src_homo_dst: torch.Tensor) -> None:
+ def precompute_warp_grid(self, src_homo_dst: Tensor) -> None:
r"""Compute and store internally the transformations of the points.
Useful when the same homography/homographies are reused.
@@ -65,7 +80,7 @@ class HomographyWarper(nn.Module):
"""
self._warped_grid = warp_grid(self.grid, src_homo_dst)
- def forward(self, patch_src: torch.Tensor, src_homo_dst: torch.Tensor | None = None) -> torch.Tensor:
+ def forward(self, patch_src: Tensor, src_homo_dst: Tensor | None = None) -> Tensor:
r"""Warp a tensor from source into reference frame.
Args:
diff --git a/kornia/geometry/transform/image_registrator.py b/kornia/geometry/transform/image_registrator.py
index 9e098e1c3..bbe4986da 100644
--- a/kornia/geometry/transform/image_registrator.py
+++ b/kornia/geometry/transform/image_registrator.py
@@ -1,20 +1,35 @@
-from typing import Callable, List, Tuple, Union
+from abc import abstractmethod
+from typing import Any, Callable, Dict, List, Optional, Tuple, Type, Union
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
-from kornia.core import Tensor
+from kornia.core import Module, Tensor
from kornia.geometry.conversions import angle_to_rotation_matrix, convert_affinematrix_to_homography
-from .homography_warper import HomographyWarper
+from .homography_warper import BaseWarper, HomographyWarper
from .pyramid import build_pyramid
-__all__ = ["ImageRegistrator", "Homography", "Similarity"]
+__all__ = ["ImageRegistrator", "Homography", "Similarity", "BaseModel"]
-class Homography(nn.Module):
+class BaseModel(Module):
+ @abstractmethod
+ def reset_model(self) -> None:
+ ...
+
+ @abstractmethod
+ def forward(self) -> Tensor:
+ ...
+
+ @abstractmethod
+ def forward_inverse(self) -> Tensor:
+ ...
+
+
+class Homography(BaseModel):
r"""Homography geometric model to be used together with ImageRegistrator module for the optimization-based
image registration."""
@@ -47,7 +62,7 @@ class Homography(nn.Module):
return torch.unsqueeze(torch.inverse(self.model), dim=0)
-class Similarity(nn.Module):
+class Similarity(BaseModel):
"""Similarity geometric model to be used together with ImageRegistrator module for the optimization-based image
registration.
@@ -102,7 +117,7 @@ class Similarity(nn.Module):
return torch.inverse(self.forward())
-class ImageRegistrator(nn.Module):
+class ImageRegistrator(Module):
r"""Module, which performs optimization-based image registration.
Args:
@@ -127,14 +142,14 @@ class ImageRegistrator(nn.Module):
# TODO: resolve better type, potentially using factory.
def __init__(
self,
- model_type='homography',
- optimizer=optim.Adam,
+ model_type: Union[str, BaseModel] = 'homography',
+ optimizer: Type[optim.Optimizer] = optim.Adam,
loss_fn: Callable[..., Tensor] = F.l1_loss,
pyramid_levels: int = 5,
lr: float = 1e-3,
num_iterations: int = 100,
tolerance: float = 1e-4,
- warper=None,
+ warper: Optional[Type[BaseWarper]] = None,
) -> None:
super().__init__()
# We provide pre-defined combinations or allow user to supply model
@@ -208,7 +223,9 @@ class ImageRegistrator(nn.Module):
"""
self.reset_model()
# ToDo: better parameter passing to optimizer
- opt: optim.Optimizer = self.optimizer(self.model.parameters(), lr=self.lr)
+ _opt_args: Dict[str, Any] = {}
+ _opt_args['lr'] = self.lr
+ opt = self.optimizer(self.model.parameters(), **_opt_args)
# compute the gaussian pyramids
# [::-1] because we have to register from coarse to fine
diff --git a/kornia/geometry/transform/imgwarp.py b/kornia/geometry/transform/imgwarp.py
index 6fce98316..075353bd0 100644
--- a/kornia/geometry/transform/imgwarp.py
+++ b/kornia/geometry/transform/imgwarp.py
@@ -625,7 +625,7 @@ def get_translation_matrix2d(translations: Tensor) -> Tensor:
return transform_h
-def get_shear_matrix2d(center: Tensor, sx: Tensor | None = None, sy: Tensor | None = None):
+def get_shear_matrix2d(center: Tensor, sx: Tensor | None = None, sy: Tensor | None = None) -> Tensor:
r"""Compose shear matrix Bx4x4 from the components.
Note: Ordered shearing, shear x-axis then y-axis.
@@ -729,7 +729,7 @@ def get_shear_matrix3d(
syz: Tensor | None = None,
szx: Tensor | None = None,
szy: Tensor | None = None,
-):
+) -> Tensor:
r"""Compose shear matrix Bx4x4 from the components.
Note: Ordered shearing, shear x-axis then y-axis then z-axis.
diff --git a/kornia/geometry/transform/pyramid.py b/kornia/geometry/transform/pyramid.py
index 02d09fa08..dba32676f 100644
--- a/kornia/geometry/transform/pyramid.py
+++ b/kornia/geometry/transform/pyramid.py
@@ -151,7 +151,7 @@ class ScalePyramid(Module):
f'double_image={self.double_image})'
)
- def get_kernel_size(self, sigma: float):
+ def get_kernel_size(self, sigma: float) -> int:
ksize = int(2.0 * 4.0 * sigma + 1.0)
# matches OpenCV, but may cause padding problem for small images
diff --git a/kornia/geometry/vector.py b/kornia/geometry/vector.py
index 0e1b08074..45b418da9 100644
--- a/kornia/geometry/vector.py
+++ b/kornia/geometry/vector.py
@@ -1,6 +1,6 @@
from typing import Optional, Tuple, Union, cast
-from kornia.core import Tensor, as_tensor, normalize, rand, stack
+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.geometry.linalg import batched_dot_product, batched_squared_norm
@@ -22,7 +22,7 @@ class Vector3(TensorWrapper):
def __repr__(self) -> str:
return f"x: {self.x}\ny: {self.y}\nz: {self.z}"
- def __getitem__(self, idx) -> "Vector3":
+ def __getitem__(self, idx: Union[slice, int, Tensor]) -> "Vector3":
return Vector3(self.data[idx, ...])
@property
@@ -47,7 +47,9 @@ class Vector3(TensorWrapper):
return Scalar(batched_squared_norm(self.data))
@classmethod
- def random(cls, shape: Optional[Tuple[int, ...]] = None, device=None, dtype=None) -> "Vector3":
+ def random(
+ cls, shape: Optional[Tuple[int, ...]] = None, device: Optional[Device] = None, dtype: Dtype = None
+ ) -> "Vector3":
if shape is None:
shape = ()
return cls(rand(shape + (3,), device=device, dtype=dtype))
@@ -74,7 +76,12 @@ class Vector3(TensorWrapper):
@classmethod
def from_coords(
- cls, x: Union[float, Tensor], y: Union[float, Tensor], z: Union[float, Tensor], device=None, dtype=None
+ cls,
+ x: Union[float, Tensor],
+ y: Union[float, Tensor],
+ z: Union[float, Tensor],
+ device: Optional[Device] = None,
+ dtype: Dtype = None,
) -> "Vector3":
KORNIA_CHECK(type(x) == type(y) == type(z))
KORNIA_CHECK(isinstance(x, (Tensor, float)))
@@ -93,7 +100,7 @@ class Vector2(TensorWrapper):
def __repr__(self) -> str:
return f"x: {self.x}\ny: {self.y}"
- def __getitem__(self, idx) -> "Vector2":
+ def __getitem__(self, idx: Union[slice, int, Tensor]) -> "Vector2":
return Vector2(self.data[idx, ...])
@property
@@ -114,13 +121,15 @@ class Vector2(TensorWrapper):
return Scalar(batched_squared_norm(self.data))
@classmethod
- def random(cls, shape: Optional[Tuple[int, ...]] = None, device=None, dtype=None) -> "Vector2":
+ def random(cls, shape: Optional[Tuple[int, ...]] = None, device: Device = None, dtype: Dtype = None) -> "Vector2":
if shape is None:
shape = ()
return cls(rand(shape + (2,), device=device, dtype=dtype))
@classmethod
- def from_coords(cls, x: Union[float, Tensor], y: Union[float, Tensor], device=None, dtype=None) -> "Vector2":
+ def from_coords(
+ cls, x: Union[float, Tensor], y: Union[float, Tensor], device: Device = None, dtype: Dtype = None
+ ) -> "Vector2":
KORNIA_CHECK(type(x) == type(y))
KORNIA_CHECK(isinstance(x, (Tensor, float)))
if isinstance(x, float):
diff --git a/kornia/losses/divergence.py b/kornia/losses/divergence.py
index 9331e7e0c..a417728b6 100644
--- a/kornia/losses/divergence.py
+++ b/kornia/losses/divergence.py
@@ -5,8 +5,10 @@ from __future__ import annotations
import torch
import torch.nn.functional as F
+from kornia.core import Tensor
-def _kl_div_2d(p: torch.Tensor, q: torch.Tensor) -> torch.Tensor:
+
+def _kl_div_2d(p: Tensor, q: Tensor) -> Tensor:
# D_KL(P || Q)
batch, chans, height, width = p.shape
unsummed_kl = F.kl_div(
@@ -16,7 +18,7 @@ def _kl_div_2d(p: torch.Tensor, q: torch.Tensor) -> torch.Tensor:
return kl_values
-def _js_div_2d(p: torch.Tensor, q: torch.Tensor) -> torch.Tensor:
+def _js_div_2d(p: Tensor, q: Tensor) -> Tensor:
# JSD(P || Q)
m = 0.5 * (p + q)
return 0.5 * _kl_div_2d(p, m) + 0.5 * _kl_div_2d(q, m)
@@ -25,13 +27,13 @@ def _js_div_2d(p: torch.Tensor, q: torch.Tensor) -> torch.Tensor:
# TODO: add this to the main module
-def _reduce_loss(losses: torch.Tensor, reduction: str) -> torch.Tensor:
+def _reduce_loss(losses: Tensor, reduction: str) -> Tensor:
if reduction == 'none':
return losses
return torch.mean(losses) if reduction == 'mean' else torch.sum(losses)
-def js_div_loss_2d(input: torch.Tensor, target: torch.Tensor, reduction: str = 'mean'):
+def js_div_loss_2d(input: Tensor, target: Tensor, reduction: str = 'mean') -> Tensor:
r"""Calculate the Jensen-Shannon divergence loss between heatmaps.
Args:
@@ -52,7 +54,7 @@ def js_div_loss_2d(input: torch.Tensor, target: torch.Tensor, reduction: str = '
return _reduce_loss(_js_div_2d(target, input), reduction)
-def kl_div_loss_2d(input: torch.Tensor, target: torch.Tensor, reduction: str = 'mean'):
+def kl_div_loss_2d(input: Tensor, target: Tensor, reduction: str = 'mean') -> Tensor:
r"""Calculate the Kullback-Leibler divergence loss between heatmaps.
Args:
diff --git a/kornia/losses/total_variation.py b/kornia/losses/total_variation.py
index bec32ecff..a96dbde2a 100644
--- a/kornia/losses/total_variation.py
+++ b/kornia/losses/total_variation.py
@@ -78,5 +78,5 @@ class TotalVariation(Module):
[1] https://en.wikipedia.org/wiki/Total_variation
"""
- def forward(self, img) -> Tensor:
+ def forward(self, img: Tensor) -> Tensor:
return total_variation(img)
diff --git a/kornia/metrics/accuracy.py b/kornia/metrics/accuracy.py
index 62c346aee..4d7799bf7 100644
--- a/kornia/metrics/accuracy.py
+++ b/kornia/metrics/accuracy.py
@@ -1,9 +1,9 @@
-from typing import List
+from typing import List, Tuple
-import torch
+from kornia.core import Tensor
-def accuracy(input: torch.Tensor, target: torch.Tensor, topk=(1,)) -> List[torch.Tensor]:
+def accuracy(input: Tensor, target: Tensor, topk: Tuple[int, ...] = (1,)) -> List[Tensor]:
"""Computes the accuracy over the k top predictions for the specified values of k.
Args:
diff --git a/kornia/metrics/average_meter.py b/kornia/metrics/average_meter.py
index 4c1928ae9..4e13a684a 100644
--- a/kornia/metrics/average_meter.py
+++ b/kornia/metrics/average_meter.py
@@ -10,12 +10,12 @@ class AverageMeter:
>>> stats = AverageMeter()
>>> acc1 = torch.tensor(0.99) # coming from K.metrics.accuracy
>>> stats.update(acc1, n=1) # where n is batch size usually
- >>> stats.avg
- tensor(0.9900)
+ >>> round(stats.avg, 2)
+ 0.99
"""
val: Union[int, float, bool, Tensor]
- avg: Union[int, float, Tensor]
+ _avg: Union[float, Tensor]
sum: Union[int, float, Tensor]
count: int
@@ -24,7 +24,7 @@ class AverageMeter:
def reset(self):
self.val = 0
- self.avg = 0
+ self._avg = 0
self.sum = 0
self.count = 0
@@ -32,4 +32,10 @@ class AverageMeter:
self.val = val
self.sum += val * n
self.count += n
- self.avg = self.sum / self.count
+ self._avg = self.sum / self.count
+
+ @property
+ def avg(self) -> float:
+ if isinstance(self._avg, Tensor):
+ return float(self._avg.item())
+ return self._avg
diff --git a/kornia/nerf/nerf_model.py b/kornia/nerf/nerf_model.py
index 756d3825f..0373660de 100755
--- a/kornia/nerf/nerf_model.py
+++ b/kornia/nerf/nerf_model.py
@@ -2,13 +2,13 @@ import torch
from torch import nn
from torch.nn import functional as F
-from kornia.core import Tensor
+from kornia.core import Module, Tensor
from kornia.nerf.positional_encoder import PositionalEncoder
from kornia.nerf.rays import sample_lengths, sample_ray_points
from kornia.nerf.renderer import IrregularRenderer, RegularRenderer
-class MLP(nn.Module):
+class MLP(Module):
r"""Class to represent a multi-layer perceptron. The MLP represents a deep NN of fully connected layers. The
network is build of user defined sub-units, each with a user defined number of layers. Skip connections span
between the sub-units. The model follows: Ben Mildenhall et el. (2020) at https://arxiv.org/abs/2003.08934.
@@ -20,7 +20,7 @@ class MLP(nn.Module):
num_hidden: Layer hidden dimensions: int
"""
- def __init__(self, num_dims, num_units: int = 2, num_unit_layers: int = 4, num_hidden: int = 128):
+ def __init__(self, num_dims: int, num_units: int = 2, num_unit_layers: int = 4, num_hidden: int = 128) -> None:
super().__init__()
self._num_unit_layers = num_unit_layers
layers = []
@@ -42,7 +42,7 @@ class MLP(nn.Module):
return out
-class NerfModel(nn.Module):
+class NerfModel(Module):
r"""Class to represent NeRF model.
Args:
@@ -65,8 +65,8 @@ class NerfModel(nn.Module):
num_units: int = 2,
num_unit_layers: int = 4,
num_hidden: int = 128, # FIXME: add as call argument
- log_space_encoding=True,
- ):
+ log_space_encoding: bool = True,
+ ) -> None:
super().__init__()
self._num_ray_points = num_ray_points
self._irregular_ray_sampling = irregular_ray_sampling
diff --git a/kornia/nerf/nerf_solver.py b/kornia/nerf/nerf_solver.py
index 3336f1273..fdc87b669 100755
--- a/kornia/nerf/nerf_solver.py
+++ b/kornia/nerf/nerf_solver.py
@@ -53,7 +53,7 @@ class NerfSolver:
batch_size: int,
num_ray_points: int,
irregular_ray_sampling: bool = True,
- log_space_encoding=True,
+ log_space_encoding: bool = True,
lr: float = 1.0e-3,
) -> None:
r"""Initializes training.
diff --git a/kornia/nerf/rays.py b/kornia/nerf/rays.py
index 62dcc8e01..b758a1103 100755
--- a/kornia/nerf/rays.py
+++ b/kornia/nerf/rays.py
@@ -30,7 +30,7 @@ class RaySampler:
self._min_depth = min_depth
self._max_depth = max_depth
self._ndc = ndc
- self._device = torch.device(device)
+ self._device = device
self._dtype = dtype
@property
@@ -54,7 +54,7 @@ class RaySampler:
return 0
return self.origins.shape[0]
- def _calc_ray_directions_cam(self, cameras: PinholeCamera, points_2d: Tensor):
+ def _calc_ray_directions_cam(self, cameras: PinholeCamera, points_2d: Tensor) -> Tensor:
# FIXME: This function should call perspective.unproject_points or, implement in PinholeCamera unproject to
# camera coordinates that will call perspective.unproject_points
fx = cameras.fx
@@ -345,7 +345,9 @@ class UniformRaySampler(RaySampler):
def __init__(self, min_depth: float, max_depth: float, ndc: bool, device: Device, dtype: torch.dtype) -> None:
super().__init__(min_depth, max_depth, ndc, device, dtype)
- def sample_points_2d(self, heights: Tensor, widths: Tensor, sampling_step=1) -> Dict[int, RaySampler.Points2D]:
+ def sample_points_2d(
+ self, heights: Tensor, widths: Tensor, sampling_step: int = 1
+ ) -> Dict[int, RaySampler.Points2D]:
r"""Uniformly sample pixel points in 2d for all scene camera pixels.
Args:
@@ -379,7 +381,9 @@ class UniformRaySampler(RaySampler):
self._calc_ray_params(cameras, points_2d_camera)
-def sample_lengths(num_rays: int, num_ray_points: int, device: Device, dtype: torch.dtype, irregular=False) -> Tensor:
+def sample_lengths(
+ num_rays: int, num_ray_points: int, device: Device, dtype: torch.dtype, irregular: bool = False
+) -> Tensor:
if num_ray_points <= 1:
raise ValueError('Number of ray points must be greater than 1')
if not irregular:
diff --git a/kornia/utils/helpers.py b/kornia/utils/helpers.py
index a1c162cde..d51a181fa 100644
--- a/kornia/utils/helpers.py
+++ b/kornia/utils/helpers.py
@@ -44,10 +44,12 @@ def map_location_to_cpu(storage: Union[str, Tensor], *args: Any, **kwargs: Any)
return storage
-def deprecated(replace_with: Optional[str] = None, version: Optional[str] = None, extra_reason: Optional[str] = None):
- def _deprecated(func: Callable[..., Any]):
+def deprecated(
+ replace_with: Optional[str] = None, version: Optional[str] = None, extra_reason: Optional[str] = None
+) -> Any:
+ def _deprecated(func: Callable[..., Any]) -> Any:
@wraps(func)
- def wrapper(*args, **kwargs):
+ def wrapper(*args: Any, **kwargs: Any) -> Any:
name = ""
beginning = f'Since kornia {version} the ' if version is not None else ''
diff --git a/kornia/utils/image.py b/kornia/utils/image.py
index 4cc989b15..217d2f79e 100644
--- a/kornia/utils/image.py
+++ b/kornia/utils/image.py
@@ -217,7 +217,7 @@ def perform_keep_shape_image(f: Callable[..., Tensor]) -> Callable[..., Tensor]:
"""
@wraps(f)
- def _wrapper(input: Tensor, *args, **kwargs) -> Tensor:
+ def _wrapper(input: Tensor, *args: Any, **kwargs: Any) -> Tensor:
if not isinstance(input, Tensor):
raise TypeError(f"Input input type is not a Tensor. Got {type(input)}")
@@ -249,7 +249,7 @@ def perform_keep_shape_video(f: Callable[..., Tensor]) -> Callable[..., Tensor]:
"""
@wraps(f)
- def _wrapper(input: Tensor, *args, **kwargs) -> Tensor:
+ def _wrapper(input: Tensor, *args: Any, **kwargs: Any) -> Tensor:
if not isinstance(input, Tensor):
raise TypeError(f"Input input type is not a Tensor. Got {type(input)}")
diff --git a/kornia/utils/memory.py b/kornia/utils/memory.py
index 71a47fe8e..77489be25 100644
--- a/kornia/utils/memory.py
+++ b/kornia/utils/memory.py
@@ -1,9 +1,11 @@
-import torch
+from typing import Any, Dict
+
+from kornia.core import Device, Module, Tensor, concatenate
def batched_forward(
- model: torch.nn.Module, data: torch.Tensor, device: torch.device, batch_size: int = 128, **kwargs
-) -> torch.Tensor:
+ model: Module, data: Tensor, device: Device, batch_size: int = 128, **kwargs: Dict[str, Any]
+) -> Tensor:
r"""Convenience function, which allows to run the forward in micro-batches.
When the just model.forward(data) does not fit into device memory, e.g. on laptop GPU.
@@ -45,6 +47,6 @@ def batched_forward(
if st >= end:
continue
out_list.append(model_dev(data[st:end].to(device), **kwargs))
- out = torch.cat(out_list, dim=0)
+ out = concatenate(out_list, 0)
return out.to(data.device)
return model(data, **kwargs)
diff --git a/kornia/utils/misc.py b/kornia/utils/misc.py
index f601f3bef..c480bc31d 100644
--- a/kornia/utils/misc.py
+++ b/kornia/utils/misc.py
@@ -1,7 +1,7 @@
-import torch
+from kornia.core import Tensor, eye, zeros
-def eye_like(n: int, input: torch.Tensor, shared_memory: bool = False) -> torch.Tensor:
+def eye_like(n: int, input: Tensor, shared_memory: bool = False) -> Tensor:
r"""Return a 2-D tensor with ones on the diagonal and zeros elsewhere with the same batch size as the input.
Args:
@@ -23,11 +23,12 @@ def eye_like(n: int, input: torch.Tensor, shared_memory: bool = False) -> torch.
if len(input.shape) < 1:
raise AssertionError(input.shape)
- identity = torch.eye(n, device=input.device).type(input.dtype)
+ identity = eye(n, device=input.device).type(input.dtype)
+
return identity[None].expand(input.shape[0], n, n) if shared_memory else identity[None].repeat(input.shape[0], 1, 1)
-def vec_like(n: int, tensor: torch.Tensor, shared_memory: bool = False):
+def vec_like(n: int, tensor: Tensor, shared_memory: bool = False) -> Tensor:
r"""Return a 2-D tensor with a vector containing zeros with the same batch size as the input.
Args:
@@ -49,5 +50,5 @@ def vec_like(n: int, tensor: torch.Tensor, shared_memory: bool = False):
if len(tensor.shape) < 1:
raise AssertionError(tensor.shape)
- vec = torch.zeros(n, 1, device=tensor.device, dtype=tensor.dtype)
+ vec = zeros(n, 1, device=tensor.device, dtype=tensor.dtype)
return vec[None].expand(tensor.shape[0], n, 1) if shared_memory else vec[None].repeat(tensor.shape[0], 1, 1)
diff --git a/kornia/x/callbacks.py b/kornia/x/callbacks.py
index 00182497f..54a309844 100644
--- a/kornia/x/callbacks.py
+++ b/kornia/x/callbacks.py
@@ -1,14 +1,16 @@
from pathlib import Path
-from typing import Callable, Optional
+from typing import Callable, Dict, Optional, Union
import torch
-import torch.nn as nn
+
+from kornia.core import Module
+from kornia.metrics import AverageMeter
from .utils import TrainerState
# default function to generate the filename in the model checkpoint
-def default_filename_fcn(x) -> str:
+def default_filename_fcn(x: Union[str, int]) -> str:
return f"model_{x}.pt"
@@ -44,7 +46,7 @@ class EarlyStopping:
self.best_score: Optional[float] = None
self.early_stop: bool = False
- def __call__(self, model: nn.Module, epoch: int, valid_metric) -> TrainerState:
+ def __call__(self, model: Module, epoch: int, valid_metric: Dict[str, AverageMeter]) -> TrainerState:
score: float = valid_metric[self.monitor].avg
if self.best_score is None:
@@ -95,7 +97,7 @@ class ModelCheckpoint:
# create directory
Path(self.filepath).mkdir(parents=True, exist_ok=True)
- def __call__(self, model: nn.Module, epoch: int, valid_metric) -> None:
+ def __call__(self, model: Module, epoch: int, valid_metric: Dict[str, AverageMeter]) -> None:
valid_metric_value: float = valid_metric[self.monitor].avg
if valid_metric_value > self.best_metric:
self.best_metric = valid_metric_value
diff --git a/kornia/x/trainer.py b/kornia/x/trainer.py
index 3626d94c3..6c991b715 100644
--- a/kornia/x/trainer.py
+++ b/kornia/x/trainer.py
@@ -67,7 +67,7 @@ class Trainer:
valid_dataloader: DataLoader[Any],
criterion: Optional[Module],
optimizer: Optimizer,
- scheduler: lr_scheduler.CosineAnnealingLR,
+ scheduler: lr_scheduler._LRScheduler,
config: Configuration,
callbacks: Dict[str, Callable[..., None]] = {},
) -> None:
@@ -194,7 +194,7 @@ class Trainer:
def augmentations(self, x: Dict[str, Tensor]) -> Dict[str, Tensor]:
return x
- def compute_metrics(self, *args: Tensor) -> Dict[str, float]:
+ def compute_metrics(self, *args: Any) -> Dict[str, float]:
"""Compute metrics during the evaluation."""
return {}
@@ -206,14 +206,14 @@ class Trainer:
def on_before_model(self, x: Dict[str, Tensor]) -> Dict[str, Tensor]:
return x
- def on_model(self, model, sample: Dict[str, Tensor]):
+ def on_model(self, model: Module, sample: Dict[str, Tensor]) -> Tensor:
return model(sample["input"])
- def on_after_model(self, output: Tensor, sample: Dict[str, Tensor]):
+ def on_after_model(self, output: Tensor, sample: Dict[str, Tensor]) -> None:
...
- def on_checkpoint(self, *args, **kwargs):
+ def on_checkpoint(self, *args: Any, **kwargs: Dict[str, Any]) -> None:
...
- def on_epoch_end(self, *args, **kwargs):
+ def on_epoch_end(self, *args: Any, **kwargs: Dict[str, Any]) -> None:
...
diff --git a/kornia/x/trainers.py b/kornia/x/trainers.py
index d6991b94f..fdb72e5ad 100644
--- a/kornia/x/trainers.py
+++ b/kornia/x/trainers.py
@@ -1,4 +1,4 @@
-from typing import Any, Callable, Dict, Optional
+from typing import Any, Callable, Dict, Optional, Tuple
from torch.optim import Optimizer, lr_scheduler
from torch.utils.data import DataLoader
@@ -80,7 +80,7 @@ class ObjectDetectionTrainer(Trainer):
self.loss_computed_by_model = loss_computed_by_model
self.num_classes = num_classes
- def on_model(self, model: Module, sample: Dict[str, Tensor]):
+ def on_model(self, model: Module, sample: Dict[str, Tensor]) -> Tensor:
if self.loss_computed_by_model and model.training:
return model(sample["input"], sample["target"])
return model(sample["input"])
@@ -95,7 +95,7 @@ class ObjectDetectionTrainer(Trainer):
raise RuntimeError("`criterion` should not be None if `loss_computed_by_model` is False.")
return self.criterion(*args)
- def compute_metrics(self, *args: Tensor) -> Dict[str, float]:
+ def compute_metrics(self, *args: Tuple[Dict[str, Tensor]]) -> Dict[str, float]:
if (
isinstance(args[0], dict)
and "boxes" in args[0]
diff --git a/pyproject.toml b/pyproject.toml
index 7d2c94968..2347e225b 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -147,6 +147,7 @@ files = ["kornia/"]
pretty = true
check_untyped_defs = true
disallow_any_generics = true
+disallow_incomplete_defs = true
show_error_codes = true
ignore_missing_imports = true
no_implicit_optional = true
diff --git a/test/geometry/transform/test_elastic_transform.py b/test/geometry/transform/test_elastic_transform.py
index 2d57f7a47..9f08437de 100644
--- a/test/geometry/transform/test_elastic_transform.py
+++ b/test/geometry/transform/test_elastic_transform.py
@@ -20,21 +20,32 @@ class TestElasticTransform:
assert elastic_transform2d(img, noise).shape == shape
def test_exception(self, device, dtype):
- with pytest.raises(TypeError):
- assert elastic_transform2d([0.0])
+ ex = torch.ones(1, device=device, dtype=dtype)
+ with pytest.raises(TypeError) as errinfo:
+ elastic_transform2d([0.0], ex)
+ assert "Not a Tensor type" in str(errinfo.value)
- with pytest.raises(TypeError):
- assert elastic_transform2d(torch.tensor(), 1)
+ with pytest.raises(TypeError) as errinfo:
+ elastic_transform2d(ex, 1)
+ assert "Not a Tensor type" in str(errinfo.value)
- with pytest.raises(ValueError):
+ with pytest.raises(TypeError) as errinfo:
img = torch.ones(1, 1, 1, device=device, dtype=dtype)
noise = torch.ones(1, 2, 1, 1, device=device, dtype=dtype)
- assert elastic_transform2d(img, noise)
+ elastic_transform2d(img, noise)
+ assert "shape must be [['B', 'C', 'H', 'W']]" in str(errinfo.value)
- with pytest.raises(ValueError):
+ with pytest.raises(TypeError) as errinfo:
+ img = torch.ones(1, 1, 1, 1, device=device, dtype=dtype)
+ noise = torch.ones(2, 1, 1, device=device, dtype=dtype)
+ elastic_transform2d(img, noise)
+ assert "shape must be [['B', 'C', 'H', 'W']]" in str(errinfo.value)
+
+ with pytest.raises(RuntimeError) as errinfo:
img = torch.ones(1, 1, 1, 1, device=device, dtype=dtype)
noise = torch.ones(1, 3, 1, 1, device=device, dtype=dtype)
- assert elastic_transform2d(img, noise)
+ elastic_transform2d(img, noise)
+ assert "The size of tensor a (2) must match the size of tensor b (3)" in str(errinfo.value)
@pytest.mark.parametrize(
"kernel_size, sigma, alpha",
diff --git a/test/geometry/transform/test_image_registrator.py b/test/geometry/transform/test_image_registrator.py
index 4cc15d163..1474ccdb8 100644
--- a/test/geometry/transform/test_image_registrator.py
+++ b/test/geometry/transform/test_image_registrator.py
@@ -54,10 +54,10 @@ class TestHomography:
class TestImageRegistrator:
- def test_smoke(self, device, dtype):
- for model_type in ['homography', 'similarity', 'translation', 'scale', 'rotation']:
- ir = kornia.geometry.transform.ImageRegistrator(model_type).to(device, dtype)
- assert ir is not None
+ @pytest.mark.parametrize("model_type", ['homography', 'similarity', 'translation', 'scale', 'rotation'])
+ def test_smoke(self, device, dtype, model_type):
+ ir = kornia.geometry.transform.ImageRegistrator(model_type).to(device, dtype)
+ assert ir is not None
def test_registration_toy(self, device, dtype):
ch, height, width = 3, 16, 18
diff --git a/test/x/test_x.py b/test/x/test_x.py
index 7e02d0aad..e11b31ebd 100644
--- a/test/x/test_x.py
+++ b/test/x/test_x.py
@@ -17,7 +17,7 @@ class TestModelCheckpoint:
assert cb is not None
metric = {'test_monitor': AverageMeter()}
- metric['test_monitor'].avg = 1.0
+ metric['test_monitor']._avg = 1.0
cb(model, epoch=0, valid_metric=metric)
assert cb.best_metric == 1.0
@@ -28,7 +28,7 @@ class TestModelCheckpoint:
assert cb is not None
metric = {'test_monitor': AverageMeter()}
- metric['test_monitor'].avg = 1.0
+ metric['test_monitor']._avg = 1.0
cb(model, epoch=0, valid_metric=metric)
assert cb.best_metric == 1.0
@@ -41,26 +41,26 @@ def test_callback_earlystopping(model):
assert cb.counter == 0
metric = {'test_monitor': AverageMeter()}
- metric['test_monitor'].avg = 1
+ metric['test_monitor']._avg = 1
state = cb(model, epoch=0, valid_metric=metric)
assert state == TrainerState.TRAINING
assert cb.best_score == 1
assert cb.counter == 0
- metric['test_monitor'].avg = 2
+ metric['test_monitor']._avg = 2
state = cb(model, epoch=0, valid_metric=metric)
assert state == TrainerState.TRAINING
assert cb.best_score == 2
assert cb.counter == 0
- metric['test_monitor'].avg = 1.9
+ metric['test_monitor']._avg = 1.9
state = cb(model, epoch=0, valid_metric=metric)
assert state == TrainerState.TRAINING
assert cb.best_score == 2
assert cb.counter == 1
- metric['test_monitor'].avg = 1.9
+ metric['test_monitor']._avg = 1.9
state = cb(model, epoch=0, valid_metric=metric)
assert state == TrainerState.TERMINATE
assert cb.best_score == 2