🐍 Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
Remove type ignore from the codebase (#2030)
João Gustavo A. Amorim19c1cc0646ac
diff --git a/conftest.py b/conftest.pyindex 3e37a19bf..3143ab3f6 100644--- a/conftest.py+++ b/conftest.py@@ -24,7 +24,7 @@ def get_test_devices() -> Dict[str, torch.device]:devices["tpu"] = xm.xla_device()if hasattr(torch.backends, 'mps'):- if torch.backends.mps.is_available(): # type: ignore+ if torch.backends.mps.is_available():devices["mps"] = torch.device("mps")return devicesdiff --git a/kornia/augmentation/_2d/mix/base.py b/kornia/augmentation/_2d/mix/base.pyindex f3733f212..613c4008a 100644--- a/kornia/augmentation/_2d/mix/base.py+++ b/kornia/augmentation/_2d/mix/base.py@@ -5,7 +5,7 @@ import torchfrom kornia.augmentation.base import _BasicAugmentationBasefrom kornia.augmentation.utils import _transform_input, _transform_output_shape, _validate_input_dtypefrom kornia.constants import DataKey, DType-from kornia.core import Tensor+from kornia.core import Tensor, tensorfrom kornia.geometry.boxes import Boxesfrom kornia.testing import KORNIA_UNWRAP@@ -130,7 +130,7 @@ class MixAugmentationBaseV2(_BasicAugmentationBase):def apply_transform_class(self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Tensor:raise NotImplementedError- def forward( # type: ignore+ def forward( # type: ignore[override]self,*input: Tensor,params: Optional[Dict[str, Tensor]] = None,@@ -147,11 +147,11 @@ class MixAugmentationBaseV2(_BasicAugmentationBase):in_tensor: Tensor = input[in_tensor_idx]in_tensor = self.transform_tensor(in_tensor)self._params = self.forward_parameters(in_tensor.shape)- self._params.update({"dtype": torch.tensor(DType.get(in_tensor.dtype).value)})+ self._params.update({"dtype": tensor(DType.get(in_tensor.dtype).value)})else:self._params = params- outputs = []+ outputs: List[Tensor] = []for dcate, _input in zip(keys, input):output: Tensorif dcate == DataKey.INPUT:diff --git a/kornia/augmentation/base.py b/kornia/augmentation/base.pyindex 8d5793ed4..9eea719cb 100644--- a/kornia/augmentation/base.py+++ b/kornia/augmentation/base.py@@ -1,5 +1,5 @@from enum import Enum-from typing import Any, Dict, Optional, Tuple, Union+from typing import Any, Callable, Dict, Optional, Tuple, Unionimport torchfrom torch.distributions import Bernoulli@@ -11,6 +11,18 @@ from kornia.core import Module, Tensor, tensorTensorWithTransformMat = Union[Tensor, Tuple[Tensor, Tensor]]+# Trick mypy into not applying contravariance rules to inputs by defining+# 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:+ r"""Defines the computation performed at every call.++ Should be overridden by all subclasses.+ """+ raise NotImplementedError(f"Module [{type(self).__name__}] is missing the required \"apply_tranform\" function")++class _BasicAugmentationBase(Module):r"""_BasicAugmentationBase base class for customized augmentation implementations.@@ -49,6 +61,8 @@ class _BasicAugmentationBase(Module):self.flags: Dict[str, Any] = {}self.set_rng_device_and_dtype(torch.device('cpu'), torch.get_default_dtype())+ apply_transform: Callable[..., Tensor] = _apply_transform_unimplemented+def __repr__(self) -> str:txt = f"p={self.p}, p_batch={self.p_batch}, same_on_batch={self.same_on_batch}"if isinstance(self._param_generator, RandomGeneratorBase):@@ -76,9 +90,6 @@ class _BasicAugmentationBase(Module):return self._param_generator(batch_shape, self.same_on_batch)return {}- def apply_transform(self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Tensor:- raise NotImplementedError-def set_rng_device_and_dtype(self, device: torch.device, dtype: torch.dtype) -> None:"""Change the random generation device and dtype.diff --git a/kornia/augmentation/container/augment.py b/kornia/augmentation/container/augment.pyindex ae53f9b09..430c3ec81 100644--- a/kornia/augmentation/container/augment.py+++ b/kornia/augmentation/container/augment.py@@ -1,6 +1,6 @@import warningsfrom itertools import zip_longest-from typing import Any, Dict, List, Optional, Tuple, Union, cast+from typing import Any, Dict, List, Optional, Tuple, Unionfrom kornia.augmentation import (AugmentationBase3D,@@ -156,7 +156,7 @@ class AugmentationSequential(ImageSequential):random_apply_weights=random_apply_weights,)- self.data_keys: List[DataKey] = [DataKey.get(inp) for inp in data_keys]+ self.data_keys = [DataKey.get(inp) for inp in data_keys]if not all(in_type in DataKey for in_type in self.data_keys):raise AssertionError(f"`data_keys` must be in {DataKey}. Got {data_keys}.")@@ -188,7 +188,7 @@ class AugmentationSequential(ImageSequential):def transform_matrix(self) -> Optional[Tensor]:return self._transform_matrix- def inverse( # type: ignore+ def inverse( # type: ignore[override]self,*args: Tensor,params: Optional[List[ParamItem]] = None,@@ -216,7 +216,7 @@ class AugmentationSequential(ImageSequential):)params = self._params- outputs: List[Tensor] = [None] * len(_data_keys) # type: ignore+ outputs: List[Optional[Tensor]] = [None] * len(_data_keys)for idx, (arg, dcate) in enumerate(zip(args, _data_keys)):if dcate in self.extra_args:@@ -231,12 +231,18 @@ class AugmentationSequential(ImageSequential):input = arg.data # all boxes are in (B, N, 4, 2) format now.else:input = arg- for (name, module), param in zip_longest(list(self.get_forward_sequence(params))[::-1], params[::-1]):+ for (name, module), _param in zip_longest(list(self.get_forward_sequence(params))[::-1], params[::-1]):if isinstance(module, (_AugmentationBase, ImageSequential)):- # TODO(jian): verify what's happening here. Mypy was complaining,- param = params[name] if name in params else param # type: ignore+ _mb = [p for p in params if name in p]+ if len(_mb) > 0:+ param = _mb[0]+ elif isinstance(_param, ParamItem):+ param = _param+ else:+ param = Noneelse:param = None+if (isinstance(module, IntensityAugmentationBase2D)and dcate in DataKey@@ -270,21 +276,28 @@ class AugmentationSequential(ImageSequential):else:outputs[idx] = input- if len(outputs) == 1 and isinstance(outputs, (tuple, list)):- return outputs[0]+ _outputs = [i for i in outputs if isinstance(i, Tensor)]++ if len(_outputs) == 1 and isinstance(_outputs, list):+ return _outputs[0]- return outputs+ return _outputs- def __packup_output__( # type: ignore+ def __packup_output__( # type: ignore[override]self, output: List[Tensor], label: Optional[Tensor] = None- ) -> Union[Tensor, Tuple[Tensor, Optional[Tensor]], List[Tensor], Tuple[List[Tensor], Optional[Tensor]]]:- if len(output) == 1 and isinstance(output, (tuple, list)) and self.return_label:- return output[0], label- if len(output) == 1 and isinstance(output, (tuple, list)):- return output[0]+ ) -> Union[Tensor, List[Tensor], Tuple[Union[Tensor, List[Tensor]], Optional[Tensor]]]:++ _out: Union[Tensor, List[Tensor]]++ if len(output) == 1 and isinstance(output, list):+ _out = output[0]+ else:+ _out = output+if self.return_label:- return output, label- return output+ return _out, label++ return _outdef _validate_args_datakeys(self, *args: Tensor, data_keys: List[DataKey]):if len(args) != len(data_keys):@@ -312,13 +325,13 @@ class AugmentationSequential(ImageSequential):raise NotImplementedError(f"input type of {dcate} is not implemented.")return inp- def forward( # type: ignore+ def forward( # type: ignore[override]self,*args: Tensor,label: Optional[Tensor] = None,params: Optional[List[ParamItem]] = None,data_keys: Optional[List[Union[str, int, DataKey]]] = None,- ) -> Union[Tensor, Tuple[Tensor, Optional[Tensor]], List[Tensor], Tuple[List[Tensor], Optional[Tensor]]]:+ ) -> Union[Tensor, List[Tensor], Tuple[Union[Tensor, List[Tensor]], Optional[Tensor]]]:"""Compute multiple tensors simultaneously according to ``self.data_keys``."""if data_keys is None:_data_keys = self.data_keys@@ -332,8 +345,7 @@ class AugmentationSequential(ImageSequential):if params is None:# image data must exist if params is not provided.if DataKey.INPUT in _data_keys:- _input = args[_data_keys.index(DataKey.INPUT)]- inp = _input+ inp = args[_data_keys.index(DataKey.INPUT)]if isinstance(inp, (tuple, list)):raise ValueError(f"`INPUT` should be a tensor but `{type(inp)}` received.")# A video input shall be BCDHW while an image input shall be BCHW@@ -345,7 +357,7 @@ class AugmentationSequential(ImageSequential):else:raise ValueError("`params` must be provided whilst INPUT is not in data_keys.")- outputs: List[Tensor] = [None] * len(_data_keys) # type: ignore+ outputs: List[Optional[Tensor]] = [None] * len(_data_keys)self.return_label = self.return_label or label is not None or self.contains_label_operations(params)@@ -361,10 +373,12 @@ class AugmentationSequential(ImageSequential):_out = super().forward(_inp, label, params=params, extra_args=extra_args)self._transform_matrix = self.get_transformation_matrix(_inp, params=params)- if self.return_label:- _input, label = cast(Tuple[Tensor, Tensor], _out)- else:- _input = cast(Tensor, _out)++ if self.return_label and isinstance(_out, tuple):+ _input, label = _out+ elif isinstance(_out, Tensor):+ _input = _out+outputs[idx] = _input# NOTE: Skip the rest here.continue@@ -411,5 +425,5 @@ class AugmentationSequential(ImageSequential):outputs[idx] = arg.to_tensor()else:outputs[idx] = input-- return self.__packup_output__(outputs, label)+ _outputs = [i for i in outputs if isinstance(i, Tensor)]+ return self.__packup_output__(_outputs, label)diff --git a/kornia/augmentation/container/base.py b/kornia/augmentation/container/base.pyindex ab79062ca..fc445df46 100644--- a/kornia/augmentation/container/base.py+++ b/kornia/augmentation/container/base.py@@ -1,18 +1,20 @@from collections import OrderedDict-from typing import Any, Iterator, List, NamedTuple, Optional, Tuple, Union+from typing import Any, Dict, Iterator, List, NamedTuple, Optional, Tuple, Unionimport torchimport torch.nn as nnfrom kornia.augmentation import MixAugmentationBaseV2from kornia.augmentation.base import _AugmentationBase+from kornia.core import Module, Tensor__all__ = ["SequentialBase", "ParamItem"]class ParamItem(NamedTuple):name: str- data: Optional[Union[dict, list]]+ # TODO: add type List['ParamItem'] when mypy > 0.991 be available (see python/mypy#14200)+ data: Optional[Union[Dict[str, Tensor], list]]class SequentialBase(nn.Sequential):@@ -28,12 +30,12 @@ class SequentialBase(nn.Sequential):to the batch form (False). If None, it will not overwrite the function-wise settings."""- def __init__(self, *args: nn.Module, same_on_batch: Optional[bool] = None, keepdim: Optional[bool] = None) -> None:+ def __init__(self, *args: Module, same_on_batch: Optional[bool] = None, keepdim: Optional[bool] = None) -> None:# To name the modules properly_args = OrderedDict()for idx, mod in enumerate(args):- if not isinstance(mod, nn.Module):- raise NotImplementedError(f"Only nn.Module are supported at this moment. Got {mod}.")+ if not isinstance(mod, Module):+ raise NotImplementedError(f"Only Module are supported at this moment. Got {mod}.")_args.update({f"{mod.__class__.__name__}_{idx}": mod})super().__init__(_args)self._same_on_batch = same_on_batch@@ -60,7 +62,7 @@ class SequentialBase(nn.Sequential):if isinstance(mod, SequentialBase):mod.update_attribute(same_on_batch, return_transform, keepdim)- def get_submodule(self, target: str) -> nn.Module:+ def get_submodule(self, target: str) -> Module:"""Get submodule.This code is taken from torch 1.9.0 since it is not introduced@@ -73,18 +75,18 @@ class SequentialBase(nn.Sequential):fully-qualified string.)Returns:- torch.nn.Module: The submodule referenced by ``target``+ Module: The submodule referenced by ``target``Raises:AttributeError: If the target string references an invalidpath or resolves to something that is not an- ``nn.Module``+ ``Module``"""if target == "":return selfatoms: List[str] = target.split(".")- mod: torch.nn.Module = self+ mod: Module = selffor item in atoms:@@ -93,8 +95,8 @@ class SequentialBase(nn.Sequential):mod = getattr(mod, item)- if not isinstance(mod, torch.nn.Module):- raise AttributeError("`" + item + "` is not " "an nn.Module")+ if not isinstance(mod, Module):+ raise AttributeError("`" + item + "` is not " "an Module")return mod@@ -131,18 +133,18 @@ class SequentialBase(nn.Sequential):def forward_parameters(self, batch_shape: torch.Size) -> List[ParamItem]:raise NotImplementedError- def get_children_by_indices(self, indices: torch.Tensor) -> Iterator[Tuple[str, nn.Module]]:+ def get_children_by_indices(self, indices: Tensor) -> Iterator[Tuple[str, Module]]:modules = list(self.named_children())for idx in indices:yield modules[idx]- def get_children_by_params(self, params: List[ParamItem]) -> Iterator[Tuple[str, nn.Module]]:+ def get_children_by_params(self, params: List[ParamItem]) -> Iterator[Tuple[str, Module]]:modules = list(self.named_children())# TODO: Wrong params passed here when nested ImageSequentialfor param in params:yield modules[list(dict(self.named_children()).keys()).index(param.name)]- def get_params_by_module(self, named_modules: Iterator[Tuple[str, nn.Module]]) -> Iterator[ParamItem]:+ def get_params_by_module(self, named_modules: Iterator[Tuple[str, Module]]) -> Iterator[ParamItem]:# This will not take module._paramsfor name, _ in named_modules:yield ParamItem(name, None)@@ -150,7 +152,7 @@ class SequentialBase(nn.Sequential):def contains_label_operations(self, params: List) -> bool:raise NotImplementedError- def autofill_dim(self, input: torch.Tensor, dim_range: Tuple[int, int] = (2, 4)) -> Tuple[torch.Size, torch.Size]:+ def autofill_dim(self, input: Tensor, dim_range: Tuple[int, int] = (2, 4)) -> Tuple[torch.Size, torch.Size]:"""Fill tensor dim to the upper bound of dim_range.If input tensor dim is smaller than the lower bound of dim_range, an error will be thrown out.diff --git a/kornia/augmentation/container/image.py b/kornia/augmentation/container/image.pyindex a718286a7..a33ed22ba 100644--- a/kornia/augmentation/container/image.py+++ b/kornia/augmentation/container/image.py@@ -95,7 +95,7 @@ class ImageSequential(SequentialBase):) -> None:super().__init__(*args, same_on_batch=same_on_batch, keepdim=keepdim)- self.random_apply: Union[Tuple[int, int], bool] = self._read_random_apply(random_apply, len(args))+ self.random_apply = self._read_random_apply(random_apply, len(args))if random_apply_weights is not None and len(random_apply_weights) != len(self):raise ValueError("The length of `random_apply_weights` must be as same as the number of operations."@@ -142,7 +142,11 @@ class ImageSequential(SequentialBase):Note:Mix augmentations (e.g. RandomMixUp) will be only applied once even in a random forward."""- num_samples = int(torch.randint(*self.random_apply, (1,)).item()) # type: ignore+ if isinstance(self.random_apply, tuple):+ num_samples = int(torch.randint(*self.random_apply, (1,)).item())+ else:+ raise TypeError(f'random apply should be a tuple. Gotcha {type(self.random_apply)}')+multinomial_weights = self.random_apply_weights.clone()# Mix augmentation can only be applied once per forwardmix_indices = self.get_mix_augmentation_indices(self.named_children())@@ -228,10 +232,12 @@ class ImageSequential(SequentialBase):return Truereturn False- def __packup_output__(self, output: Tensor, label: Optional[Tensor] = None) -> Union[Tensor, Tuple[Tensor, Tensor]]:+ def __packup_output__(+ self, output: Tensor, label: Optional[Tensor] = None+ ) -> Union[Tensor, Tuple[Tensor, Optional[Tensor]]]:if self.return_label:- return output, label # type: ignore# Implicitly indicating the label cannot be optional since there is a mix aug+ return output, labelreturn outputdef identity_matrix(self, input) -> Tensor:@@ -260,9 +266,12 @@ class ImageSequential(SequentialBase):# Define as 1 for broadcastingres_mat: Optional[Tensor] = Nonefor (_, module), param in zip(named_modules, params if params is not None else []):- if isinstance(module, (_AugmentationBase,)) and not isinstance(module, MixAugmentationBaseV2):- pdata = cast(Dict[str, Tensor], param.data)- to_apply = pdata['batch_prob']+ if (+ isinstance(module, (_AugmentationBase,))+ and not isinstance(module, MixAugmentationBaseV2)+ and isinstance(param.data, dict)+ ):+ to_apply = param.data['batch_prob']ori_shape = input.shapetry:input = module.transform_tensor(input)@@ -273,7 +282,7 @@ class ImageSequential(SequentialBase):if recompute:mat: Tensor = self.identity_matrix(input)flags = override_parameters(module.flags, extra_args, in_place=False)- mat[to_apply] = module.compute_transformation(input[to_apply], param.data, flags) # type: ignore+ mat[to_apply] = module.compute_transformation(input[to_apply], param.data, flags)else:mat = as_tensor(module._transform_matrix, device=input.device, dtype=input.dtype)res_mat = mat if res_mat is None else mat @ res_mat@@ -333,17 +342,16 @@ class ImageSequential(SequentialBase):params = self._paramsfor (name, module), param in zip_longest(list(self.get_forward_sequence(params))[::-1], params[::-1]):- maybe_param: Optional[ParamItem] = Noneif isinstance(module, (_AugmentationBase, ImageSequential)):- maybe_param = params[name] if name in params else param # type: ignore+ _mb: List[ParamItem] = [p for p in params if name in p]+ maybe_param = _mb if len(_mb) > 0 else [param]if isinstance(module, IntensityAugmentationBase2D):pass # Do nothingelif isinstance(module, ImageSequential) and module.is_intensity_only():pass # Do nothing- elif isinstance(module, ImageSequential) and maybe_param is not None:- param_data = cast(List[ParamItem], cast(ParamItem, maybe_param).data)- input = module.inverse(input, param_data, extra_args=extra_args)+ elif isinstance(module, ImageSequential) and isinstance(maybe_param, ParamItem):+ input = module.inverse(input, maybe_param, extra_args=extra_args)elif isinstance(module, (GeometricAugmentationBase2D,)):input = self.apply_inverse_func.inverse(input, module, param, extra_args=extra_args)else:@@ -358,7 +366,7 @@ class ImageSequential(SequentialBase):label: Optional[Tensor] = None,params: Optional[List[ParamItem]] = None,extra_args: Dict[str, Any] = {},- ) -> Union[Tensor, Tuple[Tensor, Tensor]]:+ ) -> Union[Tensor, Tuple[Tensor, Optional[Tensor]]]:self.clear_state()if params is None:inp = inputdiff --git a/kornia/augmentation/container/patch.py b/kornia/augmentation/container/patch.pyindex 767afc8b8..5b365cde4 100644--- a/kornia/augmentation/container/patch.py+++ b/kornia/augmentation/container/patch.py@@ -1,14 +1,15 @@from itertools import cycle, islice-from typing import Iterator, List, NamedTuple, Optional, Tuple, Union+from typing import Any, Dict, Iterator, List, NamedTuple, Optional, Tuple, Unionimport torch-import torch.nn as nnfrom kornia.augmentation import MixAugmentationBaseV2from kornia.augmentation.base import _AugmentationBasefrom kornia.augmentation.container.base import SequentialBasefrom kornia.augmentation.container.image import ImageSequential, ParamItemfrom kornia.contrib.extract_patches import extract_tensor_patches+from kornia.core import Module, Tensor, concatenate+from kornia.core import pad as fpad__all__ = ["PatchSequential"]@@ -111,7 +112,7 @@ class PatchSequential(ImageSequential):def __init__(self,- *args: nn.Module,+ *args: Module,grid_size: Tuple[int, int] = (4, 4),padding: str = "same",same_on_batch: Optional[bool] = None,@@ -150,14 +151,14 @@ class PatchSequential(ImageSequential):self.padding = paddingself.patchwise_apply = patchwise_apply- def contains_label_operations(self, params: List[PatchParamItem]) -> bool: # type: ignore+ def contains_label_operations(self, params: List[PatchParamItem]) -> bool: # type: ignore[override]for param in params:if param.param.name.startswith("RandomMixUp") or param.param.name.startswith("RandomCutMix"):return Truereturn Falsedef compute_padding(- self, input: torch.Tensor, padding: str, grid_size: Optional[Tuple[int, int]] = None+ self, input: Tensor, padding: str, grid_size: Optional[Tuple[int, int]] = None) -> Tuple[int, int, int, int]:if grid_size is None:grid_size = self.grid_size@@ -172,10 +173,10 @@ class PatchSequential(ImageSequential):def extract_patches(self,- input: torch.Tensor,+ input: Tensor,grid_size: Optional[Tuple[int, int]] = None,pad: Optional[Tuple[int, int, int, int]] = None,- ) -> torch.Tensor:+ ) -> Tensor:"""Extract patches from tensor.Example:@@ -209,7 +210,7 @@ class PatchSequential(ImageSequential):[[[31, 32, 33]]]]])"""if pad is not None:- input = torch.nn.functional.pad(input, list(pad))+ input = fpad(input, list(pad))if grid_size is None:grid_size = self.grid_sizewindow_size = (input.size(-2) // grid_size[-2], input.size(-1) // grid_size[-1])@@ -217,11 +218,8 @@ class PatchSequential(ImageSequential):return extract_tensor_patches(input, window_size, stride)def restore_from_patches(- self,- patches: torch.Tensor,- grid_size: Tuple[int, int] = (4, 4),- pad: Optional[Tuple[int, int, int, int]] = None,- ) -> torch.Tensor:+ self, patches: Tensor, grid_size: Tuple[int, int] = (4, 4), pad: Optional[Tuple[int, int, int, int]] = None+ ) -> Tensor:"""Restore input from patches.Example:@@ -237,28 +235,28 @@ class PatchSequential(ImageSequential):if grid_size is None:grid_size = self.grid_sizepatches_tensor = patches.view(-1, grid_size[0], grid_size[1], *patches.shape[-3:])- restored_tensor = torch.cat(torch.chunk(patches_tensor, grid_size[0], dim=1), -2).squeeze(1)- restored_tensor = torch.cat(torch.chunk(restored_tensor, grid_size[1], dim=1), -1).squeeze(1)+ restored_tensor = concatenate(torch.chunk(patches_tensor, grid_size[0], 1), -2).squeeze(1)+ restored_tensor = concatenate(torch.chunk(restored_tensor, grid_size[1], 1), -1).squeeze(1)if pad is not None:- restored_tensor = torch.nn.functional.pad(restored_tensor, [-i for i in pad])+ restored_tensor = fpad(restored_tensor, [-i for i in pad])return restored_tensor- def forward_parameters(self, batch_shape: torch.Size) -> List[PatchParamItem]: # type: ignore+ def forward_parameters(self, batch_shape: torch.Size) -> List[PatchParamItem]: # type: ignore[override]out_param: List[PatchParamItem] = []if not self.patchwise_apply:params = self.generate_parameters(torch.Size([1, batch_shape[0] * batch_shape[1], *batch_shape[2:]]))indices = torch.arange(0, batch_shape[0] * batch_shape[1])- [out_param.append(PatchParamItem(indices.tolist(), p)) for p, _ in params] # type: ignore+ out_param = [PatchParamItem(indices.tolist(), p) for p, _ in params]# "append" of "list" does not return a valueelif not self.same_on_batch:params = self.generate_parameters(torch.Size([batch_shape[0] * batch_shape[1], 1, *batch_shape[2:]]))- [out_param.append(PatchParamItem([i], p)) for p, i in params] # type: ignore+ out_param = [PatchParamItem([i], p) for p, i in params]# "append" of "list" does not return a valueelse:params = self.generate_parameters(torch.Size([batch_shape[1], batch_shape[0], *batch_shape[2:]]))indices = torch.arange(0, batch_shape[0] * batch_shape[1], step=batch_shape[1])- [out_param.append(PatchParamItem((indices + i).tolist(), p)) for p, i in params] # type: ignore+ out_param = [PatchParamItem((indices + i).tolist(), p) for p, i in params]# "append" of "list" does not return a valuereturn out_param@@ -306,13 +304,13 @@ class PatchSequential(ImageSequential):yield ParamItem(s[0], None), idef apply_by_param(- self, input: torch.Tensor, label: Optional[torch.Tensor], params: PatchParamItem- ) -> Tuple[torch.Tensor, Optional[torch.Tensor], PatchParamItem]:- _input: torch.Tensor+ self, input: Tensor, label: Optional[Tensor], params: PatchParamItem+ ) -> Tuple[Tensor, Optional[Tensor], PatchParamItem]:+ _input: Tensorin_shape = input.shape_input = input[params.indices]- _label: Optional[torch.Tensor]+ _label: Optional[Tensor]if label is not None:_label = label[params.indices]else:@@ -362,14 +360,14 @@ class PatchSequential(ImageSequential):return input, _label, PatchParamItem(params.indices, param=out_param)def forward_by_params(- self, input: torch.Tensor, label: Optional[torch.Tensor], params: List[PatchParamItem]- ) -> Union[torch.Tensor, Tuple[torch.Tensor, Optional[torch.Tensor]]]:- _input: torch.Tensor+ self, input: Tensor, label: Optional[Tensor], params: List[PatchParamItem]+ ) -> Union[Tensor, Tuple[Tensor, Optional[Tensor]]]:+ _input: Tensorin_shape = input.shape_input = input.reshape(-1, *in_shape[-3:])if label is not None:- label = torch.cat([label] * in_shape[1], dim=0)+ label = concatenate([label] * in_shape[1], 0)self.clear_state()for patch_param in params:@@ -378,7 +376,9 @@ class PatchSequential(ImageSequential):_input = _input.reshape(in_shape)return _input, label- def inverse(self, input: torch.Tensor, params: List[ParamItem]) -> torch.Tensor: # type: ignore+ def inverse(+ self, input: Tensor, params: Optional[List[ParamItem]] = None, extra_args: Dict[str, Any] = {}+ ) -> Tensor:"""Inverse transformation.Used to inverse a tensor according to the performed transformation by a forward pass, or with respect to@@ -389,14 +389,14 @@ class PatchSequential(ImageSequential):raise NotImplementedError("PatchSequential inverse cannot be used with geometric transformations.")- def forward( # type: ignore- self, input: torch.Tensor, label: Optional[torch.Tensor] = None, params: Optional[List[PatchParamItem]] = None- ) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]:+ def forward( # type: ignore[override]+ self, input: Tensor, label: Optional[Tensor] = None, params: Optional[List[PatchParamItem]] = None+ ) -> Union[Tensor, Tuple[Tensor, Optional[Tensor]]]:"""Input transformation will be returned if input is a tuple."""# BCHW -> B(patch)CHWif isinstance(input, (tuple,)):raise ValueError("tuple input is not currently supported.")- _input: torch.Tensor+ _input: Tensorpad = self.compute_padding(input, self.padding)input = self.extract_patches(input, self.grid_size, pad)diff --git a/kornia/augmentation/container/utils.py b/kornia/augmentation/container/utils.pyindex 23edd42f7..f20060cd2 100644--- a/kornia/augmentation/container/utils.py+++ b/kornia/augmentation/container/utils.py@@ -87,10 +87,11 @@ class ApplyInverseImpl(ApplyInverseInterface):else:mat = cls._get_transformation(input, module, param, extra_args=extra_args)mat = as_tensor(mat, device=input.device, dtype=input.dtype)+to_apply = None- if isinstance(module, _AugmentationBase):- to_apply = param.data['batch_prob'] # type: ignore- if isinstance(module, kornia.augmentation.ImageSequential):+ if isinstance(module, _AugmentationBase) and isinstance(param.data, dict):+ to_apply = param.data['batch_prob']+ elif isinstance(module, kornia.augmentation.ImageSequential):to_apply = torch.ones(input.shape[0], device=input.device, dtype=input.dtype).bool()# If any inputs need to be transformed.@@ -334,9 +335,8 @@ class BBoxApplyInverse(ApplyInverseImpl):@classmethoddef _get_padding_size(cls, module: Module, param: Optional[ParamItem]) -> Optional[Tensor]:- if isinstance(module, RandomCrop):- _param = cast(Dict[str, Tensor], param.data) # type: ignore- return _param.get("padding_size")+ if isinstance(module, RandomCrop) and param is not None and isinstance(param.data, dict):+ return param.data["padding_size"]return None@classmethoddiff --git a/kornia/augmentation/container/video.py b/kornia/augmentation/container/video.pyindex ad1a1b920..69aea0a4b 100644--- a/kornia/augmentation/container/video.py+++ b/kornia/augmentation/container/video.py@@ -244,7 +244,7 @@ class VideoSequential(ImageSequential):label: Optional[Tensor] = None,params: Optional[List[ParamItem]] = None,extra_args: Dict[str, Any] = {},- ) -> Union[Tensor, Tuple[Tensor, Tensor]]:+ ) -> Union[Tensor, Tuple[Tensor, Optional[Tensor]]]:"""Define the video computation performed."""if len(input.shape) != 5:raise AssertionError(f"Input must be a 5-dim tensor. Got {input.shape}.")diff --git a/kornia/augmentation/random_generator/base.py b/kornia/augmentation/random_generator/base.pyindex cef44699f..0b77f4e1d 100644--- a/kornia/augmentation/random_generator/base.py+++ b/kornia/augmentation/random_generator/base.py@@ -1,10 +1,9 @@from typing import Callable, Dict, Optionalimport torch-import torch.nn as nnfrom torch.distributions import Distribution-from kornia.core import Device, Tensor+from kornia.core import Device, Module, Tensorclass _PostInitInjectionMetaClass(type):@@ -16,7 +15,7 @@ class _PostInitInjectionMetaClass(type):return obj-class RandomGeneratorBase(nn.Module, metaclass=_PostInitInjectionMetaClass):+class RandomGeneratorBase(Module, metaclass=_PostInitInjectionMetaClass):"""Base class for generating random augmentation parameters."""device: Optional[Device] = Nonediff --git a/kornia/augmentation/utils/helpers.py b/kornia/augmentation/utils/helpers.pyindex 1748effb3..032a61657 100644--- a/kornia/augmentation/utils/helpers.py+++ b/kornia/augmentation/utils/helpers.py@@ -196,8 +196,11 @@ def _adapted_rsampling(If same_on_batch is True, all values generated will be exactly same given a batch_size (shape[0]). By default,same_on_batch is set to False."""+ if isinstance(shape, tuple):+ shape = torch.Size(shape)+if same_on_batch:- return dist.rsample((1, *shape[1:])).repeat(shape[0], *[1] * (len(shape) - 1))+ return dist.rsample(torch.Size((1, *shape[1:]))).repeat(shape[0], *[1] * (len(shape) - 1))return dist.rsample(shape)@@ -209,8 +212,11 @@ def _adapted_sampling(If same_on_batch is True, all values generated will be exactly same given a batch_size (shape[0]). By default,same_on_batch is set to False."""+ if isinstance(shape, tuple):+ shape = torch.Size(shape)+if same_on_batch:- return dist.sample((1, *shape[1:])).repeat(shape[0], *[1] * (len(shape) - 1))+ return dist.sample(torch.Size((1, *shape[1:]))).repeat(shape[0], *[1] * (len(shape) - 1))return dist.sample(shape)diff --git a/kornia/color/hls.py b/kornia/color/hls.pyindex b7b99a8a8..e3649a8f4 100644--- a/kornia/color/hls.py+++ b/kornia/color/hls.py@@ -1,10 +1,12 @@import math+from typing import Tupleimport torch-import torch.nn as nn+from kornia.core import Module, Tensor, stack, tensor, where-def rgb_to_hls(image: torch.Tensor, eps: float = 1e-8) -> torch.Tensor:++def rgb_to_hls(image: Tensor, eps: float = 1e-8) -> Tensor:r"""Convert a RGB image to HLS... image:: _static/img/rgb_to_hls.png@@ -24,30 +26,19 @@ def rgb_to_hls(image: torch.Tensor, eps: float = 1e-8) -> torch.Tensor:>>> input = torch.rand(2, 3, 4, 5)>>> output = rgb_to_hls(input) # 2x3x4x5"""- if not isinstance(image, torch.Tensor):- raise TypeError(f"Input type is not a torch.Tensor. Got {type(image)}")+ if not isinstance(image, Tensor):+ raise TypeError(f"Input type is not a Tensor. Got {type(image)}")if len(image.shape) < 3 or image.shape[-3] != 3:raise ValueError(f"Input size must have a shape of (*, 3, H, W). Got {image.shape}")- if not torch.jit.is_scripting():- # weird way to use globals compiling with JIT even in the code not used by JIT...- # __setattr__ can be removed if pytorch version is > 1.6.0 and then use:- # rgb_to_hls.RGB2HSL_IDX = hls_to_rgb.RGB2HSL_IDX.to(image.device)- rgb_to_hls.__setattr__('RGB2HSL_IDX', rgb_to_hls.RGB2HSL_IDX.to(image)) # type: ignore- _RGB2HSL_IDX: torch.Tensor = rgb_to_hls.RGB2HSL_IDX # type: ignore- else:- _RGB2HSL_IDX = torch.tensor([[[0.0]], [[1.0]], [[2.0]]], device=image.device, dtype=image.dtype) # 3x1x1+ _RGB2HSL_IDX = tensor([[[0.0]], [[1.0]], [[2.0]]], device=image.device, dtype=image.dtype) # 3x1x1- # maxc: torch.Tensor # not supported by JIT- # imax: torch.Tensor # not supported by JIT- maxc, imax = image.max(-3)- minc: torch.Tensor = image.min(-3)[0]+ _img_max: Tuple[Tensor, Tensor] = image.max(-3)+ maxc = _img_max[0]+ imax = _img_max[1]+ minc: Tensor = image.min(-3)[0]- # h: torch.Tensor # not supported by JIT- # l: torch.Tensor # not supported by JIT- # s: torch.Tensor # not supported by JIT- # image_hls: torch.Tensor # not supported by JITif image.requires_grad:l_ = maxc + mincs = maxc - minc@@ -67,20 +58,20 @@ def rgb_to_hls(image: torch.Tensor, eps: float = 1e-8) -> torch.Tensor:torch.sub(maxc, minc, out=s) # s = max - min# precompute image / (max - min)- im: torch.Tensor = image / (s + eps).unsqueeze(-3)+ im = image / (s + eps).unsqueeze(-3)# epsilon cannot be inside the torch.where to avoid precision issues- s /= torch.where(l_ < 1.0, l_, 2.0 - l_) + eps # saturation+ s /= where(l_ < 1.0, l_, 2.0 - l_) + eps # saturationl_ /= 2 # luminance# note that r,g and b were previously div by (max - min)- r: torch.Tensor = torch.select(im, -3, 0)- g: torch.Tensor = torch.select(im, -3, 1)- b: torch.Tensor = torch.select(im, -3, 2)+ r = torch.select(im, -3, 0)+ g = torch.select(im, -3, 1)+ b = torch.select(im, -3, 2)# h[imax == 0] = (((g - b) / (max - min)) % 6)[imax == 0]# h[imax == 1] = (((b - r) / (max - min)) + 2)[imax == 1]# h[imax == 2] = (((r - g) / (max - min)) + 4)[imax == 2]- cond: torch.Tensor = imax.unsqueeze(-3) == _RGB2HSL_IDX+ cond = imax.unsqueeze(-3) == _RGB2HSL_IDXif image.requires_grad:h = torch.mul((g - b) % 6, torch.select(cond, -3, 0))else:@@ -91,11 +82,11 @@ def rgb_to_hls(image: torch.Tensor, eps: float = 1e-8) -> torch.Tensor:h *= math.pi / 3.0 # hue [0, 2*pi]if image.requires_grad:- return torch.stack([h, l_, s], dim=-3)+ return stack([h, l_, s], -3)return image_hls-def hls_to_rgb(image: torch.Tensor) -> torch.Tensor:+def hls_to_rgb(image: Tensor) -> Tensor:r"""Convert a HLS image to RGB.The image data is assumed to be in the range of (0, 1).@@ -110,45 +101,32 @@ def hls_to_rgb(image: torch.Tensor) -> torch.Tensor:>>> input = torch.rand(2, 3, 4, 5)>>> output = hls_to_rgb(input) # 2x3x4x5"""- if not isinstance(image, torch.Tensor):- raise TypeError(f"Input type is not a torch.Tensor. Got {type(image)}")+ if not isinstance(image, Tensor):+ raise TypeError(f"Input type is not a Tensor. Got {type(image)}")if len(image.shape) < 3 or image.shape[-3] != 3:raise ValueError(f"Input size must have a shape of (*, 3, H, W). Got {image.shape}")- if not torch.jit.is_scripting():- # weird way to use globals compiling with JIT even in the code not used by JIT...- # __setattr__ can be removed if pytorch version is > 1.6.0 and then use:- # hls_to_rgb.HLS2RGB = hls_to_rgb.HLS2RGB.to(image.device)- hls_to_rgb.__setattr__('HLS2RGB', hls_to_rgb.HLS2RGB.to(image)) # type: ignore- _HLS2RGB: torch.Tensor = hls_to_rgb.HLS2RGB # type: ignore- else:- _HLS2RGB = torch.tensor([[[0.0]], [[8.0]], [[4.0]]], device=image.device, dtype=image.dtype) # 3x1x1+ _HLS2RGB = tensor([[[0.0]], [[8.0]], [[4.0]]], device=image.device, dtype=image.dtype) # 3x1x1- im: torch.Tensor = image.unsqueeze(-4)- h: torch.Tensor = torch.select(im, -3, 0)- l: torch.Tensor = torch.select(im, -3, 1)- s: torch.Tensor = torch.select(im, -3, 2)+ im: Tensor = image.unsqueeze(-4)+ h: Tensor = torch.select(im, -3, 0)+ l: Tensor = torch.select(im, -3, 1)+ s: Tensor = torch.select(im, -3, 2)h = h * (6 / math.pi) # h * 360 / (2 * math.pi) / 30a = s * torch.min(l, 1.0 - l)# kr = (0 + h) % 12# kg = (8 + h) % 12# kb = (4 + h) % 12- k: torch.Tensor = (h + _HLS2RGB) % 12+ k: Tensor = (h + _HLS2RGB) % 12# l - a * max(min(min(k - 3.0, 9.0 - k), 1), -1)mink = torch.min(k - 3.0, 9.0 - k)return torch.addcmul(l, a, mink.clamp_(min=-1.0, max=1.0), value=-1)-# tricks to speed up a little bit the conversions by presetting small tensors-# (in the functions they are moved to the proper device)-hls_to_rgb.__setattr__('HLS2RGB', torch.tensor([[[0.0]], [[8.0]], [[4.0]]])) # 3x1x1-rgb_to_hls.__setattr__('RGB2HSL_IDX', torch.tensor([[[0.0]], [[1.0]], [[2.0]]])) # 3x1x1---class RgbToHls(nn.Module):+class RgbToHls(Module):r"""Convert an image from RGB to HLS.The image data is assumed to be in the range of (0, 1).@@ -166,11 +144,11 @@ class RgbToHls(nn.Module):>>> output = hls(input) # 2x3x4x5"""- def forward(self, image: torch.Tensor) -> torch.Tensor:+ def forward(self, image: Tensor) -> Tensor:return rgb_to_hls(image)-class HlsToRgb(nn.Module):+class HlsToRgb(Module):r"""Convert an image from HLS to RGB.The image data is assumed to be in the range of (0, 1).@@ -191,5 +169,5 @@ class HlsToRgb(nn.Module):>>> output = rgb(input) # 2x3x4x5"""- def forward(self, image: torch.Tensor) -> torch.Tensor:+ def forward(self, image: Tensor) -> Tensor:return hls_to_rgb(image)diff --git a/kornia/feature/defmo.py b/kornia/feature/defmo.pyindex 5a715dcbe..90ef3a96a 100644--- a/kornia/feature/defmo.py+++ b/kornia/feature/defmo.py@@ -3,6 +3,9 @@ from typing import Callable, Dict, List, Optional, Typeimport torchimport torch.nn as nn+from kornia.core import Module, Tensor, concatenate, stack+from kornia.utils.helpers import map_location_to_cpu+urls: Dict[str, str] = {}urls["defmo_encoder"] = "http://ptak.felk.cvut.cz/personal/rozumden/defmo_saved_models/encoder_best.pt"urls["defmo_rendering"] = "http://ptak.felk.cvut.cz/personal/rozumden/defmo_saved_models/rendering_best.pt"@@ -31,7 +34,7 @@ def conv3x3(in_planes: int, out_planes: int, stride: int = 1, groups: int = 1, d)-class Bottleneck(nn.Module):+class Bottleneck(Module):# Bottleneck in torchvision places the stride for downsampling at 3x3 convolution(self.conv2)# while original implementation places the stride at the first 1x1 convolution(self.conv1)# according to "Deep residual learning for image recognition"https://arxiv.org/abs/1512.03385.@@ -45,11 +48,11 @@ class Bottleneck(nn.Module):inplanes: int,planes: int,stride: int = 1,- downsample: Optional[nn.Module] = None,+ downsample: Optional[Module] = None,groups: int = 1,base_width: int = 64,dilation: int = 1,- norm_layer: Optional[Callable[..., nn.Module]] = None,+ norm_layer: Optional[Callable[..., Module]] = None,) -> None:super().__init__()if norm_layer is None:@@ -66,7 +69,7 @@ class Bottleneck(nn.Module):self.downsample = downsampleself.stride = stride- def forward(self, x: torch.Tensor) -> torch.Tensor:+ def forward(self, x: Tensor) -> Tensor:identity = xout = self.conv1(x)@@ -89,7 +92,7 @@ class Bottleneck(nn.Module):return out-class ResNet(nn.Module):+class ResNet(Module):def __init__(self,block: Type[Bottleneck],@@ -99,7 +102,7 @@ class ResNet(nn.Module):groups: int = 1,width_per_group: int = 64,replace_stride_with_dilation: Optional[List[bool]] = None,- norm_layer: Optional[Callable[..., nn.Module]] = None,+ norm_layer: Optional[Callable[..., Module]] = None,) -> None:super().__init__()if norm_layer is None:@@ -142,8 +145,8 @@ class ResNet(nn.Module):# This improves the model by 0.2~0.3% according to https://arxiv.org/abs/1706.02677if zero_init_residual:for m in self.modules():- if isinstance(m, Bottleneck):- nn.init.constant_(m.bn3.weight, 0) # type: ignore[arg-type]+ if isinstance(m, Bottleneck) and isinstance(m.bn3.weight, Tensor):+ nn.init.constant_(m.bn3.weight, 0)def _make_layer(self, block: Type[Bottleneck], planes: int, blocks: int, stride: int = 1, dilate: bool = False@@ -180,7 +183,7 @@ class ResNet(nn.Module):return nn.Sequential(*layers)- def _forward_impl(self, x: torch.Tensor) -> torch.Tensor:+ def _forward_impl(self, x: Tensor) -> Tensor:# See note [TorchScript super()]x = self.conv1(x)x = self.bn1(x)@@ -198,11 +201,11 @@ class ResNet(nn.Module):return x- def forward(self, x: torch.Tensor) -> torch.Tensor:+ def forward(self, x: Tensor) -> Tensor:return self._forward_impl(x)-class EncoderDeFMO(nn.Module):+class EncoderDeFMO(Module):def __init__(self):super().__init__()model = ResNet(Bottleneck, [3, 4, 6, 3]) # ResNet50@@ -211,11 +214,11 @@ class EncoderDeFMO(nn.Module):modelc1[0] = nn.Conv2d(6, 64, kernel_size=(7, 7), stride=(2, 2), padding=(3, 3), bias=False)self.net = nn.Sequential(modelc1, modelc2)- def forward(self, input_data: torch.Tensor) -> torch.Tensor:+ def forward(self, input_data: Tensor) -> Tensor:return self.net(input_data)-class RenderingDeFMO(nn.Module):+class RenderingDeFMO(Module):def __init__(self):super().__init__()self.tsr_steps: int = 24@@ -238,7 +241,7 @@ class RenderingDeFMO(nn.Module):self.net = modelself.times = torch.linspace(0, 1, self.tsr_steps)- def forward(self, latent: torch.Tensor) -> torch.Tensor:+ def forward(self, latent: Tensor) -> Tensor:times = self.times.to(latent.device).unsqueeze(0).repeat(latent.shape[0], 1)renders = []for ki in range(times.shape[1]):@@ -251,15 +254,15 @@ class RenderingDeFMO(nn.Module):.unsqueeze(-1).repeat(1, 1, latent.shape[2], latent.shape[3]))- latenti = torch.cat((t_tensor, latent), 1)+ latenti = concatenate((t_tensor, latent), 1)result = self.net(latenti)renders.append(result)- renders_stacked = torch.stack(renders, 1).contiguous()+ renders_stacked = stack(renders, 1).contiguous()renders_stacked[:, :, :4] = torch.sigmoid(renders_stacked[:, :, :4])return renders_stacked-class DeFMO(nn.Module):+class DeFMO(Module):"""Module that disentangle a fast-moving object from the background and performs deblurring.This is based on the original code from paper "DeFMO: Deblurring and Shape Recovery@@ -287,14 +290,17 @@ class DeFMO(nn.Module):# use torch.hub to load pretrained modelif pretrained:- storage_fcn: Callable = lambda storage, loc: storage- pretrained_dict = torch.hub.load_state_dict_from_url(urls['defmo_encoder'], map_location=storage_fcn)+ pretrained_dict = torch.hub.load_state_dict_from_url(+ urls['defmo_encoder'], map_location=map_location_to_cpu+ )self.encoder.load_state_dict(pretrained_dict, strict=True)- pretrained_dict_ren = torch.hub.load_state_dict_from_url(urls['defmo_rendering'], map_location=storage_fcn)+ pretrained_dict_ren = torch.hub.load_state_dict_from_url(+ urls['defmo_rendering'], map_location=map_location_to_cpu+ )self.rendering.load_state_dict(pretrained_dict_ren, strict=True)self.eval()- def forward(self, input_data: torch.Tensor) -> torch.Tensor:+ def forward(self, input_data: Tensor) -> Tensor:latent = self.encoder(input_data)x_out = self.rendering(latent)return x_outdiff --git a/kornia/feature/scale_space_detector.py b/kornia/feature/scale_space_detector.pyindex 3a03c5dc4..9f550b95a 100644--- a/kornia/feature/scale_space_detector.py+++ b/kornia/feature/scale_space_detector.py@@ -128,6 +128,7 @@ class ScaleSpaceDetector(Module):def detect(self, img: Tensor, num_feats: int, mask: Optional[Tensor] = None) -> Tuple[Tensor, Tensor]:dev: Device = img.devicedtype: torch.dtype = img.dtype+ sigmas: List[Tensor]sp, sigmas, _ = self.scale_pyr(img)all_responses: List[Tensor] = []all_lafs: List[Tensor] = []@@ -144,7 +145,7 @@ class ScaleSpaceDetector(Module):# We want nms for scale responses, so reorder to (B, CH, L, H, W)oct_resp = oct_resp.permute(0, 2, 1, 3, 4)# 3rd extra level is required for DoG only- if self.scale_pyr.extra_levels % 2 != 0: # type: ignore+ if isinstance(self.scale_pyr.extra_levels, Tensor) and self.scale_pyr.extra_levels % 2 != 0:oct_resp = oct_resp[:, :, :-1]if mask is not None:@@ -152,6 +153,8 @@ class ScaleSpaceDetector(Module):oct_resp = oct_mask * oct_resp# Differentiable nms+ coord_max: Tensor+ response_max: Tensorcoord_max, response_max = self.nms(oct_resp)if self.minima_are_also_good:coord_min, response_min = self.nms(-oct_resp)@@ -172,9 +175,18 @@ class ScaleSpaceDetector(Module):B, N = resp_flat_best.size()# Converts scale level index from ConvSoftArgmax3d to the actual scale, using the sigmas- max_coords_best = _scale_index_to_scale(- max_coords_best, sigmas_oct, self.scale_pyr.n_levels # type: ignore- )++ if isinstance(self.scale_pyr.n_levels, Tensor):+ num_levels = int(self.scale_pyr.n_levels.item())+ elif isinstance(self.scale_pyr.n_levels, int):+ num_levels = self.scale_pyr.n_levels+ else:+ raise TypeError(+ 'Expected the scale pyramid module to have `n_levels` as a Tensor or int.'+ f'Gotcha {type(self.scale_pyr.n_levels)}'+ )++ max_coords_best = _scale_index_to_scale(max_coords_best, sigmas_oct, num_levels)# Create local affine frames (LAFs)rotmat = eye(2, dtype=dtype, device=dev).view(1, 1, 2, 2)diff --git a/kornia/feature/siftdesc.py b/kornia/feature/siftdesc.pyindex 446c421cd..7a887f6d7 100644--- a/kornia/feature/siftdesc.py+++ b/kornia/feature/siftdesc.py@@ -3,9 +3,8 @@ from typing import Tupleimport torchimport torch.nn as nn-import torch.nn.functional as F-from kornia.core import Module, Tensor, concatenate, eye+from kornia.core import Module, Tensor, concatenate, eye, normalizefrom kornia.filters import get_gaussian_kernel2d, spatial_gradientfrom kornia.geometry.conversions import pifrom kornia.testing import KORNIA_CHECK_SHAPE@@ -169,11 +168,11 @@ class SIFTDescriptor(Module):ang_bins.append(out)ang_bins = concatenate(ang_bins, 1)ang_bins = ang_bins.view(B, -1)- ang_bins = F.normalize(ang_bins, p=2)+ ang_bins = normalize(ang_bins, p=2)ang_bins = torch.clamp(ang_bins, 0.0, float(self.clipval))- ang_bins = F.normalize(ang_bins, p=2)+ ang_bins = normalize(ang_bins, p=2)if self.rootsift:- ang_bins = torch.sqrt(F.normalize(ang_bins, p=1) + self.eps)+ ang_bins = torch.sqrt(normalize(ang_bins, p=1) + self.eps)return ang_bins@@ -287,36 +286,39 @@ class DenseSIFTDescriptor(Module):def get_pooling_kernel(self) -> Tensor:return self.bin_pooling_kernel.weight.detach()- def forward(self, input):+ def forward(self, input: Tensor) -> Tensor:KORNIA_CHECK_SHAPE(input, ["B", "1", "H", "W"])B, CH, W, H = input.size()self.bin_pooling_kernel = self.bin_pooling_kernel.to(input.dtype).to(input.device)self.PoolingConv = self.PoolingConv.to(input.dtype).to(input.device)- grads: Tensor = spatial_gradient(input, 'diff')+ grads = spatial_gradient(input, 'diff')# unpack the edges- gx: Tensor = grads[:, :, 0]- gy: Tensor = grads[:, :, 1]- mag: Tensor = torch.sqrt(gx * gx + gy * gy + self.eps)- ori: Tensor = torch.atan2(gy, gx + self.eps) + 2.0 * pi- o_big: Tensor = float(self.num_ang_bins) * ori / (2.0 * pi)-- bo0_big_: Tensor = torch.floor(o_big)- wo1_big_: Tensor = o_big - bo0_big_- bo0_big: Tensor = bo0_big_ % self.num_ang_bins- bo1_big: Tensor = (bo0_big + 1) % self.num_ang_bins- wo0_big: Tensor = (1.0 - wo1_big_) * mag # type: ignore- wo1_big: Tensor = wo1_big_ * mag- ang_bins = []- for i in range(0, self.num_ang_bins):- out = self.bin_pooling_kernel(- (bo0_big == i).to(input.dtype) * wo0_big + (bo1_big == i).to(input.dtype) * wo1_big- )- ang_bins.append(out)- ang_bins = concatenate(ang_bins, 1)+ gx = grads[:, :, 0]+ gy = grads[:, :, 1]+ mag = torch.sqrt(gx * gx + gy * gy + self.eps)+ ori = torch.atan2(gy, gx + self.eps) + 2.0 * pi+ o_big = float(self.num_ang_bins) * ori / (2.0 * pi)++ bo0_big_ = torch.floor(o_big)+ wo1_big_ = o_big - bo0_big_+ bo0_big = bo0_big_ % self.num_ang_bins+ bo1_big = (bo0_big + 1) % self.num_ang_bins+ wo0_big = (1.0 - wo1_big_) * mag+ wo1_big = wo1_big_ * mag+ ang_bins = concatenate(+ [+ self.bin_pooling_kernel(+ (bo0_big == i).to(input.dtype) * wo0_big + (bo1_big == i).to(input.dtype) * wo1_big+ )+ for i in range(0, self.num_ang_bins)+ ],+ 1,+ )+out_no_norm = self.PoolingConv(ang_bins)- out = F.normalize(out_no_norm, dim=1, p=2).clamp_(0, float(self.clipval))- out = F.normalize(out, dim=1, p=2)+ out = normalize(out_no_norm, dim=1, p=2).clamp_(0, float(self.clipval))+ out = normalize(out, dim=1, p=2)if self.rootsift:- out = torch.sqrt(F.normalize(out, p=1) + self.eps)+ out = torch.sqrt(normalize(out, p=1) + self.eps)return outdiff --git a/kornia/filters/kernels.py b/kornia/filters/kernels.pyindex 45df30d47..0084bd87a 100644--- a/kornia/filters/kernels.py+++ b/kornia/filters/kernels.py@@ -1,21 +1,23 @@import mathfrom math import sqrt-from typing import List, Optional, Tuple+from typing import List, Tupleimport torch+from kornia.core import Tensor, as_tensor, stack, tensor, zeros-def normalize_kernel2d(input: torch.Tensor) -> torch.Tensor:++def normalize_kernel2d(input: Tensor) -> Tensor:r"""Normalize both derivative and smoothing kernel."""if len(input.size()) < 2:raise TypeError(f"input should be at least 2D tensor. Got {input.size()}")- norm: torch.Tensor = input.abs().sum(dim=-1).sum(dim=-1)+ norm: Tensor = input.abs().sum(dim=-1).sum(dim=-1)return input / (norm.unsqueeze(-1).unsqueeze(-1))-def gaussian(window_size: int, sigma: float) -> torch.Tensor:+def gaussian(window_size: int, sigma: float) -> Tensor:device, dtype = None, None- if isinstance(sigma, torch.Tensor):+ if isinstance(sigma, Tensor):device, dtype = sigma.device, sigma.dtypex = torch.arange(window_size, device=device, dtype=dtype) - window_size // 2if window_size % 2 == 0:@@ -24,14 +26,14 @@ def gaussian(window_size: int, sigma: float) -> torch.Tensor:return gauss / gauss.sum()-def gaussian_discrete_erf(window_size: int, sigma) -> torch.Tensor:+def gaussian_discrete_erf(window_size: int, sigma) -> Tensor:r"""Discrete Gaussian by interpolating the error function.Adapted from:https://github.com/Project-MONAI/MONAI/blob/master/monai/networks/layers/convutils.py"""- device = sigma.device if isinstance(sigma, torch.Tensor) else None- sigma = torch.as_tensor(sigma, dtype=torch.float, device=device)+ device = sigma.device if isinstance(sigma, Tensor) else None+ sigma = as_tensor(sigma, dtype=torch.float, device=device)x = torch.arange(window_size).float() - window_size // 2t = 0.70710678 / torch.abs(sigma)gauss = 0.5 * ((t * (x + 0.5)).erf() - (t * (x - 0.5)).erf())@@ -39,7 +41,7 @@ def gaussian_discrete_erf(window_size: int, sigma) -> torch.Tensor:return gauss / gauss.sum()-def _modified_bessel_0(x: torch.Tensor) -> torch.Tensor:+def _modified_bessel_0(x: Tensor) -> Tensor:r"""Adapted from:https://github.com/Project-MONAI/MONAI/blob/master/monai/networks/layers/convutils.py@@ -56,7 +58,7 @@ def _modified_bessel_0(x: torch.Tensor) -> torch.Tensor:return (torch.exp(ax) / torch.sqrt(ax)) * coef-def _modified_bessel_1(x: torch.Tensor) -> torch.Tensor:+def _modified_bessel_1(x: Tensor) -> Tensor:r"""adapted from:https://github.com/Project-MONAI/MONAI/blob/master/monai/networks/layers/convutils.py@@ -73,7 +75,7 @@ def _modified_bessel_1(x: torch.Tensor) -> torch.Tensor:return -ans if x < 0.0 else ans-def _modified_bessel_i(n: int, x: torch.Tensor) -> torch.Tensor:+def _modified_bessel_i(n: int, x: Tensor) -> Tensor:r"""adapted from:https://github.com/Project-MONAI/MONAI/blob/master/monai/networks/layers/convutils.py@@ -84,9 +86,9 @@ def _modified_bessel_i(n: int, x: torch.Tensor) -> torch.Tensor:return xdevice = x.devicetox = 2.0 / torch.abs(x)- ans = torch.tensor(0.0, device=device)- bip = torch.tensor(0.0, device=device)- bi = torch.tensor(1.0, device=device)+ ans = tensor(0.0, device=device)+ bip = tensor(0.0, device=device)+ bi = tensor(1.0, device=device)m = int(2 * (n + int(sqrt(40.0 * n))))for j in range(m, 0, -1):bim = bip + float(j) * tox * bi@@ -102,65 +104,65 @@ def _modified_bessel_i(n: int, x: torch.Tensor) -> torch.Tensor:return -ans if x < 0.0 and (n % 2) == 1 else ans-def gaussian_discrete(window_size, sigma) -> torch.Tensor:+def gaussian_discrete(window_size, sigma) -> Tensor:r"""Discrete Gaussian kernel based on the modified Bessel functions.Adapted from:https://github.com/Project-MONAI/MONAI/blob/master/monai/networks/layers/convutils.py"""- device = sigma.device if isinstance(sigma, torch.Tensor) else None- sigma = torch.as_tensor(sigma, dtype=torch.float, device=device)+ device = sigma.device if isinstance(sigma, Tensor) else None+ sigma = as_tensor(sigma, dtype=torch.float, device=device)sigma2 = sigma * sigma- tail = int(window_size // 2)- out_pos: List[Optional[torch.Tensor]] = [None] * (tail + 1)- out_pos[0] = _modified_bessel_0(sigma2)- out_pos[1] = _modified_bessel_1(sigma2)- for k in range(2, len(out_pos)):- out_pos[k] = _modified_bessel_i(k, sigma2)- out = out_pos[:0:-1]- out.extend(out_pos)- out = torch.stack(out) * torch.exp(sigma2) # type: ignore- return out / out.sum() # type: ignore---def laplacian_1d(window_size) -> torch.Tensor:+ tail = int(window_size // 2) + 1+ bessels = [+ _modified_bessel_0(sigma2),+ _modified_bessel_1(sigma2),+ *(_modified_bessel_i(k, sigma2) for k in range(2, tail)),+ ]++ out = stack(bessels[:0:-1] + bessels, 0) * torch.exp(sigma2)++ return out / out.sum()+++def laplacian_1d(window_size) -> Tensor:r"""One could also use the Laplacian of Gaussian formula to design the filter."""filter_1d = torch.ones(window_size)filter_1d[window_size // 2] = 1 - window_size- laplacian_1d: torch.Tensor = filter_1d+ laplacian_1d: Tensor = filter_1dreturn laplacian_1d-def get_box_kernel2d(kernel_size: Tuple[int, int]) -> torch.Tensor:+def get_box_kernel2d(kernel_size: Tuple[int, int]) -> Tensor:r"""Utility function that returns a box filter."""kx: float = float(kernel_size[0])ky: float = float(kernel_size[1])- scale: torch.Tensor = torch.tensor(1.0) / torch.tensor([kx * ky])- tmp_kernel: torch.Tensor = torch.ones(1, kernel_size[0], kernel_size[1])+ scale: Tensor = tensor(1.0) / tensor([kx * ky])+ tmp_kernel: Tensor = torch.ones(1, kernel_size[0], kernel_size[1])return scale.to(tmp_kernel.dtype) * tmp_kernel-def get_binary_kernel2d(window_size: Tuple[int, int]) -> torch.Tensor:+def get_binary_kernel2d(window_size: Tuple[int, int]) -> Tensor:r"""Create a binary kernel to extract the patches.If the window size is HxW will create a (H*W)xHxW kernel."""window_range: int = window_size[0] * window_size[1]- kernel: torch.Tensor = torch.zeros(window_range, window_range)+ kernel: Tensor = zeros(window_range, window_range)for i in range(window_range):kernel[i, i] += 1.0return kernel.view(window_range, 1, window_size[0], window_size[1])-def get_sobel_kernel_3x3() -> torch.Tensor:+def get_sobel_kernel_3x3() -> Tensor:"""Utility function that returns a sobel kernel of 3x3."""- return torch.tensor([[-1.0, 0.0, 1.0], [-2.0, 0.0, 2.0], [-1.0, 0.0, 1.0]])+ return tensor([[-1.0, 0.0, 1.0], [-2.0, 0.0, 2.0], [-1.0, 0.0, 1.0]])-def get_sobel_kernel_5x5_2nd_order() -> torch.Tensor:+def get_sobel_kernel_5x5_2nd_order() -> Tensor:"""Utility function that returns a 2nd order sobel kernel of 5x5."""- return torch.tensor(+ return tensor([[-1.0, 0.0, 2.0, 0.0, -1.0],[-4.0, 0.0, 8.0, 0.0, -4.0],@@ -171,9 +173,9 @@ def get_sobel_kernel_5x5_2nd_order() -> torch.Tensor:)-def _get_sobel_kernel_5x5_2nd_order_xy() -> torch.Tensor:+def _get_sobel_kernel_5x5_2nd_order_xy() -> Tensor:"""Utility function that returns a 2nd order sobel kernel of 5x5."""- return torch.tensor(+ return tensor([[-1.0, -2.0, 0.0, 2.0, 1.0],[-2.0, -4.0, 0.0, 4.0, 2.0],@@ -184,14 +186,14 @@ def _get_sobel_kernel_5x5_2nd_order_xy() -> torch.Tensor:)-def get_diff_kernel_3x3() -> torch.Tensor:+def get_diff_kernel_3x3() -> Tensor:"""Utility function that returns a first order derivative kernel of 3x3."""- return torch.tensor([[-0.0, 0.0, 0.0], [-1.0, 0.0, 1.0], [-0.0, 0.0, 0.0]])+ return tensor([[-0.0, 0.0, 0.0], [-1.0, 0.0, 1.0], [-0.0, 0.0, 0.0]])-def get_diff_kernel3d(device=torch.device('cpu'), dtype=torch.float) -> torch.Tensor:+def get_diff_kernel3d(device=torch.device('cpu'), dtype=torch.float) -> Tensor:"""Utility function that returns a first order derivative kernel of 3x3x3."""- kernel: torch.Tensor = torch.tensor(+ kernel: Tensor = tensor([[[[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]],@@ -215,9 +217,9 @@ def get_diff_kernel3d(device=torch.device('cpu'), dtype=torch.float) -> torch.Tereturn kernel.unsqueeze(1)-def get_diff_kernel3d_2nd_order(device=torch.device('cpu'), dtype=torch.float) -> torch.Tensor:+def get_diff_kernel3d_2nd_order(device=torch.device('cpu'), dtype=torch.float) -> Tensor:"""Utility function that returns a first order derivative kernel of 3x3x3."""- kernel: torch.Tensor = torch.tensor(+ kernel: Tensor = tensor([[[[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]],@@ -256,33 +258,33 @@ def get_diff_kernel3d_2nd_order(device=torch.device('cpu'), dtype=torch.float) -return kernel.unsqueeze(1)-def get_sobel_kernel2d() -> torch.Tensor:- kernel_x: torch.Tensor = get_sobel_kernel_3x3()- kernel_y: torch.Tensor = kernel_x.transpose(0, 1)- return torch.stack([kernel_x, kernel_y])+def get_sobel_kernel2d() -> Tensor:+ kernel_x: Tensor = get_sobel_kernel_3x3()+ kernel_y: Tensor = kernel_x.transpose(0, 1)+ return stack([kernel_x, kernel_y])-def get_diff_kernel2d() -> torch.Tensor:- kernel_x: torch.Tensor = get_diff_kernel_3x3()- kernel_y: torch.Tensor = kernel_x.transpose(0, 1)- return torch.stack([kernel_x, kernel_y])+def get_diff_kernel2d() -> Tensor:+ kernel_x: Tensor = get_diff_kernel_3x3()+ kernel_y: Tensor = kernel_x.transpose(0, 1)+ return stack([kernel_x, kernel_y])-def get_sobel_kernel2d_2nd_order() -> torch.Tensor:- gxx: torch.Tensor = get_sobel_kernel_5x5_2nd_order()- gyy: torch.Tensor = gxx.transpose(0, 1)- gxy: torch.Tensor = _get_sobel_kernel_5x5_2nd_order_xy()- return torch.stack([gxx, gxy, gyy])+def get_sobel_kernel2d_2nd_order() -> Tensor:+ gxx: Tensor = get_sobel_kernel_5x5_2nd_order()+ gyy: Tensor = gxx.transpose(0, 1)+ gxy: Tensor = _get_sobel_kernel_5x5_2nd_order_xy()+ return stack([gxx, gxy, gyy])-def get_diff_kernel2d_2nd_order() -> torch.Tensor:- gxx: torch.Tensor = torch.tensor([[0.0, 0.0, 0.0], [1.0, -2.0, 1.0], [0.0, 0.0, 0.0]])- gyy: torch.Tensor = gxx.transpose(0, 1)- gxy: torch.Tensor = torch.tensor([[-1.0, 0.0, 1.0], [0.0, 0.0, 0.0], [1.0, 0.0, -1.0]])- return torch.stack([gxx, gxy, gyy])+def get_diff_kernel2d_2nd_order() -> Tensor:+ gxx: Tensor = tensor([[0.0, 0.0, 0.0], [1.0, -2.0, 1.0], [0.0, 0.0, 0.0]])+ gyy: Tensor = gxx.transpose(0, 1)+ gxy: Tensor = tensor([[-1.0, 0.0, 1.0], [0.0, 0.0, 0.0], [1.0, 0.0, -1.0]])+ return stack([gxx, gxy, gyy])-def get_spatial_gradient_kernel2d(mode: str, order: int) -> torch.Tensor:+def get_spatial_gradient_kernel2d(mode: str, order: int) -> Tensor:r"""Function that returns kernel for 1st or 2nd order image gradients, using one of the following operators:sobel, diff.@@ -302,7 +304,7 @@ def get_spatial_gradient_kernel2d(mode: str, order: int) -> torch.Tensor:))if mode == 'sobel' and order == 1:- kernel: torch.Tensor = get_sobel_kernel2d()+ kernel: Tensor = get_sobel_kernel2d()elif mode == 'sobel' and order == 2:kernel = get_sobel_kernel2d_2nd_order()elif mode == 'diff' and order == 1:@@ -314,7 +316,7 @@ def get_spatial_gradient_kernel2d(mode: str, order: int) -> torch.Tensor:return kernel-def get_spatial_gradient_kernel3d(mode: str, order: int, device=torch.device('cpu'), dtype=torch.float) -> torch.Tensor:+def get_spatial_gradient_kernel3d(mode: str, order: int, device=torch.device('cpu'), dtype=torch.float) -> Tensor:r"""Function that returns kernel for 1st or 2nd order scale pyramid gradients, using one of the followingoperators: sobel, diff."""if mode not in ['sobel', 'diff']:@@ -342,7 +344,7 @@ def get_spatial_gradient_kernel3d(mode: str, order: int, device=torch.device('cpreturn kernel-def get_gaussian_kernel1d(kernel_size: int, sigma: float, force_even: bool = False) -> torch.Tensor:+def get_gaussian_kernel1d(kernel_size: int, sigma: float, force_even: bool = False) -> Tensor:r"""Function that returns Gaussian filter coefficients.Args:@@ -366,11 +368,11 @@ def get_gaussian_kernel1d(kernel_size: int, sigma: float, force_even: bool = Fal"""if not isinstance(kernel_size, int) or ((kernel_size % 2 == 0) and not force_even) or (kernel_size <= 0):raise TypeError("kernel_size must be an odd positive integer. " "Got {}".format(kernel_size))- window_1d: torch.Tensor = gaussian(kernel_size, sigma)+ window_1d: Tensor = gaussian(kernel_size, sigma)return window_1d-def get_gaussian_discrete_kernel1d(kernel_size: int, sigma: float, force_even: bool = False) -> torch.Tensor:+def get_gaussian_discrete_kernel1d(kernel_size: int, sigma: float, force_even: bool = False) -> 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.@@ -399,7 +401,7 @@ def get_gaussian_discrete_kernel1d(kernel_size: int, sigma: float, force_even: breturn window_1d-def get_gaussian_erf_kernel1d(kernel_size: int, sigma: float, force_even: bool = False) -> torch.Tensor:+def get_gaussian_erf_kernel1d(kernel_size: int, sigma: float, force_even: bool = False) -> 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.@@ -428,9 +430,7 @@ def get_gaussian_erf_kernel1d(kernel_size: int, sigma: float, force_even: bool =return window_1d-def get_gaussian_kernel2d(- kernel_size: Tuple[int, int], sigma: Tuple[float, float], force_even: bool = False-) -> torch.Tensor:+def get_gaussian_kernel2d(kernel_size: Tuple[int, int], sigma: Tuple[float, float], force_even: bool = False) -> Tensor:r"""Function that returns Gaussian filter matrix coefficients.Args:@@ -462,13 +462,13 @@ def get_gaussian_kernel2d(raise TypeError(f"sigma must be a tuple of length two. Got {sigma}")ksize_x, ksize_y = kernel_sizesigma_x, sigma_y = sigma- kernel_x: torch.Tensor = get_gaussian_kernel1d(ksize_x, sigma_x, force_even)- kernel_y: torch.Tensor = get_gaussian_kernel1d(ksize_y, sigma_y, force_even)- kernel_2d: torch.Tensor = torch.matmul(kernel_x.unsqueeze(-1), kernel_y.unsqueeze(-1).t())+ kernel_x: Tensor = get_gaussian_kernel1d(ksize_x, sigma_x, force_even)+ kernel_y: Tensor = get_gaussian_kernel1d(ksize_y, sigma_y, force_even)+ kernel_2d: Tensor = torch.matmul(kernel_x.unsqueeze(-1), kernel_y.unsqueeze(-1).t())return kernel_2d-def get_laplacian_kernel1d(kernel_size: int) -> torch.Tensor:+def get_laplacian_kernel1d(kernel_size: int) -> Tensor:r"""Function that returns the coefficients of a 1D Laplacian filter.Args:@@ -488,11 +488,11 @@ def get_laplacian_kernel1d(kernel_size: int) -> torch.Tensor:"""if not isinstance(kernel_size, int) or kernel_size % 2 == 0 or kernel_size <= 0:raise TypeError(f"ksize must be an odd positive integer. Got {kernel_size}")- window_1d: torch.Tensor = laplacian_1d(kernel_size)+ window_1d: Tensor = laplacian_1d(kernel_size)return window_1d-def get_laplacian_kernel2d(kernel_size: int) -> torch.Tensor:+def get_laplacian_kernel2d(kernel_size: int) -> Tensor:r"""Function that returns Gaussian filter matrix coefficients.Args:@@ -522,11 +522,11 @@ def get_laplacian_kernel2d(kernel_size: int) -> torch.Tensor:kernel = torch.ones((kernel_size, kernel_size))mid = kernel_size // 2kernel[mid, mid] = 1 - kernel_size**2- kernel_2d: torch.Tensor = kernel+ kernel_2d: Tensor = kernelreturn kernel_2d-def get_pascal_kernel_2d(kernel_size: int, norm: bool = True) -> torch.Tensor:+def get_pascal_kernel_2d(kernel_size: int, norm: bool = True) -> Tensor:"""Generate pascal filter kernel by kernel size.Args:@@ -558,7 +558,7 @@ def get_pascal_kernel_2d(kernel_size: int, norm: bool = True) -> torch.Tensor:return filt-def get_pascal_kernel_1d(kernel_size: int, norm: bool = False) -> torch.Tensor:+def get_pascal_kernel_1d(kernel_size: int, norm: bool = False) -> Tensor:"""Generate Yang Hui triangle (Pascal's triangle) by a given number.Args:@@ -594,15 +594,15 @@ def get_pascal_kernel_1d(kernel_size: int, norm: bool = False) -> torch.Tensor:cur[-j - 1] = valuepre = cur- out = torch.as_tensor(cur)+ out = as_tensor(cur)if norm:out = out / torch.sum(out)return out-def get_canny_nms_kernel(device=torch.device('cpu'), dtype=torch.float) -> torch.Tensor:+def get_canny_nms_kernel(device=torch.device('cpu'), dtype=torch.float) -> Tensor:"""Utility function that returns 3x3 kernels for the Canny Non-maximal suppression."""- kernel: torch.Tensor = torch.tensor(+ kernel: Tensor = tensor([[[0.0, 0.0, 0.0], [0.0, 1.0, -1.0], [0.0, 0.0, 0.0]],[[0.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, -1.0]],@@ -619,9 +619,9 @@ def get_canny_nms_kernel(device=torch.device('cpu'), dtype=torch.float) -> torchreturn kernel.unsqueeze(1)-def get_hysteresis_kernel(device=torch.device('cpu'), dtype=torch.float) -> torch.Tensor:+def get_hysteresis_kernel(device=torch.device('cpu'), dtype=torch.float) -> Tensor:"""Utility function that returns the 3x3 kernels for the Canny hysteresis."""- kernel: torch.Tensor = torch.tensor(+ kernel: Tensor = tensor([[[0.0, 0.0, 0.0], [0.0, 0.0, 1.0], [0.0, 0.0, 0.0]],[[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 1.0]],@@ -638,7 +638,7 @@ def get_hysteresis_kernel(device=torch.device('cpu'), dtype=torch.float) -> torcreturn kernel.unsqueeze(1)-def get_hanning_kernel1d(kernel_size: int, device=torch.device('cpu'), dtype=torch.float) -> torch.Tensor:+def get_hanning_kernel1d(kernel_size: int, device=torch.device('cpu'), dtype=torch.float) -> 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)@@ -663,12 +663,12 @@ def get_hanning_kernel1d(kernel_size: int, device=torch.device('cpu'), dtype=torif not isinstance(kernel_size, int) or kernel_size <= 2:raise TypeError(f"ksize must be an positive integer > 2. Got {kernel_size}")- x: torch.Tensor = torch.arange(kernel_size, device=device, dtype=dtype)+ x: Tensor = torch.arange(kernel_size, device=device, dtype=dtype)x = 0.5 - 0.5 * torch.cos(2.0 * math.pi * x / float(kernel_size - 1))return x-def get_hanning_kernel2d(kernel_size: Tuple[int, int], device=torch.device('cpu'), dtype=torch.float) -> torch.Tensor:+def get_hanning_kernel2d(kernel_size: Tuple[int, int], device=torch.device('cpu'), dtype=torch.float) -> Tensor:r"""Returns 2d Hanning kernel, used in signal processing and KCF tracker.Args:@@ -683,7 +683,7 @@ def get_hanning_kernel2d(kernel_size: Tuple[int, int], device=torch.device('cpu'"""if kernel_size[0] <= 2 or kernel_size[1] <= 2:raise TypeError(f"ksize must be an tuple of positive integers > 2. Got {kernel_size}")- ky: torch.Tensor = get_hanning_kernel1d(kernel_size[0], device, dtype)[None].T- kx: torch.Tensor = get_hanning_kernel1d(kernel_size[1], device, dtype)[None]+ ky: Tensor = get_hanning_kernel1d(kernel_size[0], device, dtype)[None].T+ kx: Tensor = get_hanning_kernel1d(kernel_size[1], device, dtype)[None]kernel2d = ky @ kxreturn kernel2ddiff --git a/kornia/geometry/epipolar/projection.py b/kornia/geometry/epipolar/projection.pyindex 2a3744974..22bac8e7b 100644--- a/kornia/geometry/epipolar/projection.py+++ b/kornia/geometry/epipolar/projection.py@@ -49,7 +49,7 @@ def random_intrinsics(low: Union[float, torch.Tensor], high: Union[float, torch.the random camera matrix with the shape of :math:`(1, 3, 3)`."""sampler = torch.distributions.Uniform(low, high)- fx, fy, cx, cy = (sampler.sample((1,)) for _ in range(4))+ fx, fy, cx, cy = (sampler.sample(torch.Size((1,))) for _ in range(4))zeros, ones = torch.zeros_like(fx), torch.ones_like(fx)camera_matrix: torch.Tensor = torch.cat([fx, zeros, cx, zeros, fy, cy, zeros, zeros, ones])return camera_matrix.view(1, 3, 3)diff --git a/kornia/geometry/ransac.py b/kornia/geometry/ransac.pyindex 90edf7a40..8b371ac83 100644--- a/kornia/geometry/ransac.py+++ b/kornia/geometry/ransac.py@@ -1,6 +1,6 @@"""Module containing RANSAC modules."""import math-from typing import Optional, Tuple+from typing import Callable, Optional, Tupleimport torch@@ -54,23 +54,28 @@ class RANSAC(Module):self.confidence = confidenceself.max_lo_iters = max_lo_itersself.model_type = model_type++ self.error_fn: Callable[..., Tensor]+ self.minimal_solver: Callable[..., Tensor]+ self.polisher_solver: Callable[..., Tensor]+if model_type == 'homography':self.error_fn = oneway_transfer_errorself.minimal_solver = find_homography_dltself.polisher_solver = find_homography_dlt_iteratedself.minimal_sample_size = 4elif model_type == 'homography_from_linesegments':- self.error_fn = line_segment_transfer_error_one_way # type: ignore- self.minimal_solver = find_homography_lines_dlt # type: ignore- self.polisher_solver = find_homography_lines_dlt_iterated # type: ignore+ self.error_fn = line_segment_transfer_error_one_way+ self.minimal_solver = find_homography_lines_dlt+ self.polisher_solver = find_homography_lines_dlt_iteratedself.minimal_sample_size = 4elif model_type == 'fundamental':- self.error_fn = symmetrical_epipolar_distance # type: ignore- self.minimal_solver = find_fundamental # type: ignore+ self.error_fn = symmetrical_epipolar_distance+ self.minimal_solver = find_fundamentalself.minimal_sample_size = 8# ToDo: implement 7pt solver instead of 8pt minimal_solver# https://github.com/opencv/opencv/blob/master/modules/calib3d/src/fundam.cpp#L498- self.polisher_solver = find_fundamental # type: ignore+ self.polisher_solver = find_fundamentalelse:raise NotImplementedError(f"{model_type} is unknown. Try one of {self.supported_models}")diff --git a/kornia/geometry/subpix/nms.py b/kornia/geometry/subpix/nms.pyindex 8357f2021..6897a653a 100644--- a/kornia/geometry/subpix/nms.py+++ b/kornia/geometry/subpix/nms.py@@ -26,6 +26,7 @@ def _get_nms_kernel3d(kd: int, ky: int, kx: int) -> Tensor:class NonMaximaSuppression2d(Module):r"""Apply non maxima suppression to filter."""+ kernel: Tensordef __init__(self, kernel_size: Tuple[int, int]):super().__init__()@@ -55,7 +56,7 @@ class NonMaximaSuppression2d(Module):B, CH, HP, WP = x_padded.size()max_non_center = (- F.conv2d(x_padded.view(B * CH, 1, HP, WP), self.kernel.to(x.device, x.dtype), stride=1) # type: ignore+ F.conv2d(x_padded.view(B * CH, 1, HP, WP), self.kernel.to(x.device, x.dtype), stride=1).view(B, CH, -1, H, W).max(dim=2)[0])diff --git a/kornia/geometry/transform/crop2d.py b/kornia/geometry/transform/crop2d.pyindex d9360edb4..92ba3705c 100644--- a/kornia/geometry/transform/crop2d.py+++ b/kornia/geometry/transform/crop2d.py@@ -325,7 +325,7 @@ def crop_by_indices(== len(y2.unique(sorted=False))== 1):- out = input_tensor[..., y1[0] : y2[0], x1[0] : x2[0]] # type: ignore[misc]+ out = input_tensor[..., int(y1[0]) : int(y2[0]), int(x1[0]) : int(x2[0])]if size is not None and out.shape[-2:] != size:return resize(out, size, interpolation=interpolation, align_corners=align_corners, side="short", antialias=antialias@@ -337,7 +337,7 @@ def crop_by_indices(out = torch.empty(B, C, *size, device=input_tensor.device, dtype=input_tensor.dtype)# Find out the cropped shapes that need to be resized.for i, _ in enumerate(out):- _out = input_tensor[i : i + 1, :, y1[i] : y2[i], x1[i] : x2[i]] # type: ignore[misc]+ _out = input_tensor[i : i + 1, :, int(y1[i]) : int(y2[i]), int(x1[i]) : int(x2[i])]if _out.shape[-2:] != size:if shape_compensation == "resize":out[i] = resize(diff --git a/kornia/geometry/transform/pyramid.py b/kornia/geometry/transform/pyramid.pyindex 3f4a5db9d..86c54be26 100644--- a/kornia/geometry/transform/pyramid.py+++ b/kornia/geometry/transform/pyramid.py@@ -166,7 +166,7 @@ class ScalePyramid(Module):ksize += 1return ksize- def get_first_level(self, input):+ def get_first_level(self, input: Tensor) -> Tuple[Tensor, float, float]:pixel_distance = 1.0cur_sigma = 0.5# Same as in OpenCV up to interpolation difference@@ -176,6 +176,7 @@ class ScalePyramid(Module):cur_sigma *= 2.0else:x = input+if self.init_sigma > cur_sigma:sigma = max(math.sqrt(self.init_sigma**2 - cur_sigma**2), 0.01)ksize = self.get_kernel_size(sigma)@@ -223,9 +224,10 @@ class ScalePyramid(Module):sigmas.append(cur_sigma * torch.ones(bs, self.n_levels + self.extra_levels).to(x.device))pixel_dists.append(pixel_distance * torch.ones(bs, self.n_levels + self.extra_levels).to(x.device))oct_idx += 1- for i in range(len(pyr)):- pyr[i] = stack(pyr[i], 2) # type: ignore- return pyr, sigmas, pixel_dists++ output_pyr = [stack(i, 2) for i in pyr]++ return output_pyr, sigmas, pixel_distsdef pyrdown(input: Tensor, border_type: str = 'reflect', align_corners: bool = False, factor: float = 2.0) -> Tensor:diff --git a/kornia/losses/hausdorff.py b/kornia/losses/hausdorff.pyindex 03756f803..eb90fce1b 100644--- a/kornia/losses/hausdorff.py+++ b/kornia/losses/hausdorff.py@@ -3,6 +3,8 @@ from typing import Callableimport torchimport torch.nn as nn+from kornia.core import Tensor, as_tensor, stack, tensor, where, zeros_like+class _HausdorffERLossBase(torch.jit.ScriptModule):"""Base class for binary Hausdorff loss based on morphological erosion.@@ -33,15 +35,15 @@ class _HausdorffERLossBase(torch.jit.ScriptModule):self.reduction = reductionself.register_buffer("kernel", self.get_kernel())- def get_kernel(self) -> torch.Tensor:+ def get_kernel(self) -> Tensor:"""Get kernel for image morphology convolution."""raise NotImplementedError- def perform_erosion(self, pred: torch.Tensor, target: torch.Tensor) -> torch.Tensor:+ def perform_erosion(self, pred: Tensor, target: Tensor) -> Tensor:bound = (pred - target) ** 2- kernel = torch.as_tensor(self.kernel, device=pred.device, dtype=pred.dtype)- eroded = torch.zeros_like(bound, device=pred.device, dtype=pred.dtype)+ kernel = as_tensor(self.kernel, device=pred.device, dtype=pred.dtype)+ eroded = zeros_like(bound, device=pred.device, dtype=pred.dtype)mask = torch.ones_like(bound, device=pred.device, dtype=torch.bool)# Same padding, assuming kernel is odd and square (cube) shaped.@@ -65,7 +67,7 @@ class _HausdorffERLossBase(torch.jit.ScriptModule):# erosion[to_norm] = (erosion[to_norm] - erosion_min[to_norm]) / (# erosion_max[to_norm] - erosion_min[to_norm])_erosion_to_fill = (erosion - erosion_min) / (erosion_max - erosion_min)- erosion = torch.where(mask * _to_norm, _erosion_to_fill, erosion)+ erosion = where(mask * _to_norm, _erosion_to_fill, erosion)# save erosion and add to losseroded = eroded + erosion * (k + 1) ** self.alpha@@ -74,7 +76,7 @@ class _HausdorffERLossBase(torch.jit.ScriptModule):return eroded# NOTE: we add type ignore because the forward pass does not work well with subclassing- def forward(self, pred: torch.Tensor, target: torch.Tensor) -> torch.Tensor: # type: ignore+ def forward(self, pred: Tensor, target: Tensor) -> Tensor: # type: ignore[override]"""Compute Hausdorff loss.Args:@@ -94,14 +96,14 @@ class _HausdorffERLossBase(torch.jit.ScriptModule):if pred.size(1) < target.max().item():raise ValueError("Invalid target value.")- out = torch.stack(+ out = stack([self.perform_erosion(pred[:, i : i + 1],- torch.where(+ where(target == i,- torch.tensor(1, device=target.device, dtype=target.dtype),- torch.tensor(0, device=target.device, dtype=target.dtype),+ tensor(1, device=target.device, dtype=target.dtype),+ tensor(0, device=target.device, dtype=target.dtype),),)for i in range(pred.size(1))@@ -159,14 +161,14 @@ class HausdorffERLoss(_HausdorffERLossBase):conv = torch.conv2dmax_pool = nn.AdaptiveMaxPool2d(1)- def get_kernel(self) -> torch.Tensor:+ def get_kernel(self) -> Tensor:"""Get kernel for image morphology convolution."""- cross = torch.tensor([[[0, 1, 0], [1, 1, 1], [0, 1, 0]]])+ cross = tensor([[[0, 1, 0], [1, 1, 1], [0, 1, 0]]])kernel = cross * 0.2return kernel[None]# NOTE: we add type ignore because the forward pass does not work well with subclassing- def forward(self, pred: torch.Tensor, target: torch.Tensor) -> torch.Tensor: # type: ignore+ def forward(self, pred: Tensor, target: Tensor) -> Tensor: # type: ignore[override]"""Compute Hausdorff loss.Args:@@ -226,18 +228,18 @@ class HausdorffERLoss3D(_HausdorffERLossBase):conv = torch.conv3dmax_pool = nn.AdaptiveMaxPool3d(1)- def get_kernel(self) -> torch.Tensor:+ def get_kernel(self) -> Tensor:"""Get kernel for image morphology convolution."""- cross = torch.tensor([[[0, 1, 0], [1, 1, 1], [0, 1, 0]]])- bound = torch.tensor([[[0, 0, 0], [0, 1, 0], [0, 0, 0]]])+ cross = tensor([[[0, 1, 0], [1, 1, 1], [0, 1, 0]]])+ bound = tensor([[[0, 0, 0], [0, 1, 0], [0, 0, 0]]])# NOTE: The original repo claimed it shaped as (3, 1, 3, 3)# which Jian suspect it is wrongly implemented.# https://github.com/PatRyg99/HausdorffLoss/blob/9f580acd421af648e74b45d46555ccb7a876c27c/hausdorff_loss.py#L94- kernel = torch.stack([bound, cross, bound], dim=1) * (1 / 7)+ kernel = stack([bound, cross, bound], 1) * (1 / 7)return kernel[None]# NOTE: we add type ignore because the forward pass does not work well with subclassing- def forward(self, pred: torch.Tensor, target: torch.Tensor) -> torch.Tensor: # type: ignore+ def forward(self, pred: Tensor, target: Tensor) -> Tensor: # type: ignore[override]"""Compute 3D Hausdorff loss.Args:diff --git a/kornia/tracking/planar_tracker.py b/kornia/tracking/planar_tracker.pyindex 1c5833969..80cbf93b9 100644--- a/kornia/tracking/planar_tracker.py+++ b/kornia/tracking/planar_tracker.py@@ -1,8 +1,8 @@from typing import Dict, Optional, Tupleimport torch-import torch.nn as nn+from kornia.core import Module, Tensorfrom kornia.feature import DescriptorMatcher, GFTTAffNetHardNet, LocalFeatureMatcher, LoFTRfrom kornia.feature.integrated import LocalFeaturefrom kornia.geometry.linalg import transform_points@@ -10,7 +10,7 @@ from kornia.geometry.ransac import RANSACfrom kornia.geometry.transform import warp_perspective-class HomographyTracker(nn.Module):+class HomographyTracker(Module):r"""Module, which performs local-feature-based tracking of the target planar object in the sequence of theframes.@@ -26,8 +26,8 @@ class HomographyTracker(nn.Module):def __init__(self,initial_matcher: Optional[LocalFeature] = None,- fast_matcher: Optional[nn.Module] = None,- ransac: Optional[nn.Module] = None,+ fast_matcher: Optional[Module] = None,+ ransac: Optional[Module] = None,minimum_inliers_num: int = 30,) -> None:super().__init__()@@ -39,10 +39,10 @@ class HomographyTracker(nn.Module):self.minimum_inliers_num = minimum_inliers_num# placeholders- self.target: torch.Tensor- self.target_initial_representation: Dict[str, torch.Tensor] = {}- self.target_fast_representation: Dict[str, torch.Tensor] = {}- self.previous_homography: Optional[torch.Tensor] = None+ self.target: Tensor+ self.target_initial_representation: Dict[str, Tensor] = {}+ self.target_fast_representation: Dict[str, Tensor] = {}+ self.previous_homography: Optional[Tensor] = Noneself.inliers_num: int = 0self.keypoints0_num: int = 0@@ -59,32 +59,34 @@ class HomographyTracker(nn.Module):return self.target.dtype@torch.no_grad()- def set_target(self, target: torch.Tensor) -> None:+ def set_target(self, target: Tensor) -> None:self.target = targetself.target_initial_representation = {}self.target_fast_representation = {}- if hasattr(self.initial_matcher, 'extract_features'):- self.target_initial_representation = self.initial_matcher.extract_features(target) # type: ignore- if hasattr(self.fast_matcher, 'extract_features'):- self.target_fast_representation = self.fast_matcher.extract_features(target) # type: ignore+ if hasattr(self.initial_matcher, 'extract_features') and isinstance(+ self.initial_matcher.extract_features, Module+ ):+ self.target_initial_representation = self.initial_matcher.extract_features(target)+ if hasattr(self.fast_matcher, 'extract_features') and isinstance(self.fast_matcher.extract_features, Module):+ self.target_fast_representation = self.fast_matcher.extract_features(target)def reset_tracking(self) -> None:self.previous_homography = None- def no_match(self) -> Tuple[torch.Tensor, bool]:+ def no_match(self) -> Tuple[Tensor, bool]:self.inliers_num = 0self.keypoints0_num = 0self.keypoints1_num = 0return torch.empty(3, 3, device=self.device, dtype=self.dtype), False- def match_initial(self, x: torch.Tensor) -> Tuple[torch.Tensor, bool]:+ def match_initial(self, x: Tensor) -> Tuple[Tensor, bool]:"""The frame `x` is matched with initial_matcher and verified with ransac."""- input_dict: Dict[str, torch.Tensor] = {"image0": self.target, "image1": x}+ input_dict: Dict[str, Tensor] = {"image0": self.target, "image1": x}for k, v in self.target_initial_representation.items():input_dict[f'{k}0'] = v- match_dict: Dict[str, torch.Tensor] = self.initial_matcher(input_dict)+ match_dict: Dict[str, Tensor] = self.initial_matcher(input_dict)keypoints0 = match_dict['keypoints0'][match_dict['batch_indexes'] == 0]keypoints1 = match_dict['keypoints1'][match_dict['batch_indexes'] == 0]@@ -103,7 +105,7 @@ class HomographyTracker(nn.Module):return H, True- def track_next_frame(self, x: torch.Tensor) -> Tuple[torch.Tensor, bool]:+ def track_next_frame(self, x: Tensor) -> Tuple[Tensor, bool]:"""The frame `x` is prewarped according to the previous frame homography, matched with fast_matcherverified with ransac."""if self.previous_homography is not None: # mypy, shut up@@ -114,7 +116,7 @@ class HomographyTracker(nn.Module):Hinv = torch.inverse(Hwarp)h, w = self.target.shape[2:]frame_warped = warp_perspective(x, Hinv, (h, w))- input_dict: Dict[str, torch.Tensor] = {"image0": self.target, "image1": frame_warped}+ input_dict: Dict[str, Tensor] = {"image0": self.target, "image1": frame_warped}for k, v in self.target_fast_representation.items():input_dict[f'{k}0'] = v@@ -140,7 +142,7 @@ class HomographyTracker(nn.Module):self.previous_homography = H.clone()return H, True- def forward(self, x: torch.Tensor) -> Tuple[torch.Tensor, bool]:+ def forward(self, x: Tensor) -> Tuple[Tensor, bool]:if self.previous_homography is not None:return self.track_next_frame(x)return self.match_initial(x)diff --git a/kornia/x/utils.py b/kornia/x/utils.pyindex 958b1d153..54d108555 100644--- a/kornia/x/utils.py+++ b/kornia/x/utils.py@@ -2,11 +2,10 @@ from dataclasses import dataclass, fieldfrom enum import Enumfrom typing import Dict-import torch.nn as nn-+from kornia.core import Modulefrom kornia.metrics.average_meter import AverageMeter-# import yaml # type: ignore+# import yamlclass TrainerState(Enum):@@ -39,8 +38,8 @@ class Configuration:# return cls(**data)-class Lambda(nn.Module):- """Module to create a lambda function as nn.Module.+class Lambda(Module):+ """Module to create a lambda function as Module.Args:fcn: a pointer to any function.diff --git a/test/geometry/test_boxes.py b/test/geometry/test_boxes.pyindex 0352a7382..1e7905a40 100644--- a/test/geometry/test_boxes.py+++ b/test/geometry/test_boxes.py@@ -150,19 +150,19 @@ class TestBoxes2D:boxes_vertices = box.to_tensor(mode='vertices')boxes_vertices_plus = box.to_tensor(mode='vertices_plus')- assert boxes_xyxy.shape == expected_box_xyxy.shape # type: ignore+ assert boxes_xyxy.shape == expected_box_xyxy.shapeassert_allclose(boxes_xyxy, expected_box_xyxy)- assert boxes_xyxy_plus.shape == expected_box_xyxy_plus.shape # type: ignore+ assert boxes_xyxy_plus.shape == expected_box_xyxy_plus.shapeassert_allclose(boxes_xyxy_plus, expected_box_xyxy_plus)- assert boxes_xywh.shape == expected_box_xywh.shape # type: ignore+ assert boxes_xywh.shape == expected_box_xywh.shapeassert_allclose(boxes_xywh, expected_box_xywh)- assert boxes_vertices.shape == expected_vertices.shape # type: ignore+ assert boxes_vertices.shape == expected_vertices.shapeassert_allclose(boxes_vertices, expected_vertices)- assert boxes_vertices_plus.shape == expected_vertices_plus.shape # type: ignore+ assert boxes_vertices_plus.shape == expected_vertices_plus.shapeassert_allclose(boxes_vertices_plus, expected_vertices_plus)@pytest.mark.parametrize('mode', ['xyxy', 'xyxy_plus', 'xywh', 'vertices', 'vertices_plus'])