Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

Remove unused `type: ignore` (#1998)

João Gustavo A. Amorima13ab5ef3a49
diff --git a/kornia/augmentation/_2d/geometric/crop.py b/kornia/augmentation/_2d/geometric/crop.py
index 85393285d..b0007d7ce 100644
--- a/kornia/augmentation/_2d/geometric/crop.py
+++ b/kornia/augmentation/_2d/geometric/crop.py
@@ -1,13 +1,12 @@
from typing import Any, Dict, List, Optional, Tuple, Union, cast
import torch
-from torch import Tensor
-from torch.nn.functional import pad
from kornia.augmentation import random_generator as rg
from kornia.augmentation._2d.geometric.base import GeometricAugmentationBase2D
from kornia.augmentation.utils import _transform_input, _transform_output_shape, override_parameters
from kornia.constants import Resample
+from kornia.core import Tensor, pad, tensor
from kornia.geometry.transform import crop_by_indices, crop_by_transform_mat, get_perspective_transform
@@ -226,7 +225,7 @@ class RandomCrop(GeometricAugmentationBase2D):
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 = torch.tensor(tuple(input_pad), dtype=torch.long).expand(batch_shape[0], -1)
+ padding_size = tensor(tuple(input_pad), dtype=torch.long).expand(batch_shape[0], -1)
_params = super().forward_parameters(batch_shape_new)
_params.update({"padding_size": padding_size})
return _params
@@ -245,21 +244,21 @@ class RandomCrop(GeometricAugmentationBase2D):
input_temp = _transform_input(input[0])
input_pad = self.compute_padding(input[0].shape, flags) if input_pad is None else input_pad
_input = (self.precrop_padding(input_temp, input_pad, flags), input[1])
- _input = _transform_output_shape(_input, ori_shape) if self.keepdim else _input # type:ignore
+ _input = _transform_output_shape(_input, ori_shape) if self.keepdim else _input
else:
input = cast(Tensor, input)
ori_shape = input.shape
input_temp = _transform_input(input)
input_pad = self.compute_padding(input_temp.shape, flags) if input_pad is None else input_pad
- _input = self.precrop_padding(input_temp, input_pad, flags) # type: ignore
- _input = _transform_output_shape(_input, ori_shape) if self.keepdim else _input # type:ignore
+ _input = self.precrop_padding(input_temp, input_pad, flags)
+ _input = _transform_output_shape(_input, ori_shape) if self.keepdim else _input
if params is not None:
params, flags = self._process_kwargs_to_params_and_flags(params, self.flags, **kwargs)
- out = super().forward(_input, params, **kwargs) # type:ignore
+ out = super().forward(_input, params, **kwargs)
# Update the actual input size for inverse
if "padding_size" not in self._params:
- _padding_size = torch.tensor(tuple(input_pad), device=input_temp.device, dtype=torch.long).expand(
+ _padding_size = tensor(tuple(input_pad), device=input_temp.device, dtype=torch.long).expand(
input_temp.size(0), -1
)
self._params.update({"padding_size": _padding_size})
diff --git a/kornia/augmentation/_2d/mix/base.py b/kornia/augmentation/_2d/mix/base.py
index 5e8f4a23e..a921c55d5 100644
--- a/kornia/augmentation/_2d/mix/base.py
+++ b/kornia/augmentation/_2d/mix/base.py
@@ -106,7 +106,7 @@ class MixAugmentationBase(_BasicAugmentationBase):
self._params = params
output, lab = self.apply_func(in_tensor, label, self._params)
- output = _transform_output_shape(output, ori_shape) if self.keepdim else output # type: ignore
+ output = _transform_output_shape(output, ori_shape) if self.keepdim else output
if in_trans is not None:
return (output, in_trans), lab
return output, lab
diff --git a/kornia/augmentation/_2d/mix/cutmix.py b/kornia/augmentation/_2d/mix/cutmix.py
index 86c3e25ef..bbc6b3c78 100644
--- a/kornia/augmentation/_2d/mix/cutmix.py
+++ b/kornia/augmentation/_2d/mix/cutmix.py
@@ -1,13 +1,11 @@
import warnings
from typing import Any, Dict, List, Optional, Tuple, Union
-import torch
-
from kornia.augmentation import random_generator as rg
from kornia.augmentation._2d.mix.base import MixAugmentationBase, MixAugmentationBaseV2
from kornia.augmentation.utils import _shape_validation
from kornia.constants import DataKey, DType
-from kornia.core import Tensor
+from kornia.core import Tensor, stack, zeros
from kornia.geometry.bbox import bbox_to_mask, infer_bbox_shape
@@ -112,7 +110,7 @@ class RandomCutMix(MixAugmentationBase):
warnings.warn("`RandomCutMix` is deprecated. Please use `RandomCutMixV2` instead.")
def apply_transform( # type: ignore
- self, input: Tensor, label: Tensor, params: Dict[str, Tensor] # type: ignore
+ self, input: Tensor, label: Tensor, params: Dict[str, Tensor]
) -> Tuple[Tensor, Tensor]:
height, width = input.size(2), input.size(3)
num_mixes = params["mix_pairs"].size(0)
@@ -131,11 +129,9 @@ class RandomCutMix(MixAugmentationBase):
# compute mask to match input shape
mask = bbox_to_mask(crop, width, height).bool().unsqueeze(dim=1).repeat(1, input.size(1), 1, 1)
out_inputs[mask] = input_permute[mask]
- out_labels.append(
- torch.stack([label.to(input.dtype), labels_permute.to(input.dtype), lam.to(label.device)], dim=1)
- )
+ out_labels.append(stack([label.to(input.dtype), labels_permute.to(input.dtype), lam.to(label.device)], 1))
- return out_inputs, torch.stack(out_labels, dim=0)
+ return out_inputs, stack(out_labels, 0)
class RandomCutMixV2(MixAugmentationBaseV2):
@@ -220,36 +216,36 @@ class RandomCutMixV2(MixAugmentationBaseV2):
w, h = infer_bbox_shape(crop)
lam = w.to(input.dtype) * h.to(input.dtype) / (width * height) # width_beta * height_beta
out_labels.append(
- torch.stack(
+ stack(
[
input.to(device=input.device, dtype=DType.to_torch(int(params["dtype"].item()))),
labels_permute.to(device=input.device, dtype=DType.to_torch(int(params["dtype"].item()))),
lam.to(device=input.device, dtype=DType.to_torch(int(params["dtype"].item()))),
],
- dim=1,
+ 1,
)
)
- return torch.stack(out_labels, dim=0)
+ return stack(out_labels, 0)
def apply_non_transform_class(
self, input: Tensor, params: Dict[str, Tensor], flags: Optional[Dict[str, Any]] = None
) -> Tensor:
out_labels = []
- lam = torch.zeros((len(input)), device=input.device, dtype=DType.to_torch(int(params["dtype"].item())))
+ lam = zeros((len(input)), device=input.device, dtype=DType.to_torch(int(params["dtype"].item())))
for _ in range(self._param_generator.num_mix):
out_labels.append(
- torch.stack(
+ stack(
[
input.to(device=input.device, dtype=DType.to_torch(int(params["dtype"].item()))),
input.to(device=input.device, dtype=DType.to_torch(int(params["dtype"].item()))),
lam,
],
- dim=1,
+ 1,
)
)
- return torch.stack(out_labels, dim=0)
+ return stack(out_labels, 0)
def apply_transform(
self, input: Tensor, params: Dict[str, Tensor], maybe_flags: Optional[Dict[str, Any]] = None
diff --git a/kornia/augmentation/_3d/geometric/crop.py b/kornia/augmentation/_3d/geometric/crop.py
index e0f40b93b..7117784a4 100644
--- a/kornia/augmentation/_3d/geometric/crop.py
+++ b/kornia/augmentation/_3d/geometric/crop.py
@@ -1,11 +1,9 @@
from typing import Any, Dict, Optional, Tuple, Union, cast
-from torch import Tensor
-from torch.nn.functional import pad
-
from kornia.augmentation import random_generator as rg
from kornia.augmentation._3d.base import AugmentationBase3D
from kornia.constants import Resample
+from kornia.core import Tensor, pad
from kornia.geometry import crop_by_transform_mat3d, get_perspective_transform3d
@@ -104,7 +102,7 @@ class RandomCrop3D(AugmentationBase3D):
elif isinstance(padding, (tuple, list)) and len(padding) == 3:
padding = [padding[0], padding[0], padding[1], padding[1], padding[2], padding[2]]
elif isinstance(padding, (tuple, list)) and len(padding) == 6:
- padding = [padding[0], padding[1], padding[2], padding[3], padding[4], padding[5]] # type: ignore
+ padding = [padding[0], padding[1], padding[2], padding[3], padding[4], padding[5]]
else:
raise ValueError(f"`padding` must be an integer, 3-element-list or 6-element-list. Got {padding}.")
input = pad(input, padding, value=flags["fill"], mode=flags["padding_mode"])
@@ -136,7 +134,7 @@ class RandomCrop3D(AugmentationBase3D):
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: # type: ignore
+ def forward(self, input: Tensor, params: Optional[Dict[str, Tensor]] = None, **kwargs) -> Tensor:
# TODO: need to align 2D implementations
input = self.precrop_padding(input)
- return super().forward(input, params) # type:ignore
+ return super().forward(input, params)
diff --git a/kornia/augmentation/base.py b/kornia/augmentation/base.py
index 2662dd2d9..8d5793ed4 100644
--- a/kornia/augmentation/base.py
+++ b/kornia/augmentation/base.py
@@ -2,17 +2,16 @@ from enum import Enum
from typing import Any, Dict, Optional, Tuple, Union
import torch
-import torch.nn as nn
-from torch import Tensor
from torch.distributions import Bernoulli
from kornia.augmentation.random_generator import RandomGeneratorBase
from kornia.augmentation.utils import _adapted_sampling, _transform_output_shape, override_parameters
+from kornia.core import Module, Tensor, tensor
TensorWithTransformMat = Union[Tensor, Tuple[Tensor, Tensor]]
-class _BasicAugmentationBase(nn.Module):
+class _BasicAugmentationBase(Module):
r"""_BasicAugmentationBase base class for customized augmentation implementations.
Plain augmentation base class without the functionality of transformation matrix calculations.
@@ -96,18 +95,18 @@ class _BasicAugmentationBase(nn.Module):
) -> Tensor:
batch_prob: Tensor
if p_batch == 1:
- batch_prob = torch.tensor([True])
+ batch_prob = tensor([True])
elif p_batch == 0:
- batch_prob = torch.tensor([False])
+ batch_prob = tensor([False])
else:
batch_prob = _adapted_sampling((1,), self._p_batch_gen, same_on_batch).bool()
if batch_prob.sum().item() == 1:
elem_prob: Tensor
if p == 1:
- elem_prob = torch.tensor([True] * batch_shape[0])
+ elem_prob = tensor([True] * batch_shape[0])
elif p == 0:
- elem_prob = torch.tensor([False] * batch_shape[0])
+ elem_prob = tensor([False] * batch_shape[0])
else:
elem_prob = _adapted_sampling((batch_shape[0],), self._p_gen, same_on_batch).bool()
batch_prob = batch_prob * elem_prob
@@ -140,14 +139,14 @@ class _BasicAugmentationBase(nn.Module):
_params['batch_prob'] = to_apply
# Added another input_size parameter for geometric transformations
# This might be needed for correctly inversing.
- input_size = torch.tensor(batch_shape, dtype=torch.long)
+ input_size = tensor(batch_shape, dtype=torch.long)
_params.update({'forward_input_shape': input_size})
return _params
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: # type: ignore
+ def forward(self, input: Tensor, params: Optional[Dict[str, Tensor]] = None, **kwargs) -> Tensor:
"""Perform forward operations.
Args:
@@ -169,7 +168,7 @@ class _BasicAugmentationBase(nn.Module):
params = self.forward_parameters(batch_shape)
if 'batch_prob' not in params:
- params['batch_prob'] = torch.tensor([True] * batch_shape[0])
+ params['batch_prob'] = tensor([True] * batch_shape[0])
params, flags = self._process_kwargs_to_params_and_flags(params, self.flags, **kwargs)
@@ -229,7 +228,7 @@ class _AugmentationBase(_BasicAugmentationBase):
) -> Tensor:
raise NotImplementedError
- def apply_func( # type: ignore
+ def apply_func(
self, in_tensor: Tensor, params: Dict[str, Tensor], flags: Optional[Dict[str, Any]] = None
) -> Tensor:
if flags is None:
diff --git a/kornia/augmentation/container/augment.py b/kornia/augmentation/container/augment.py
index bf3dacff9..e2f218a00 100644
--- a/kornia/augmentation/container/augment.py
+++ b/kornia/augmentation/container/augment.py
@@ -2,8 +2,6 @@ import warnings
from itertools import zip_longest
from typing import Any, Dict, List, Optional, Tuple, Union, cast
-from torch import Tensor
-
from kornia.augmentation import (
AugmentationBase3D,
GeometricAugmentationBase2D,
@@ -18,6 +16,7 @@ from kornia.augmentation.container.patch import PatchSequential
from kornia.augmentation.container.utils import ApplyInverse
from kornia.augmentation.container.video import VideoSequential
from kornia.constants import DataKey, Resample
+from kornia.core import Tensor
from kornia.geometry.boxes import Boxes
from kornia.utils import eye_like
@@ -314,7 +313,7 @@ class AugmentationSequential(ImageSequential):
mode = "xywh"
else:
raise ValueError(f"Unsupported mode `{DataKey.get(dcate).name}`.")
- inp.append(Boxes.from_tensor(arg, mode=mode)) # type: ignore
+ inp.append(Boxes.from_tensor(arg, mode=mode))
else:
raise NotImplementedError(f"input type of {dcate} is not implemented.")
return inp
@@ -367,7 +366,7 @@ class AugmentationSequential(ImageSequential):
if dcate == DataKey.INPUT:
_inp = args[idx]
- _out = super().forward(_inp, label, params=params, extra_args=extra_args) # type: ignore
+ _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)
diff --git a/kornia/augmentation/container/image.py b/kornia/augmentation/container/image.py
index 9fc5f1a8f..39dc78142 100644
--- a/kornia/augmentation/container/image.py
+++ b/kornia/augmentation/container/image.py
@@ -2,8 +2,6 @@ from itertools import zip_longest
from typing import Any, Dict, Iterator, List, Optional, Tuple, Type, Union, cast
import torch
-import torch.nn as nn
-from torch import Tensor
import kornia
from kornia.augmentation import (
@@ -17,6 +15,7 @@ from kornia.augmentation.base import _AugmentationBase
from kornia.augmentation.container.base import ParamItem, SequentialBase
from kornia.augmentation.container.utils import ApplyInverseInterface, InputApplyInverse
from kornia.augmentation.utils import override_parameters
+from kornia.core import Module, Tensor, as_tensor
__all__ = ["ImageSequential"]
@@ -89,7 +88,7 @@ class ImageSequential(SequentialBase):
def __init__(
self,
- *args: nn.Module,
+ *args: Module,
same_on_batch: Optional[bool] = None,
return_transform: Optional[bool] = None,
keepdim: Optional[bool] = None,
@@ -110,7 +109,7 @@ class ImageSequential(SequentialBase):
"The length of `random_apply_weights` must be as same as the number of operations."
f"Got {len(random_apply_weights)} and {len(self)}."
)
- self.random_apply_weights = torch.as_tensor(random_apply_weights or torch.ones((len(self),)))
+ self.random_apply_weights = as_tensor(random_apply_weights or torch.ones((len(self),)))
self.return_label: Optional[bool] = None
self.apply_inverse_func: Type[ApplyInverseInterface] = InputApplyInverse
self.if_unsupported_ops = if_unsupported_ops
@@ -145,7 +144,7 @@ class ImageSequential(SequentialBase):
raise AssertionError(f"Expect a tuple of (int, int). Got {random_apply}.")
return random_apply
- def get_random_forward_sequence(self, with_mix: bool = True) -> Tuple[Iterator[Tuple[str, nn.Module]], bool]:
+ def get_random_forward_sequence(self, with_mix: bool = True) -> Tuple[Iterator[Tuple[str, Module]], bool]:
"""Get a forward sequence when random apply is in need.
Note:
@@ -174,7 +173,7 @@ class ImageSequential(SequentialBase):
return self.get_children_by_indices(indices), mix_added
- def get_mix_augmentation_indices(self, named_modules: Iterator[Tuple[str, nn.Module]]) -> List[int]:
+ def get_mix_augmentation_indices(self, named_modules: Iterator[Tuple[str, Module]]) -> List[int]:
"""Get all the mix augmentations since they are label-involved.
Special operations needed for label-involved augmentations.
@@ -185,7 +184,7 @@ class ImageSequential(SequentialBase):
indices.append(idx)
return indices
- def get_forward_sequence(self, params: Optional[List[ParamItem]] = None) -> Iterator[Tuple[str, nn.Module]]:
+ def get_forward_sequence(self, params: Optional[List[ParamItem]] = None) -> Iterator[Tuple[str, Module]]:
if params is None:
# Mix augmentation can only be applied once per forward
mix_indices = self.get_mix_augmentation_indices(self.named_children())
@@ -207,16 +206,16 @@ class ImageSequential(SequentialBase):
self,
input: Tensor,
label: Optional[Tensor],
- module: Optional[nn.Module],
+ module: Optional[Module],
param: ParamItem,
extra_args: Dict[str, Any],
) -> Tuple[Tensor, Optional[Tensor]]:
if module is None:
module = self.get_submodule(param.name)
- return self.apply_inverse_func.apply_trans(input, label, module, param, extra_args) # type: ignore
+ return self.apply_inverse_func.apply_trans(input, label, module, param, extra_args)
def forward_parameters(self, batch_shape: torch.Size) -> List[ParamItem]:
- named_modules: Iterator[Tuple[str, nn.Module]] = self.get_forward_sequence()
+ named_modules: Iterator[Tuple[str, Module]] = self.get_forward_sequence()
params: List[ParamItem] = []
mod_param: Union[dict, list]
@@ -267,7 +266,7 @@ class ImageSequential(SequentialBase):
"""
if params is None:
raise NotImplementedError("requires params to be provided.")
- named_modules: Iterator[Tuple[str, nn.Module]] = self.get_forward_sequence(params)
+ named_modules: Iterator[Tuple[str, Module]] = self.get_forward_sequence(params)
# Define as 1 for broadcasting
res_mat: Optional[Tensor] = None
@@ -276,7 +275,7 @@ class ImageSequential(SequentialBase):
module, (MixAugmentationBase, MixAugmentationBaseV2)
):
pdata = cast(Dict[str, Tensor], param.data)
- to_apply = pdata['batch_prob'] # type: ignore
+ to_apply = pdata['batch_prob']
ori_shape = input.shape
try:
input = module.transform_tensor(input)
@@ -289,7 +288,7 @@ class ImageSequential(SequentialBase):
flags = override_parameters(module.flags, extra_args, in_place=False)
mat[to_apply] = module.compute_transformation(input[to_apply], param.data, flags) # type: ignore
else:
- mat = torch.as_tensor(module._transform_matrix, device=input.device, dtype=input.dtype)
+ mat = as_tensor(module._transform_matrix, device=input.device, dtype=input.dtype)
res_mat = mat if res_mat is None else mat @ res_mat
input = module.transform_output_tensor(input, ori_shape)
if module.keepdim and ori_shape != input.shape:
@@ -297,12 +296,12 @@ class ImageSequential(SequentialBase):
elif isinstance(module, (ImageSequential,)):
# If not augmentationSequential
if isinstance(module, (kornia.augmentation.AugmentationSequential,)) and not recompute:
- mat = torch.as_tensor(module._transform_matrix, device=input.device, dtype=input.dtype)
+ mat = as_tensor(module._transform_matrix, device=input.device, dtype=input.dtype)
else:
maybe_param_data = cast(Optional[List[ParamItem]], param.data)
_mat = module.get_transformation_matrix(
input, maybe_param_data, recompute=recompute, extra_args=extra_args
- ) # type: ignore
+ )
mat = module.identity_matrix(input) if _mat is None else _mat
res_mat = mat if res_mat is None else mat @ res_mat
return res_mat
@@ -311,7 +310,7 @@ class ImageSequential(SequentialBase):
"""Check if all transformations are intensity-based.
Args:
- strict: if strict is False, it will allow non-augmentation nn.Modules to be passed.
+ strict: if strict is False, it will allow non-augmentation Modules to be passed.
e.g. `kornia.enhance.AdjustBrightness` will be recognized as non-intensity module
if strict is set to True.
@@ -366,7 +365,7 @@ class ImageSequential(SequentialBase):
return input
- def forward( # type: ignore
+ def forward(
self,
input: Tensor,
label: Optional[Tensor] = None,
@@ -382,7 +381,7 @@ class ImageSequential(SequentialBase):
self.return_label = label is not None or self.contains_label_operations(params)
for param in params:
module = self.get_submodule(param.name)
- input, label = self.apply_to_input(input, label, module, param=param, extra_args=extra_args) # type: ignore
+ input, label = self.apply_to_input(input, label, module, param=param, extra_args=extra_args)
if isinstance(module, (_AugmentationBase, MixAugmentationBase, MixAugmentationBaseV2, SequentialBase)):
param = ParamItem(param.name, module._params)
else:
diff --git a/kornia/augmentation/container/utils.py b/kornia/augmentation/container/utils.py
index 5c8754d39..1f3e9be10 100644
--- a/kornia/augmentation/container/utils.py
+++ b/kornia/augmentation/container/utils.py
@@ -4,8 +4,6 @@ from functools import partial
from typing import Any, Callable, Dict, Iterator, List, Optional, Tuple, Type, Union, cast
import torch
-import torch.nn as nn
-from torch import Tensor
import kornia # lazy loading for circular dependencies
from kornia.augmentation import GeometricAugmentationBase2D, MixAugmentationBase, RandomCrop, RandomErasing
@@ -14,6 +12,7 @@ from kornia.augmentation.base import _AugmentationBase
from kornia.augmentation.container.base import ParamItem
from kornia.augmentation.utils import override_parameters
from kornia.constants import DataKey
+from kornia.core import Module, Tensor, as_tensor
from kornia.geometry.bbox import transform_bbox
from kornia.geometry.linalg import transform_points
from kornia.testing import KORNIA_UNWRAP
@@ -21,7 +20,7 @@ from kornia.utils.helpers import _torch_inverse_cast
def _get_geometric_only_param(module: "kornia.augmentation.ImageSequential", param: List[ParamItem]) -> List[ParamItem]:
- named_modules: Iterator[Tuple[str, nn.Module]] = module.get_forward_sequence(param)
+ named_modules: Iterator[Tuple[str, Module]] = module.get_forward_sequence(param)
res: List[ParamItem] = []
for (_, mod), p in zip(named_modules, param):
@@ -36,12 +35,7 @@ class ApplyInverseInterface(metaclass=ABCMeta):
@classmethod
@abstractmethod
def apply_trans(
- cls,
- input: Tensor,
- label: Optional[Tensor],
- module: nn.Module,
- param: ParamItem,
- extra_args: Dict[str, Any] = {},
+ cls, input: Tensor, label: Optional[Tensor], module: Module, param: ParamItem, extra_args: Dict[str, Any] = {}
) -> Tuple[Tensor, Optional[Tensor]]:
"""Apply a transformation with respect to the parameters.
@@ -57,7 +51,7 @@ class ApplyInverseInterface(metaclass=ABCMeta):
@classmethod
@abstractmethod
def inverse(
- cls, input: Tensor, module: nn.Module, param: Optional[ParamItem] = None, extra_args: Dict[str, Any] = {}
+ cls, input: Tensor, module: Module, param: Optional[ParamItem] = None, extra_args: Dict[str, Any] = {}
) -> Tensor:
"""Inverse a transformation with respect to the parameters.
@@ -77,12 +71,7 @@ class ApplyInverseImpl(ApplyInverseInterface):
@classmethod
def apply_trans(
- cls,
- input: Tensor,
- label: Optional[Tensor],
- module: nn.Module,
- param: ParamItem,
- extra_args: Dict[str, Any] = {},
+ cls, input: Tensor, label: Optional[Tensor], module: Module, param: ParamItem, extra_args: Dict[str, Any] = {}
) -> Tuple[Tensor, Optional[Tensor]]:
"""Apply a transformation with respect to the parameters.
@@ -98,7 +87,7 @@ class ApplyInverseImpl(ApplyInverseInterface):
mat = cast(Tensor, module.transform_matrix)
else:
mat = cls._get_transformation(input, module, param, extra_args=extra_args)
- mat = torch.as_tensor(mat, device=input.device, dtype=input.dtype)
+ 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
@@ -113,7 +102,7 @@ class ApplyInverseImpl(ApplyInverseInterface):
@classmethod
def inverse(
- cls, input: Tensor, module: nn.Module, param: Optional[ParamItem] = None, extra_args: Dict[str, Any] = {}
+ cls, input: Tensor, module: Module, param: Optional[ParamItem] = None, extra_args: Dict[str, Any] = {}
) -> Tensor:
"""Inverse a transformation with respect to the parameters.
@@ -128,16 +117,16 @@ class ApplyInverseImpl(ApplyInverseInterface):
mat = cast(Tensor, module.transform_matrix)
else:
mat = cls._get_transformation(input, module, param, extra_args=extra_args)
- mat = torch.as_tensor(mat, device=input.device, dtype=input.dtype)
+ mat = as_tensor(mat, device=input.device, dtype=input.dtype)
if mat is not None:
transform: Tensor = cls._get_inverse_transformation(mat)
- input = cls.apply_func(torch.as_tensor(transform, device=input.device, dtype=input.dtype), input)
+ input = cls.apply_func(as_tensor(transform, device=input.device, dtype=input.dtype), input)
return input
@classmethod
def _get_transformation(
- cls, input: Tensor, module: nn.Module, maybe_param: Optional[ParamItem] = None, extra_args: Dict[str, Any] = {}
+ cls, input: Tensor, module: Module, maybe_param: Optional[ParamItem] = None, extra_args: Dict[str, Any] = {}
) -> Optional[Tensor]:
if (
@@ -170,13 +159,8 @@ class InputApplyInverse(ApplyInverseImpl):
data_key = DataKey.INPUT
@classmethod
- def apply_trans( # type: ignore
- cls,
- input: Tensor,
- label: Optional[Tensor],
- module: nn.Module,
- param: ParamItem,
- extra_args: Dict[str, Any] = {},
+ def apply_trans(
+ cls, input: Tensor, label: Optional[Tensor], module: Module, param: ParamItem, extra_args: Dict[str, Any] = {}
) -> Tuple[Tensor, Optional[Tensor]]:
"""Apply a transformation with respect to the parameters.
@@ -214,7 +198,7 @@ class InputApplyInverse(ApplyInverseImpl):
@classmethod
def inverse(
- cls, input: Tensor, module: nn.Module, param: Optional[ParamItem] = None, extra_args: Dict[str, Any] = {}
+ cls, input: Tensor, module: Module, param: Optional[ParamItem] = None, extra_args: Dict[str, Any] = {}
) -> Tensor:
"""Inverse a transformation with respect to the parameters.
@@ -264,7 +248,7 @@ class MaskApplyInverse(ApplyInverseImpl):
cls,
input: Tensor,
label: Optional[Tensor],
- module: nn.Module,
+ module: Module,
param: Optional[ParamItem] = None,
extra_args: Dict[str, Any] = {},
) -> Tuple[Tensor, Optional[Tensor]]:
@@ -280,7 +264,7 @@ class MaskApplyInverse(ApplyInverseImpl):
if param is not None:
_param = param.data
else:
- _param = None # type: ignore
+ _param = None
if isinstance(module, (GeometricAugmentationBase2D, RandomErasing)):
_param = cast(Dict[str, Tensor], _param).copy()
@@ -302,7 +286,7 @@ class MaskApplyInverse(ApplyInverseImpl):
@classmethod
def inverse(
- cls, input: Tensor, module: nn.Module, param: Optional[ParamItem] = None, extra_args: Dict[str, Any] = {}
+ cls, input: Tensor, module: Module, param: Optional[ParamItem] = None, extra_args: Dict[str, Any] = {}
) -> Tensor:
"""Inverse a transformation with respect to the parameters.
@@ -330,7 +314,7 @@ class BBoxApplyInverse(ApplyInverseImpl):
"""
@classmethod
- def _get_padding_size(cls, module: nn.Module, param: Optional[ParamItem]) -> Optional[Tensor]:
+ def _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")
@@ -394,12 +378,7 @@ class BBoxApplyInverse(ApplyInverseImpl):
@classmethod
def apply_trans(
- cls,
- input: Tensor,
- label: Optional[Tensor],
- module: nn.Module,
- param: ParamItem,
- extra_args: Dict[str, Any] = {},
+ cls, input: Tensor, label: Optional[Tensor], module: Module, param: ParamItem, extra_args: Dict[str, Any] = {}
) -> Tuple[Tensor, Optional[Tensor]]:
"""Apply a transformation with respect to the parameters.
@@ -424,7 +403,7 @@ class BBoxApplyInverse(ApplyInverseImpl):
@classmethod
def inverse(
- cls, input: Tensor, module: nn.Module, param: Optional[ParamItem] = None, extra_args: Dict[str, Any] = {}
+ cls, input: Tensor, module: Module, param: Optional[ParamItem] = None, extra_args: Dict[str, Any] = {}
) -> Tensor:
"""Inverse a transformation with respect to the parameters.
@@ -471,19 +450,14 @@ class BBoxXYXYApplyInverse(BBoxApplyInverse):
@classmethod
def apply_trans(
- cls,
- input: Tensor,
- label: Optional[Tensor],
- module: nn.Module,
- param: ParamItem,
- extra_args: Dict[str, Any] = {},
+ cls, input: Tensor, label: Optional[Tensor], module: Module, param: ParamItem, extra_args: Dict[str, Any] = {}
) -> Tuple[Tensor, Optional[Tensor]]:
warnings.warn("BBoxXYXYApplyInverse is no longer maintained. Please use BBoxApplyInverse instead.")
return super().apply_trans(input, label=label, module=module, param=param, extra_args=extra_args)
@classmethod
def inverse(
- cls, input: Tensor, module: nn.Module, param: Optional[ParamItem] = None, extra_args: Dict[str, Any] = {}
+ cls, input: Tensor, module: Module, param: Optional[ParamItem] = None, extra_args: Dict[str, Any] = {}
) -> Tensor:
warnings.warn("BBoxXYXYApplyInverse is no longer maintained. Please use BBoxApplyInverse instead.")
return super().inverse(input, module=module, param=param, extra_args=extra_args)
@@ -593,7 +567,7 @@ class ApplyInverse:
cls,
input: Tensor,
label: Optional[Tensor],
- module: nn.Module,
+ module: Module,
param: ParamItem,
dcate: Union[str, int, DataKey] = DataKey.INPUT,
extra_args: Dict[str, Any] = {},
@@ -613,14 +587,14 @@ class ApplyInverse:
if isinstance(input, (tuple,)):
# If the input is a tuple with (input, mat) or something else
- return (func.apply_trans(input[0], label, module, param, extra_args), *input[1:]) # type: ignore
+ return (func.apply_trans(input[0], label, module, param, extra_args), *input[1:])
return func.apply_trans(input, label, module=module, param=param, extra_args=extra_args)
@classmethod
def inverse_by_key(
cls,
input: Tensor,
- module: nn.Module,
+ module: Module,
param: Optional[ParamItem] = None,
dcate: Union[str, int, DataKey] = DataKey.INPUT,
extra_args: Dict[str, Any] = {},
diff --git a/kornia/augmentation/container/video.py b/kornia/augmentation/container/video.py
index 4a0448208..09ffed40b 100644
--- a/kornia/augmentation/container/video.py
+++ b/kornia/augmentation/container/video.py
@@ -1,7 +1,6 @@
from typing import Any, Dict, List, Optional, Tuple, Union, cast
import torch
-import torch.nn as nn
import kornia
from kornia.augmentation import RandomCrop
@@ -10,6 +9,7 @@ from kornia.augmentation.base import _AugmentationBase
from kornia.augmentation.container.base import SequentialBase
from kornia.augmentation.container.image import ImageSequential, ParamItem, _get_new_batch_shape
from kornia.augmentation.container.utils import InputApplyInverse, MaskApplyInverse
+from kornia.core import Module, Tensor
__all__ = ["VideoSequential"]
@@ -96,7 +96,7 @@ class VideoSequential(ImageSequential):
def __init__(
self,
- *args: nn.Module,
+ *args: Module,
data_format: str = "BTCHW",
same_on_frame: bool = True,
random_apply: Union[int, bool, Tuple[int, int]] = False,
@@ -123,7 +123,7 @@ class VideoSequential(ImageSequential):
# Fix mypy complains: error: Incompatible return value type (got "Tuple[int, ...]", expected "Size")
return cast(torch.Size, batch_shape[:chennel_index] + batch_shape[chennel_index + 1 :])
- def __repeat_param_across_channels__(self, param: torch.Tensor, frame_num: int) -> torch.Tensor:
+ def __repeat_param_across_channels__(self, param: Tensor, frame_num: int) -> Tensor:
"""Repeat parameters across channels.
The input is shaped as (B, ...), while to output (B * same_on_frame, ...), which
@@ -133,11 +133,11 @@ class VideoSequential(ImageSequential):
| ch_size | | ch_size | ..., | ch_size |
"""
repeated = param[:, None, ...].repeat(1, frame_num, *([1] * len(param.shape[1:])))
- return repeated.reshape(-1, *list(param.shape[1:])) # type: ignore
+ return repeated.reshape(-1, *list(param.shape[1:]))
def _input_shape_convert_in(
- self, input: torch.Tensor, label: Optional[torch.Tensor], frame_num: int
- ) -> Tuple[torch.Tensor, Optional[torch.Tensor]]:
+ self, input: Tensor, label: Optional[Tensor], frame_num: int
+ ) -> Tuple[Tensor, Optional[Tensor]]:
# Convert any shape to (B, T, C, H, W)
if self.data_format == "BCTHW":
# Convert (B, C, T, H, W) to (B, T, C, H, W)
@@ -160,8 +160,8 @@ class VideoSequential(ImageSequential):
return input, label
def _input_shape_convert_back(
- self, input: torch.Tensor, label: Optional[torch.Tensor], frame_num: int
- ) -> Tuple[torch.Tensor, Optional[torch.Tensor]]:
+ self, input: Tensor, label: Optional[Tensor], frame_num: int
+ ) -> Tuple[Tensor, Optional[Tensor]]:
input = input.view(-1, frame_num, *input.shape[1:])
if self.data_format == "BCTHW":
input = input.transpose(1, 2)
@@ -217,8 +217,8 @@ class VideoSequential(ImageSequential):
return params
def inverse(
- self, input: torch.Tensor, params: Optional[List[ParamItem]] = None, extra_args: Dict[str, Any] = {}
- ) -> torch.Tensor:
+ 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
@@ -239,13 +239,13 @@ class VideoSequential(ImageSequential):
return input
- def forward( # type: ignore
+ def forward(
self,
- input: torch.Tensor,
- label: Optional[torch.Tensor] = None,
+ input: Tensor,
+ label: Optional[Tensor] = None,
params: Optional[List[ParamItem]] = None,
extra_args: Dict[str, Any] = {},
- ) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]:
+ ) -> Union[Tensor, Tuple[Tensor, Tensor]]:
"""Define the video computation performed."""
if len(input.shape) != 5:
raise AssertionError(f"Input must be a 5-dim tensor. Got {input.shape}.")
@@ -263,11 +263,11 @@ class VideoSequential(ImageSequential):
batch_size: int = input.size(0)
input = input.view(-1, *input.shape[2:])
- out = super().forward(input, label, params, extra_args=extra_args) # type: ignore
+ out = super().forward(input, label, params, extra_args=extra_args)
if self.return_label:
- output, label = cast(Tuple[torch.Tensor, torch.Tensor], out)
+ output, label = cast(Tuple[Tensor, Tensor], out)
else:
- output = cast(torch.Tensor, out)
+ output = cast(Tensor, out)
if isinstance(output, (tuple, list)):
if self.apply_inverse_func in (InputApplyInverse, MaskApplyInverse):
diff --git a/kornia/augmentation/random_generator/_2d/affine.py b/kornia/augmentation/random_generator/_2d/affine.py
index 1cede6ab4..d03aa588b 100644
--- a/kornia/augmentation/random_generator/_2d/affine.py
+++ b/kornia/augmentation/random_generator/_2d/affine.py
@@ -11,6 +11,7 @@ from kornia.augmentation.utils import (
_joint_range_check,
_range_bound,
)
+from kornia.core import Device, Tensor, as_tensor, concatenate, stack, tensor, zeros
from kornia.utils.helpers import _deprecated, _extract_device_dtype
@@ -35,12 +36,12 @@ class AffineGenerator(RandomGeneratorBase):
Returns:
A dict of parameters to be passed for transformation.
- - translations (torch.Tensor): element-wise translations with a shape of (B, 2).
- - center (torch.Tensor): element-wise center with a shape of (B, 2).
- - scale (torch.Tensor): element-wise scales with a shape of (B, 2).
- - angle (torch.Tensor): element-wise rotation angles with a shape of (B,).
- - sx (torch.Tensor): element-wise x-axis shears with a shape of (B,).
- - sy (torch.Tensor): element-wise y-axis shears with a shape of (B,).
+ - translations (Tensor): element-wise translations with a shape of (B, 2).
+ - center (Tensor): element-wise center with a shape of (B, 2).
+ - scale (Tensor): element-wise scales with a shape of (B, 2).
+ - angle (Tensor): element-wise rotation angles with a shape of (B,).
+ - sx (Tensor): element-wise x-axis shears with a shape of (B,).
+ - sy (Tensor): element-wise y-axis shears with a shape of (B,).
Note:
The generated random numbers are not reproducible across different devices and dtypes. By default,
@@ -50,10 +51,10 @@ class AffineGenerator(RandomGeneratorBase):
def __init__(
self,
- degrees: Union[torch.Tensor, float, Tuple[float, float]],
- translate: Optional[Union[torch.Tensor, Tuple[float, float]]] = None,
- scale: Optional[Union[torch.Tensor, Tuple[float, float], Tuple[float, float, float, float]]] = None,
- shear: Optional[Union[torch.Tensor, float, Tuple[float, float]]] = None,
+ degrees: Union[Tensor, float, Tuple[float, float]],
+ translate: Optional[Union[Tensor, Tuple[float, float]]] = None,
+ scale: Optional[Union[Tensor, Tuple[float, float], Tuple[float, float, float, float]]] = None,
+ shear: Optional[Union[Tensor, float, Tuple[float, float]]] = None,
) -> None:
super().__init__()
self.degrees = degrees
@@ -74,14 +75,14 @@ class AffineGenerator(RandomGeneratorBase):
device=device, dtype=dtype
)
)
- _scale: Optional[torch.Tensor] = None
+ _scale: Optional[Tensor] = None
if self.scale is not None:
if len(self.scale) == 2:
_scale = _range_bound(self.scale[:2], 'scale', bounds=(0, float('inf')), check='singular').to(
device=device, dtype=dtype
)
elif len(self.scale) == 4:
- _scale = torch.cat(
+ _scale = concatenate(
[
_range_bound(self.scale[:2], 'scale_x', bounds=(0, float('inf')), check='singular'),
_range_bound(
@@ -91,16 +92,16 @@ class AffineGenerator(RandomGeneratorBase):
).to(device=device, dtype=dtype)
else:
raise ValueError(f"'scale' expected to be either 2 or 4 elements. Got {self.scale}")
- _shear: Optional[torch.Tensor] = None
+ _shear: Optional[Tensor] = None
if self.shear is not None:
- shear = torch.as_tensor(self.shear, device=device, dtype=dtype)
+ shear = as_tensor(self.shear, device=device, dtype=dtype)
if shear.shape == torch.Size([2, 2]):
_shear = shear
else:
- _shear = torch.stack(
+ _shear = stack(
[
_range_bound(shear if shear.dim() == 0 else shear[:2], 'shear-x', 0, (-360, 360)),
- torch.tensor([0, 0], device=device, dtype=dtype)
+ tensor([0, 0], device=device, dtype=dtype)
if shear.dim() == 0 or len(shear) == 2
else _range_bound(shear[2:], 'shear-y', 0, (-360, 360)),
]
@@ -125,8 +126,8 @@ class AffineGenerator(RandomGeneratorBase):
else:
raise ValueError(f"'scale' expected to be either 2 or 4 elements. Got {self.scale}")
if _shear is not None:
- _joint_range_check(cast(torch.Tensor, _shear)[0], "shear")
- _joint_range_check(cast(torch.Tensor, _shear)[1], "shear")
+ _joint_range_check(cast(Tensor, _shear)[0], "shear")
+ _joint_range_check(cast(Tensor, _shear)[1], "shear")
shear_x_sampler = Uniform(_shear[0][0], _shear[0][1], validate_args=False)
shear_y_sampler = Uniform(_shear[1][0], _shear[1][1], validate_args=False)
@@ -138,7 +139,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, torch.Tensor]: # type: ignore
+ def forward(self, batch_shape: torch.Size, same_on_batch: bool = False) -> Dict[str, Tensor]:
batch_size = batch_shape[0]
height = batch_shape[-2]
width = batch_shape[-1]
@@ -160,7 +161,7 @@ class AffineGenerator(RandomGeneratorBase):
_scale = torch.ones((batch_size, 2), device=_device, dtype=_dtype)
if self.translate_x_sampler is not None and self.translate_y_sampler is not None:
- translations = torch.stack(
+ translations = stack(
[
_adapted_rsampling((batch_size,), self.translate_x_sampler, same_on_batch) * width,
_adapted_rsampling((batch_size,), self.translate_y_sampler, same_on_batch) * height,
@@ -169,9 +170,9 @@ class AffineGenerator(RandomGeneratorBase):
)
translations = translations.to(device=_device, dtype=_dtype)
else:
- translations = torch.zeros((batch_size, 2), device=_device, dtype=_dtype)
+ translations = zeros((batch_size, 2), device=_device, dtype=_dtype)
- center: torch.Tensor = torch.tensor([width, height], device=_device, dtype=_dtype).view(1, 2) / 2.0 - 0.5
+ center: Tensor = tensor([width, height], device=_device, dtype=_dtype).view(1, 2) / 2.0 - 0.5
center = center.expand(batch_size, -1)
if self.shear_x_sampler is not None and self.shear_y_sampler is not None:
@@ -180,7 +181,7 @@ class AffineGenerator(RandomGeneratorBase):
sx = sx.to(device=_device, dtype=_dtype)
sy = sy.to(device=_device, dtype=_dtype)
else:
- sx = sy = torch.tensor([0] * batch_size, device=_device, dtype=_dtype)
+ sx = sy = tensor([0] * batch_size, device=_device, dtype=_dtype)
return dict(translations=translations, center=center, scale=_scale, angle=angle, sx=sx, sy=sy)
@@ -190,21 +191,21 @@ def random_affine_generator(
batch_size: int,
height: int,
width: int,
- degrees: torch.Tensor,
- translate: Optional[torch.Tensor] = None,
- scale: Optional[torch.Tensor] = None,
- shear: Optional[torch.Tensor] = None,
+ degrees: Tensor,
+ translate: Optional[Tensor] = None,
+ scale: Optional[Tensor] = None,
+ shear: Optional[Tensor] = None,
same_on_batch: bool = False,
- device: torch.device = torch.device('cpu'),
+ device: Device = torch.device('cpu'),
dtype: torch.dtype = torch.float32,
-) -> Dict[str, torch.Tensor]:
+) -> Dict[str, Tensor]:
r"""Get parameters for ``affine`` for a random affine transform.
Args:
batch_size (int): the tensor batch size.
height (int) : height of the image.
width (int): width of the image.
- degrees (torch.Tensor): Range of degrees to select from like (min, max).
+ degrees (Tensor): Range of degrees to select from like (min, max).
translate (tensor, optional): tuple of maximum absolute fraction for horizontal
and vertical translations. For example translate=(a, b), then horizontal shift
is randomly sampled in the range -img_width * a < dx < img_width * a and vertical shift is
@@ -215,17 +216,17 @@ def random_affine_generator(
Shear is a 2x2 tensor, a x-axis shear in (shear[0][0], shear[0][1]) and y-axis shear in
(shear[1][0], shear[1][1]) will be applied. Will not apply shear by default.
same_on_batch (bool): apply the same transformation across the batch. Default: False.
- device (torch.device): the device on which the random numbers will be generated. Default: cpu.
+ device (Device): the device on which the random numbers will be generated. Default: cpu.
dtype (torch.dtype): the data type of the generated random numbers. Default: float32.
Returns:
- params Dict[str, torch.Tensor]: parameters to be passed for transformation.
- - translations (torch.Tensor): element-wise translations with a shape of (B, 2).
- - center (torch.Tensor): element-wise center with a shape of (B, 2).
- - scale (torch.Tensor): element-wise scales with a shape of (B, 2).
- - angle (torch.Tensor): element-wise rotation angles with a shape of (B,).
- - sx (torch.Tensor): element-wise x-axis shears with a shape of (B,).
- - sy (torch.Tensor): element-wise y-axis shears with a shape of (B,).
+ params Dict[str, Tensor]: parameters to be passed for transformation.
+ - translations (Tensor): element-wise translations with a shape of (B, 2).
+ - center (Tensor): element-wise center with a shape of (B, 2).
+ - scale (Tensor): element-wise scales with a shape of (B, 2).
+ - angle (Tensor): element-wise rotation angles with a shape of (B,).
+ - sx (Tensor): element-wise x-axis shears with a shape of (B,).
+ - sy (Tensor): element-wise y-axis shears with a shape of (B,).
Note:
The generated random numbers are not reproducible across different devices and dtypes.
@@ -245,10 +246,10 @@ def random_affine_generator(
scale = scale.to(device=device, dtype=dtype)
if not (len(scale.shape) == 1 and len(scale) in (2, 4)):
raise AssertionError(f"`scale` shall have 2 or 4 elements. Got {scale}.")
- _joint_range_check(cast(torch.Tensor, scale[:2]), "scale")
+ _joint_range_check(cast(Tensor, scale[:2]), "scale")
_scale = _adapted_uniform((batch_size,), scale[0], scale[1], same_on_batch).unsqueeze(1).repeat(1, 2)
if len(scale) == 4:
- _joint_range_check(cast(torch.Tensor, scale[2:]), "scale_y")
+ _joint_range_check(cast(Tensor, scale[2:]), "scale_y")
_scale[:, 1] = _adapted_uniform((batch_size,), scale[2], scale[3], same_on_batch)
_scale = _scale.to(device=_device, dtype=_dtype)
else:
@@ -258,9 +259,9 @@ def random_affine_generator(
translate = translate.to(device=device, dtype=dtype)
if not (0.0 <= translate[0] <= 1.0 and 0.0 <= translate[1] <= 1.0 and translate.shape == torch.Size([2])):
raise AssertionError(f"Expect translate contains two elements and ranges are in [0, 1]. Got {translate}.")
- max_dx: torch.Tensor = translate[0] * width
- max_dy: torch.Tensor = translate[1] * height
- translations = torch.stack(
+ max_dx: Tensor = translate[0] * width
+ max_dy: Tensor = translate[1] * height
+ translations = stack(
[
_adapted_uniform((batch_size,), -max_dx, max_dx, same_on_batch),
_adapted_uniform((batch_size,), -max_dy, max_dy, same_on_batch),
@@ -269,20 +270,20 @@ def random_affine_generator(
)
translations = translations.to(device=_device, dtype=_dtype)
else:
- translations = torch.zeros((batch_size, 2), device=_device, dtype=_dtype)
+ translations = zeros((batch_size, 2), device=_device, dtype=_dtype)
- center: torch.Tensor = torch.tensor([width, height], device=_device, dtype=_dtype).view(1, 2) / 2.0 - 0.5
+ center: Tensor = tensor([width, height], device=_device, dtype=_dtype).view(1, 2) / 2.0 - 0.5
center = center.expand(batch_size, -1)
if shear is not None:
shear = shear.to(device=device, dtype=dtype)
- _joint_range_check(cast(torch.Tensor, shear)[0], "shear")
- _joint_range_check(cast(torch.Tensor, shear)[1], "shear")
+ _joint_range_check(cast(Tensor, shear)[0], "shear")
+ _joint_range_check(cast(Tensor, shear)[1], "shear")
sx = _adapted_uniform((batch_size,), shear[0][0], shear[0][1], same_on_batch)
sy = _adapted_uniform((batch_size,), shear[1][0], shear[1][1], same_on_batch)
sx = sx.to(device=_device, dtype=_dtype)
sy = sy.to(device=_device, dtype=_dtype)
else:
- sx = sy = torch.tensor([0] * batch_size, device=_device, dtype=_dtype)
+ sx = sy = tensor([0] * batch_size, device=_device, dtype=_dtype)
return dict(translations=translations, center=center, scale=_scale, angle=angle, sx=sx, sy=sy)
diff --git a/kornia/augmentation/random_generator/_2d/color_jiggle.py b/kornia/augmentation/random_generator/_2d/color_jiggle.py
index a3e6ebdda..1a5d47c42 100644
--- a/kornia/augmentation/random_generator/_2d/color_jiggle.py
+++ b/kornia/augmentation/random_generator/_2d/color_jiggle.py
@@ -2,11 +2,11 @@ from functools import partial
from typing import Dict, List, Tuple, Union
import torch
-from torch import Tensor
from torch.distributions import Uniform
from kornia.augmentation.random_generator.base import RandomGeneratorBase
from kornia.augmentation.utils import _adapted_rsampling, _common_param_check, _joint_range_check, _range_bound
+from kornia.core import Tensor
from kornia.utils.helpers import _extract_device_dtype
@@ -71,7 +71,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]: # type:ignore
+ def forward(self, batch_shape: torch.Size, 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 c94e57031..80926652a 100644
--- a/kornia/augmentation/random_generator/_2d/color_jitter.py
+++ b/kornia/augmentation/random_generator/_2d/color_jitter.py
@@ -2,11 +2,11 @@ from functools import partial
from typing import Dict, List, Tuple, Union
import torch
-from torch import Tensor
from torch.distributions import Uniform
from kornia.augmentation.random_generator.base import RandomGeneratorBase
from kornia.augmentation.utils import _adapted_rsampling, _common_param_check, _joint_range_check, _range_bound
+from kornia.core import Tensor
from kornia.utils.helpers import _extract_device_dtype
@@ -75,7 +75,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]: # type:ignore
+ def forward(self, batch_shape: torch.Size, 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 dbebb48e1..fb7ad855e 100644
--- a/kornia/augmentation/random_generator/_2d/crop.py
+++ b/kornia/augmentation/random_generator/_2d/crop.py
@@ -5,6 +5,7 @@ from torch.distributions import Uniform
from kornia.augmentation.random_generator.base import RandomGeneratorBase
from kornia.augmentation.utils import _adapted_rsampling, _adapted_uniform, _common_param_check, _joint_range_check
+from kornia.core import Device, Tensor, tensor, where, zeros
from kornia.geometry.bbox import bbox_generator
from kornia.utils.helpers import _deprecated, _extract_device_dtype
@@ -18,9 +19,9 @@ class CropGenerator(RandomGeneratorBase):
resize_to (tuple): Desired output size of the crop, like (h, w). If None, no resize will be performed.
Returns:
- params Dict[str, torch.Tensor]: parameters to be passed for transformation.
- - src (torch.Tensor): cropping bounding boxes with a shape of (B, 4, 2).
- - dst (torch.Tensor): output bounding boxes with a shape (B, 4, 2).
+ params Dict[str, Tensor]: parameters to be passed for transformation.
+ - src (Tensor): cropping bounding boxes with a shape of (B, 4, 2).
+ - dst (Tensor): output bounding boxes with a shape (B, 4, 2).
Note:
The generated random numbers are not reproducible across different devices and dtypes. By default,
@@ -28,7 +29,7 @@ class CropGenerator(RandomGeneratorBase):
``self.set_rng_device_and_dtype(device="cuda", dtype=torch.float64)``.
"""
- def __init__(self, size: Union[Tuple[int, int], torch.Tensor], resize_to: Optional[Tuple[int, int]] = None) -> None:
+ def __init__(self, size: Union[Tuple[int, int], Tensor], resize_to: Optional[Tuple[int, int]] = None) -> None:
super().__init__()
self.size = size
self.resize_to = resize_to
@@ -40,24 +41,21 @@ class CropGenerator(RandomGeneratorBase):
return repr
def make_samplers(self, device: torch.device, dtype: torch.dtype) -> None:
- self.rand_sampler = Uniform(
- torch.tensor(0.0, device=device, dtype=dtype), torch.tensor(1.0, device=device, dtype=dtype)
- )
+ 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, torch.Tensor]: # type:ignore
+ def forward(self, batch_shape: torch.Size, 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, torch.Tensor) else None])
+ _device, _dtype = _extract_device_dtype([self.size if isinstance(self.size, Tensor) else None])
if batch_size == 0:
return dict(
- src=torch.zeros([0, 4, 2], device=_device, dtype=_dtype),
- dst=torch.zeros([0, 4, 2], device=_device, dtype=_dtype),
+ src=zeros([0, 4, 2], device=_device, dtype=_dtype), dst=zeros([0, 4, 2], device=_device, dtype=_dtype)
)
input_size = (batch_shape[-2], batch_shape[-1])
- if not isinstance(self.size, torch.Tensor):
- size = torch.tensor(self.size, device=_device, dtype=_dtype).repeat(batch_size, 1)
+ if not isinstance(self.size, Tensor):
+ size = tensor(self.size, device=_device, dtype=_dtype).repeat(batch_size, 1)
else:
size = self.size.to(device=_device, dtype=_dtype)
if size.shape != torch.Size([batch_size, 2]):
@@ -90,14 +88,14 @@ class CropGenerator(RandomGeneratorBase):
crop_src = bbox_generator(
x_start.view(-1).to(device=_device, dtype=_dtype),
y_start.view(-1).to(device=_device, dtype=_dtype),
- torch.where(size[:, 1] == 0, torch.tensor(input_size[1], device=_device, dtype=_dtype), size[:, 1]),
- torch.where(size[:, 0] == 0, torch.tensor(input_size[0], device=_device, dtype=_dtype), size[:, 0]),
+ where(size[:, 1] == 0, tensor(input_size[1], device=_device, dtype=_dtype), size[:, 1]),
+ where(size[:, 0] == 0, tensor(input_size[0], device=_device, dtype=_dtype), size[:, 0]),
)
if self.resize_to is None:
crop_dst = bbox_generator(
- torch.tensor([0] * batch_size, device=_device, dtype=_dtype),
- torch.tensor([0] * batch_size, device=_device, dtype=_dtype),
+ tensor([0] * batch_size, device=_device, dtype=_dtype),
+ tensor([0] * batch_size, device=_device, dtype=_dtype),
size[:, 1],
size[:, 0],
)
@@ -111,7 +109,7 @@ class CropGenerator(RandomGeneratorBase):
and self.resize_to[1] > 0
):
raise AssertionError(f"`resize_to` must be a tuple of 2 positive integers. Got {self.resize_to}.")
- crop_dst = torch.tensor(
+ crop_dst = tensor(
[
[
[0, 0],
@@ -123,9 +121,9 @@ class CropGenerator(RandomGeneratorBase):
device=_device,
dtype=_dtype,
).repeat(batch_size, 1, 1)
- _output_size = torch.tensor(self.resize_to, device=_device, dtype=torch.long).expand(batch_size, -1)
+ _output_size = tensor(self.resize_to, device=_device, dtype=torch.long).expand(batch_size, -1)
- _input_size = torch.tensor(input_size, device=_device, dtype=torch.long).expand(batch_size, -1)
+ _input_size = tensor(input_size, device=_device, dtype=torch.long).expand(batch_size, -1)
return dict(src=crop_src, dst=crop_dst, input_size=_input_size, output_size=_output_size)
@@ -135,12 +133,12 @@ class ResizedCropGenerator(CropGenerator):
Args:
output_size (Tuple[int, int]): expected output size of each edge.
- scale (torch.Tensor): range of size of the origin size cropped with (2,) shape.
- ratio (torch.Tensor): range of aspect ratio of the origin aspect ratio cropped with (2,) shape.
+ scale (Tensor): range of size of the origin size cropped with (2,) shape.
+ ratio (Tensor): range of aspect ratio of the origin aspect ratio cropped with (2,) shape.
Returns:
- params Dict[str, torch.Tensor]: parameters to be passed for transformation.
- - size (torch.Tensor): element-wise cropping sizes with a shape of (B, 2).
+ params Dict[str, Tensor]: parameters to be passed for transformation.
+ - size (Tensor): element-wise cropping sizes with a shape of (B, 2).
Note:
The generated random numbers are not reproducible across different devices and dtypes.
@@ -156,8 +154,8 @@ class ResizedCropGenerator(CropGenerator):
def __init__(
self,
output_size: Tuple[int, int],
- scale: Union[torch.Tensor, Tuple[float, float]],
- ratio: Union[torch.Tensor, Tuple[float, float]],
+ scale: Union[Tensor, Tuple[float, float]],
+ ratio: Union[Tensor, Tuple[float, float]],
) -> None:
if not (
len(output_size) == 2
@@ -181,21 +179,19 @@ class ResizedCropGenerator(CropGenerator):
ratio = torch.as_tensor(self.ratio, device=device, dtype=dtype)
_joint_range_check(scale, "scale")
_joint_range_check(ratio, "ratio")
- self.rand_sampler = Uniform(
- torch.tensor(0.0, device=device, dtype=dtype), torch.tensor(1.0, device=device, dtype=dtype)
- )
+ 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, torch.Tensor]: # type:ignore
+ def forward(self, batch_shape: torch.Size, 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])
if batch_size == 0:
return dict(
- src=torch.zeros([0, 4, 2], device=_device, dtype=_dtype),
- dst=torch.zeros([0, 4, 2], device=_device, dtype=_dtype),
- size=torch.zeros([0, 2], device=_device, dtype=_dtype),
+ src=zeros([0, 4, 2], device=_device, dtype=_dtype),
+ dst=zeros([0, 4, 2], device=_device, dtype=_dtype),
+ size=zeros([0, 2], device=_device, dtype=_dtype),
)
rand = _adapted_rsampling((batch_size, 10), self.rand_sampler, same_on_batch).to(device=_device, dtype=_dtype)
@@ -219,16 +215,16 @@ class ResizedCropGenerator(CropGenerator):
if not cond_bool.all():
# Fallback to center crop
in_ratio = float(size[0]) / float(size[1])
- _min = self.ratio.min() if isinstance(self.ratio, torch.Tensor) else min(self.ratio)
+ _min = self.ratio.min() if isinstance(self.ratio, Tensor) else min(self.ratio)
if in_ratio < _min: # type:ignore
- h_ct = torch.tensor(size[0], device=_device, dtype=_dtype)
+ h_ct = tensor(size[0], device=_device, dtype=_dtype)
w_ct = torch.round(h_ct / _min)
elif in_ratio > _min: # type:ignore
- w_ct = torch.tensor(size[1], device=_device, dtype=_dtype)
+ w_ct = tensor(size[1], device=_device, dtype=_dtype)
h_ct = torch.round(w_ct * _min)
else: # whole image
- h_ct = torch.tensor(size[0], device=_device, dtype=_dtype)
- w_ct = torch.tensor(size[1], device=_device, dtype=_dtype)
+ h_ct = tensor(size[0], device=_device, dtype=_dtype)
+ w_ct = tensor(size[1], device=_device, dtype=_dtype)
h_ct = h_ct.floor()
w_ct = w_ct.floor()
@@ -244,12 +240,12 @@ class ResizedCropGenerator(CropGenerator):
def random_crop_generator(
batch_size: int,
input_size: Tuple[int, int],
- size: Union[Tuple[int, int], torch.Tensor],
+ size: Union[Tuple[int, int], Tensor],
resize_to: Optional[Tuple[int, int]] = None,
same_on_batch: bool = False,
- device: torch.device = torch.device('cpu'),
+ device: Device = torch.device('cpu'),
dtype: torch.dtype = torch.float32,
-) -> Dict[str, torch.Tensor]:
+) -> Dict[str, Tensor]:
r"""Get parameters for ```crop``` transformation for crop transform.
Args:
@@ -259,13 +255,13 @@ def random_crop_generator(
If tensor, it must be (B, 2).
resize_to (tuple): Desired output size of the crop, like (h, w). If None, no resize will be performed.
same_on_batch (bool): apply the same transformation across the batch. Default: False.
- device (torch.device): the device on which the random numbers will be generated. Default: cpu.
+ device (Device): the device on which the random numbers will be generated. Default: cpu.
dtype (torch.dtype): the data type of the generated random numbers. Default: float32.
Returns:
- params Dict[str, torch.Tensor]: parameters to be passed for transformation.
- - src (torch.Tensor): cropping bounding boxes with a shape of (B, 4, 2).
- - dst (torch.Tensor): output bounding boxes with a shape (B, 4, 2).
+ params Dict[str, Tensor]: parameters to be passed for transformation.
+ - src (Tensor): cropping bounding boxes with a shape of (B, 4, 2).
+ - dst (Tensor): output bounding boxes with a shape (B, 4, 2).
Note:
The generated random numbers are not reproducible across different devices and dtypes.
@@ -305,11 +301,11 @@ def random_crop_generator(
[30, 30]])}
"""
_common_param_check(batch_size, same_on_batch)
- _device, _dtype = _extract_device_dtype([size if isinstance(size, torch.Tensor) else None])
+ _device, _dtype = _extract_device_dtype([size if isinstance(size, Tensor) else None])
# Use float point instead
_dtype = _dtype if _dtype in [torch.float16, torch.float32, torch.float64] else dtype
- if not isinstance(size, torch.Tensor):
- size = torch.tensor(size, device=_device, dtype=_dtype).repeat(batch_size, 1)
+ if not isinstance(size, Tensor):
+ size = tensor(size, device=_device, dtype=_dtype).repeat(batch_size, 1)
else:
size = size.to(device=_device, dtype=_dtype)
if size.shape != torch.Size([batch_size, 2]):
@@ -330,8 +326,7 @@ def random_crop_generator(
if batch_size == 0:
return dict(
- src=torch.zeros([0, 4, 2], device=_device, dtype=_dtype),
- dst=torch.zeros([0, 4, 2], device=_device, dtype=_dtype),
+ src=zeros([0, 4, 2], device=_device, dtype=_dtype), dst=zeros([0, 4, 2], device=_device, dtype=_dtype)
)
if same_on_batch:
@@ -344,14 +339,14 @@ def random_crop_generator(
crop_src = bbox_generator(
x_start.view(-1).to(device=_device, dtype=_dtype),
y_start.view(-1).to(device=_device, dtype=_dtype),
- torch.where(size[:, 1] == 0, torch.tensor(input_size[1], device=_device, dtype=_dtype), size[:, 1]),
- torch.where(size[:, 0] == 0, torch.tensor(input_size[0], device=_device, dtype=_dtype), size[:, 0]),
+ where(size[:, 1] == 0, tensor(input_size[1], device=_device, dtype=_dtype), size[:, 1]),
+ where(size[:, 0] == 0, tensor(input_size[0], device=_device, dtype=_dtype), size[:, 0]),
)
if resize_to is None:
crop_dst = bbox_generator(
- torch.tensor([0] * batch_size, device=_device, dtype=_dtype),
- torch.tensor([0] * batch_size, device=_device, dtype=_dtype),
+ tensor([0] * batch_size, device=_device, dtype=_dtype),
+ tensor([0] * batch_size, device=_device, dtype=_dtype),
size[:, 1],
size[:, 0],
)
@@ -364,13 +359,13 @@ def random_crop_generator(
and resize_to[1] > 0
):
raise AssertionError(f"`resize_to` must be a tuple of 2 positive integers. Got {resize_to}.")
- crop_dst = torch.tensor(
+ crop_dst = tensor(
[[[0, 0], [resize_to[1] - 1, 0], [resize_to[1] - 1, resize_to[0] - 1], [0, resize_to[0] - 1]]],
device=_device,
dtype=_dtype,
).repeat(batch_size, 1, 1)
- _input_size = torch.tensor(input_size, device=_device, dtype=torch.long).expand(batch_size, -1)
+ _input_size = tensor(input_size, device=_device, dtype=torch.long).expand(batch_size, -1)
return dict(src=crop_src, dst=crop_dst, input_size=_input_size)
@@ -379,26 +374,26 @@ def random_crop_generator(
def random_crop_size_generator(
batch_size: int,
size: Tuple[int, int],
- scale: torch.Tensor,
- ratio: torch.Tensor,
+ scale: Tensor,
+ ratio: Tensor,
same_on_batch: bool = False,
- device: torch.device = torch.device('cpu'),
+ device: Device = torch.device('cpu'),
dtype: torch.dtype = torch.float32,
-) -> Dict[str, torch.Tensor]:
+) -> Dict[str, Tensor]:
r"""Get cropping heights and widths for ```crop``` transformation for resized crop transform.
Args:
batch_size (int): the tensor batch size.
size (Tuple[int, int]): expected output size of each edge.
- scale (torch.Tensor): range of size of the origin size cropped with (2,) shape.
- ratio (torch.Tensor): range of aspect ratio of the origin aspect ratio cropped with (2,) shape.
+ scale (Tensor): range of size of the origin size cropped with (2,) shape.
+ ratio (Tensor): range of aspect ratio of the origin aspect ratio cropped with (2,) shape.
same_on_batch (bool): apply the same transformation across the batch. Default: False.
- device (torch.device): the device on which the random numbers will be generated. Default: cpu.
+ device (Device): the device on which the random numbers will be generated. Default: cpu.
dtype (torch.dtype): the data type of the generated random numbers. Default: float32.
Returns:
- params Dict[str, torch.Tensor]: parameters to be passed for transformation.
- - size (torch.Tensor): element-wise cropping sizes with a shape of (B, 2).
+ params Dict[str, Tensor]: parameters to be passed for transformation.
+ - size (Tensor): element-wise cropping sizes with a shape of (B, 2).
Note:
The generated random numbers are not reproducible across different devices and dtypes.
@@ -419,7 +414,7 @@ def random_crop_size_generator(
_device, _dtype = _extract_device_dtype([scale, ratio])
if batch_size == 0:
- return dict(size=torch.zeros([0, 2], device=_device, dtype=_dtype))
+ return dict(size=zeros([0, 2], device=_device, dtype=_dtype))
scale = scale.to(device=device, dtype=dtype)
ratio = ratio.to(device=device, dtype=dtype)
@@ -443,14 +438,14 @@ def random_crop_size_generator(
# Fallback to center crop
in_ratio = float(size[0]) / float(size[1])
if in_ratio < ratio.min():
- h_ct = torch.tensor(size[0], device=device, dtype=dtype)
+ h_ct = tensor(size[0], device=device, dtype=dtype)
w_ct = torch.round(h_ct / ratio.min())
elif in_ratio > ratio.min():
- w_ct = torch.tensor(size[1], device=device, dtype=dtype)
+ w_ct = tensor(size[1], device=device, dtype=dtype)
h_ct = torch.round(w_ct * ratio.min())
else: # whole image
- h_ct = torch.tensor(size[0], device=device, dtype=dtype)
- w_ct = torch.tensor(size[1], device=device, dtype=dtype)
+ h_ct = tensor(size[0], device=device, dtype=dtype)
+ w_ct = tensor(size[1], device=device, dtype=dtype)
h_ct = h_ct.floor()
w_ct = w_ct.floor()
@@ -461,8 +456,8 @@ def random_crop_size_generator(
def center_crop_generator(
- batch_size: int, height: int, width: int, size: Tuple[int, int], device: torch.device = torch.device('cpu')
-) -> Dict[str, torch.Tensor]:
+ batch_size: int, height: int, width: int, size: Tuple[int, int], device: Device = torch.device('cpu')
+) -> Dict[str, Tensor]:
r"""Get parameters for ```center_crop``` transformation for center crop transform.
Args:
@@ -470,12 +465,12 @@ def center_crop_generator(
height (int) : height of the image.
width (int): width of the image.
size (tuple): Desired output size of the crop, like (h, w).
- device (torch.device): the device on which the random numbers will be generated. Default: cpu.
+ device (Device): the device on which the random numbers will be generated. Default: cpu.
Returns:
- params Dict[str, torch.Tensor]: parameters to be passed for transformation.
- - src (torch.Tensor): cropping bounding boxes with a shape of (B, 4, 2).
- - dst (torch.Tensor): output bounding boxes with a shape (B, 4, 2).
+ params Dict[str, Tensor]: parameters to be passed for transformation.
+ - src (Tensor): cropping bounding boxes with a shape of (B, 4, 2).
+ - dst (Tensor): output bounding boxes with a shape (B, 4, 2).
Note:
No random number will be generated.
@@ -506,17 +501,17 @@ def center_crop_generator(
# [y, x] origin
# top-left, top-right, bottom-right, bottom-left
- points_src: torch.Tensor = torch.tensor(
+ points_src: Tensor = tensor(
[[[start_x, start_y], [end_x, start_y], [end_x, end_y], [start_x, end_y]]], device=device, dtype=torch.long
).expand(batch_size, -1, -1)
# [y, x] destination
# top-left, top-right, bottom-right, bottom-left
- points_dst: torch.Tensor = torch.tensor(
+ points_dst: Tensor = tensor(
[[[0, 0], [dst_w - 1, 0], [dst_w - 1, dst_h - 1], [0, dst_h - 1]]], device=device, dtype=torch.long
).expand(batch_size, -1, -1)
- _input_size = torch.tensor((height, width), device=device, dtype=torch.long).expand(batch_size, -1)
- _output_size = torch.tensor(size, device=device, dtype=torch.long).expand(batch_size, -1)
+ _input_size = tensor((height, width), device=device, dtype=torch.long).expand(batch_size, -1)
+ _output_size = tensor(size, device=device, dtype=torch.long).expand(batch_size, -1)
return dict(src=points_src, dst=points_dst, input_size=_input_size, output_size=_output_size)
diff --git a/kornia/augmentation/random_generator/_2d/motion_blur.py b/kornia/augmentation/random_generator/_2d/motion_blur.py
index a218a47de..5d013c112 100644
--- a/kornia/augmentation/random_generator/_2d/motion_blur.py
+++ b/kornia/augmentation/random_generator/_2d/motion_blur.py
@@ -11,6 +11,7 @@ from kornia.augmentation.utils import (
_joint_range_check,
_range_bound,
)
+from kornia.core import Tensor, tensor
from kornia.utils.helpers import _deprecated, _extract_device_dtype
@@ -32,9 +33,9 @@ class MotionBlurGenerator(RandomGeneratorBase):
Returns:
A dict of parameters to be passed for transformation.
- - ksize_factor (torch.Tensor): element-wise kernel size factors with a shape of (B,).
- - angle_factor (torch.Tensor): element-wise angle factors with a shape of (B,).
- - direction_factor (torch.Tensor): element-wise direction factors with a shape of (B,).
+ - ksize_factor (Tensor): element-wise kernel size factors with a shape of (B,).
+ - angle_factor (Tensor): element-wise angle factors with a shape of (B,).
+ - direction_factor (Tensor): element-wise direction factors with a shape of (B,).
Note:
The generated random numbers are not reproducible across different devices and dtypes. By default,
@@ -45,8 +46,8 @@ class MotionBlurGenerator(RandomGeneratorBase):
def __init__(
self,
kernel_size: Union[int, Tuple[int, int]],
- angle: Union[torch.Tensor, float, Tuple[float, float]],
- direction: Union[torch.Tensor, float, Tuple[float, float]],
+ angle: Union[Tensor, float, Tuple[float, float]],
+ direction: Union[Tensor, float, Tuple[float, float]],
) -> None:
super().__init__()
self.kernel_size = kernel_size
@@ -75,7 +76,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, torch.Tensor]: # type:ignore
+ def forward(self, batch_shape: torch.Size, 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))
@@ -95,19 +96,19 @@ class MotionBlurGenerator(RandomGeneratorBase):
def random_motion_blur_generator(
batch_size: int,
kernel_size: Union[int, Tuple[int, int]],
- angle: torch.Tensor,
- direction: torch.Tensor,
+ angle: Tensor,
+ direction: Tensor,
same_on_batch: bool = False,
device: torch.device = torch.device('cpu'),
dtype: torch.dtype = torch.float32,
-) -> Dict[str, torch.Tensor]:
+) -> Dict[str, Tensor]:
r"""Get parameters for motion blur.
Args:
batch_size (int): the tensor batch size.
kernel_size (int or (int, int)): motion kernel size (odd and positive) or range.
- angle (torch.Tensor): angle of the motion blur in degrees (anti-clockwise rotation).
- direction (torch.Tensor): forward/backward direction of the motion blur.
+ angle (Tensor): angle of the motion blur in degrees (anti-clockwise rotation).
+ direction (Tensor): forward/backward direction of the motion blur.
Lower values towards -1.0 will point the motion blur towards the back (with
angle provided via angle), while higher values towards 1.0 will point the motion
blur forward. A value of 0.0 leads to a uniformly (but still angled) motion blur.
@@ -116,10 +117,10 @@ def random_motion_blur_generator(
dtype (torch.dtype): the data type of the generated random numbers. Default: float32.
Returns:
- params Dict[str, torch.Tensor]: parameters to be passed for transformation.
- - ksize_factor (torch.Tensor): element-wise kernel size factors with a shape of (B,).
- - angle_factor (torch.Tensor): element-wise angle factors with a shape of (B,).
- - direction_factor (torch.Tensor): element-wise direction factors with a shape of (B,).
+ params Dict[str, Tensor]: parameters to be passed for transformation.
+ - ksize_factor (Tensor): element-wise kernel size factors with a shape of (B,).
+ - angle_factor (Tensor): element-wise angle factors with a shape of (B,).
+ - direction_factor (Tensor): element-wise direction factors with a shape of (B,).
Note:
The generated random numbers are not reproducible across different devices and dtypes.
@@ -133,7 +134,7 @@ def random_motion_blur_generator(
if isinstance(kernel_size, int):
if not (kernel_size >= 3 and kernel_size % 2 == 1):
raise AssertionError(f"`kernel_size` must be odd and greater than 3. Got {kernel_size}.")
- ksize_factor = torch.tensor([kernel_size] * batch_size, device=device, dtype=dtype)
+ ksize_factor = tensor([kernel_size] * batch_size, device=device, dtype=dtype)
elif isinstance(kernel_size, tuple):
# kernel_size is fixed across the batch
if len(kernel_size) != 2:
diff --git a/kornia/augmentation/random_generator/_2d/perspective.py b/kornia/augmentation/random_generator/_2d/perspective.py
index d61880204..29841e6b6 100644
--- a/kornia/augmentation/random_generator/_2d/perspective.py
+++ b/kornia/augmentation/random_generator/_2d/perspective.py
@@ -5,6 +5,7 @@ from torch.distributions import Uniform
from kornia.augmentation.random_generator.base import RandomGeneratorBase
from kornia.augmentation.utils import _adapted_rsampling, _adapted_uniform, _common_param_check
+from kornia.core import Tensor, tensor
from kornia.utils.helpers import _deprecated, _extract_device_dtype
@@ -20,8 +21,8 @@ class PerspectiveGenerator(RandomGeneratorBase):
Returns:
A dict of parameters to be passed for transformation.
- - start_points (torch.Tensor): element-wise perspective source areas with a shape of (B, 4, 2).
- - end_points (torch.Tensor): element-wise perspective target areas with a shape of (B, 4, 2).
+ - start_points (Tensor): element-wise perspective source areas with a shape of (B, 4, 2).
+ - end_points (Tensor): element-wise perspective target areas with a shape of (B, 4, 2).
Note:
The generated random numbers are not reproducible across different devices and dtypes. By default,
@@ -29,7 +30,7 @@ class PerspectiveGenerator(RandomGeneratorBase):
``self.set_rng_device_and_dtype(device="cuda", dtype=torch.float64)``.
"""
- def __init__(self, distortion_scale: Union[torch.Tensor, float] = 0.5, sampling_method: str = "basic") -> None:
+ def __init__(self, distortion_scale: Union[Tensor, float] = 0.5, sampling_method: str = "basic") -> None:
super().__init__()
if sampling_method not in ("basic", "area_preserving"):
raise NotImplementedError(f"Sampling method {sampling_method} not yet implemented.")
@@ -45,12 +46,10 @@ class PerspectiveGenerator(RandomGeneratorBase):
if not (self._distortion_scale.dim() == 0 and 0 <= self._distortion_scale <= 1):
raise AssertionError(f"'distortion_scale' must be a scalar within [0, 1]. Got {self._distortion_scale}.")
self.rand_val_sampler = Uniform(
- torch.tensor(0, device=device, dtype=dtype),
- torch.tensor(1, device=device, dtype=dtype),
- validate_args=False,
+ 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, torch.Tensor]: # type:ignore
+ def forward(self, batch_shape: torch.Size, same_on_batch: bool = False) -> Dict[str, Tensor]:
batch_size = batch_shape[0]
height = batch_shape[-2]
width = batch_shape[-1]
@@ -60,7 +59,7 @@ class PerspectiveGenerator(RandomGeneratorBase):
if not (type(height) is int and height > 0 and type(width) is int and width > 0):
raise AssertionError(f"'height' and 'width' must be integers. Got {height}, {width}.")
- start_points: torch.Tensor = torch.tensor(
+ start_points: Tensor = tensor(
[[[0.0, 0], [width - 1, 0], [width - 1, height - 1], [0, height - 1]]], device=_device, dtype=_dtype
).expand(batch_size, -1, -1)
@@ -71,11 +70,11 @@ class PerspectiveGenerator(RandomGeneratorBase):
factor = torch.stack([fx, fy], dim=0).view(-1, 1, 2).to(device=_device, dtype=_dtype)
# TODO: This line somehow breaks the gradcheck
- rand_val: torch.Tensor = _adapted_rsampling(start_points.shape, self.rand_val_sampler, same_on_batch).to(
+ rand_val: Tensor = _adapted_rsampling(start_points.shape, self.rand_val_sampler, same_on_batch).to(
device=_device, dtype=_dtype
)
if self.sampling_method == "basic":
- pts_norm = torch.tensor([[[1, 1], [-1, 1], [-1, -1], [1, -1]]], device=_device, dtype=_dtype)
+ pts_norm = tensor([[[1, 1], [-1, 1], [-1, -1], [1, -1]]], device=_device, dtype=_dtype)
offset = factor * rand_val * pts_norm
elif self.sampling_method == "area_preserving":
offset = 2 * factor * (rand_val - 0.5)
@@ -90,26 +89,26 @@ def random_perspective_generator(
batch_size: int,
height: int,
width: int,
- distortion_scale: torch.Tensor,
+ distortion_scale: Tensor,
same_on_batch: bool = False,
device: torch.device = torch.device('cpu'),
dtype: torch.dtype = torch.float32,
-) -> Dict[str, torch.Tensor]:
+) -> Dict[str, Tensor]:
r"""Get parameters for ``perspective`` for a random perspective transform.
Args:
batch_size (int): the tensor batch size.
height (int) : height of the image.
width (int): width of the image.
- distortion_scale (torch.Tensor): it controls the degree of distortion and ranges from 0 to 1.
+ distortion_scale (Tensor): it controls the degree of distortion and ranges from 0 to 1.
same_on_batch (bool): apply the same transformation across the batch. Default: False.
device (torch.device): the device on which the random numbers will be generated. Default: cpu.
dtype (torch.dtype): the data type of the generated random numbers. Default: float32.
Returns:
- params Dict[str, torch.Tensor]: parameters to be passed for transformation.
- - start_points (torch.Tensor): element-wise perspective source areas with a shape of (B, 4, 2).
- - end_points (torch.Tensor): element-wise perspective target areas with a shape of (B, 4, 2).
+ params Dict[str, Tensor]: parameters to be passed for transformation.
+ - start_points (Tensor): element-wise perspective source areas with a shape of (B, 4, 2).
+ - end_points (Tensor): element-wise perspective target areas with a shape of (B, 4, 2).
Note:
The generated random numbers are not reproducible across different devices and dtypes.
@@ -120,7 +119,7 @@ def random_perspective_generator(
if not (type(height) is int and height > 0 and type(width) is int and width > 0):
raise AssertionError(f"'height' and 'width' must be integers. Got {height}, {width}.")
- start_points: torch.Tensor = torch.tensor(
+ start_points: Tensor = tensor(
[[[0.0, 0], [width - 1, 0], [width - 1, height - 1], [0, height - 1]]],
device=distortion_scale.device,
dtype=distortion_scale.dtype,
@@ -133,14 +132,11 @@ def random_perspective_generator(
factor = torch.stack([fx, fy], dim=0).view(-1, 1, 2)
# TODO: This line somehow breaks the gradcheck
- rand_val: torch.Tensor = _adapted_uniform(
- start_points.shape,
- torch.tensor(0, device=device, dtype=dtype),
- torch.tensor(1, device=device, dtype=dtype),
- same_on_batch,
+ rand_val: Tensor = _adapted_uniform(
+ start_points.shape, tensor(0, device=device, dtype=dtype), tensor(1, device=device, dtype=dtype), same_on_batch
).to(device=distortion_scale.device, dtype=distortion_scale.dtype)
- pts_norm = torch.tensor(
+ pts_norm = tensor(
[[[1, 1], [-1, 1], [-1, -1], [1, -1]]], device=distortion_scale.device, dtype=distortion_scale.dtype
)
end_points = start_points + factor * rand_val * pts_norm
diff --git a/kornia/augmentation/random_generator/_2d/plain_uniform.py b/kornia/augmentation/random_generator/_2d/plain_uniform.py
index 6f380b27e..e773e5454 100644
--- a/kornia/augmentation/random_generator/_2d/plain_uniform.py
+++ b/kornia/augmentation/random_generator/_2d/plain_uniform.py
@@ -5,6 +5,7 @@ from torch.distributions import Distribution, Uniform
from kornia.augmentation.random_generator.base import RandomGeneratorBase
from kornia.augmentation.utils import _adapted_rsampling, _common_param_check, _range_bound
+from kornia.core import Tensor, as_tensor
from kornia.utils.helpers import _extract_device_dtype
# factor, name, center, range
@@ -49,7 +50,7 @@ class PlainUniformGenerator(RandomGeneratorBase):
names.append(name)
if isinstance(factor, torch.nn.Parameter):
self.register_parameter(name, factor)
- elif isinstance(factor, torch.Tensor):
+ elif isinstance(factor, Tensor):
self.register_buffer(name, factor)
def __repr__(self) -> str:
@@ -60,14 +61,14 @@ class PlainUniformGenerator(RandomGeneratorBase):
self.sampler_dict: Dict[str, Distribution] = {}
for factor, name, center, bound in self.samplers:
if center is None and bound is None:
- factor = torch.as_tensor(factor, device=device, dtype=dtype)
+ factor = as_tensor(factor, device=device, dtype=dtype)
elif center is None or bound is None:
raise ValueError(f"`center` and `bound` should be both None or provided. Got {center} and {bound}.")
else:
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, torch.Tensor]: # type:ignore
+ def forward(self, batch_shape: torch.Size, 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/posterize.py b/kornia/augmentation/random_generator/_2d/posterize.py
index 9f2bd5833..8a3e037e0 100644
--- a/kornia/augmentation/random_generator/_2d/posterize.py
+++ b/kornia/augmentation/random_generator/_2d/posterize.py
@@ -5,6 +5,7 @@ from torch.distributions import Uniform
from kornia.augmentation.random_generator.base import RandomGeneratorBase
from kornia.augmentation.utils import _adapted_rsampling, _adapted_uniform, _common_param_check, _joint_range_check
+from kornia.core import Tensor, as_tensor, tensor
from kornia.utils.helpers import _deprecated, _extract_device_dtype
@@ -18,7 +19,7 @@ class PosterizeGenerator(RandomGeneratorBase):
Returns:
A dict of parameters to be passed for transformation.
- - bits_factor (torch.Tensor): element-wise bit factors with a shape of (B,).
+ - bits_factor (Tensor): element-wise bit factors with a shape of (B,).
Note:
The generated random numbers are not reproducible across different devices and dtypes. By default,
@@ -26,7 +27,7 @@ class PosterizeGenerator(RandomGeneratorBase):
``self.set_rng_device_and_dtype(device="cuda", dtype=torch.float64)``.
"""
- def __init__(self, bits: Union[int, Tuple[int, int], torch.Tensor]) -> None:
+ def __init__(self, bits: Union[int, Tuple[int, int], Tensor]) -> None:
super().__init__()
self.bits = bits
@@ -35,7 +36,7 @@ class PosterizeGenerator(RandomGeneratorBase):
return repr
def make_samplers(self, device: torch.device, dtype: torch.dtype) -> None:
- bits = torch.as_tensor(self.bits, device=device, dtype=dtype)
+ bits = as_tensor(self.bits, device=device, dtype=dtype)
if len(bits.size()) == 0:
bits = bits.repeat(2)
bits[1] = 8
@@ -44,10 +45,10 @@ 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, torch.Tensor]: # type:ignore
+ def forward(self, batch_shape: torch.Size, 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 if isinstance(self.bits, torch.Tensor) else None])
+ _device, _ = _extract_device_dtype([self.bits if isinstance(self.bits, Tensor) else None])
bits_factor = _adapted_rsampling((batch_size,), self.bit_sampler, same_on_batch)
return dict(bits_factor=bits_factor.to(device=_device, dtype=torch.int32))
@@ -55,11 +56,11 @@ class PosterizeGenerator(RandomGeneratorBase):
@_deprecated()
def random_posterize_generator(
batch_size: int,
- bits: torch.Tensor = torch.tensor([3, 5]),
+ bits: Tensor = tensor([3, 5]),
same_on_batch: bool = False,
device: torch.device = torch.device('cpu'),
dtype: torch.dtype = torch.float32,
-) -> Dict[str, torch.Tensor]:
+) -> Dict[str, Tensor]:
r"""Generate random posterize parameters for a batch of images.
Args:
@@ -70,8 +71,8 @@ def random_posterize_generator(
dtype (torch.dtype): the data type of the generated random numbers. Default: float32.
Returns:
- params Dict[str, torch.Tensor]: parameters to be passed for transformation.
- - bits_factor (torch.Tensor): element-wise bit factors with a shape of (B,).
+ params Dict[str, Tensor]: parameters to be passed for transformation.
+ - bits_factor (Tensor): element-wise bit factors with a shape of (B,).
Note:
The generated random numbers are not reproducible across different devices and dtypes.
diff --git a/kornia/augmentation/random_generator/_2d/probability.py b/kornia/augmentation/random_generator/_2d/probability.py
index 74057c7a0..2e272bb28 100644
--- a/kornia/augmentation/random_generator/_2d/probability.py
+++ b/kornia/augmentation/random_generator/_2d/probability.py
@@ -5,6 +5,7 @@ from torch.distributions import Bernoulli
from kornia.augmentation.random_generator.base import RandomGeneratorBase
from kornia.augmentation.utils import _adapted_sampling, _common_param_check
+from kornia.core import Tensor, tensor
class ProbabilityGenerator(RandomGeneratorBase):
@@ -15,7 +16,7 @@ class ProbabilityGenerator(RandomGeneratorBase):
Returns:
A dict of parameters to be passed for transformation.
- - probs (torch.Tensor): element-wise probabilities with a shape of (B,).
+ - probs (Tensor): element-wise probabilities with a shape of (B,).
Note:
The generated random numbers are not reproducible across different devices and dtypes. By default,
@@ -35,9 +36,9 @@ 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, torch.Tensor]: # type:ignore
+ def forward(self, batch_shape: torch.Size, same_on_batch: bool = False) -> Dict[str, Tensor]:
batch_size = batch_shape[0]
- probs_mask: torch.Tensor = _adapted_sampling((batch_size,), self.sampler, same_on_batch).bool()
+ probs_mask: Tensor = _adapted_sampling((batch_size,), self.sampler, same_on_batch).bool()
return dict(probs=probs_mask)
@@ -47,7 +48,7 @@ def random_prob_generator(
same_on_batch: bool = False,
device: torch.device = torch.device('cpu'),
dtype: torch.dtype = torch.float32,
-) -> torch.Tensor:
+) -> Tensor:
r"""Generate random probabilities for a batch of inputs.
Args:
@@ -58,8 +59,8 @@ def random_prob_generator(
dtype (torch.dtype): the data type of the generated random numbers. Default: float32.
Returns:
- torch.Tensor: parameters to be passed for transformation.
- - probs (torch.Tensor): element-wise probabilities with a shape of (B,).
+ Tensor: parameters to be passed for transformation.
+ - probs (Tensor): element-wise probabilities with a shape of (B,).
Note:
The generated random numbers are not reproducible across different devices and dtypes.
@@ -68,7 +69,7 @@ def random_prob_generator(
if not isinstance(p, (int, float)) or p > 1 or p < 0:
raise TypeError(f"The probability should be a float number within [0, 1]. Got {type(p)}.")
- _bernoulli = Bernoulli(torch.tensor(float(p), device=device, dtype=dtype))
- probs_mask: torch.Tensor = _adapted_sampling((batch_size,), _bernoulli, same_on_batch).bool()
+ _bernoulli = Bernoulli(tensor(float(p), device=device, dtype=dtype))
+ probs_mask: Tensor = _adapted_sampling((batch_size,), _bernoulli, same_on_batch).bool()
return probs_mask
diff --git a/kornia/augmentation/random_generator/_2d/rectangle_earase.py b/kornia/augmentation/random_generator/_2d/rectangle_earase.py
index d96ffd30b..988544220 100644
--- a/kornia/augmentation/random_generator/_2d/rectangle_earase.py
+++ b/kornia/augmentation/random_generator/_2d/rectangle_earase.py
@@ -5,6 +5,7 @@ from torch.distributions import Uniform
from kornia.augmentation.random_generator.base import RandomGeneratorBase
from kornia.augmentation.utils import _adapted_rsampling, _adapted_uniform, _common_param_check, _joint_range_check
+from kornia.core import Tensor, as_tensor, tensor, where
from kornia.utils.helpers import _deprecated, _extract_device_dtype
@@ -12,17 +13,17 @@ class RectangleEraseGenerator(RandomGeneratorBase):
r"""Get parameters for ```erasing``` transformation for erasing transform.
Args:
- scale (torch.Tensor): range of size of the origin size cropped. Shape (2).
- ratio (torch.Tensor): range of aspect ratio of the origin aspect ratio cropped. Shape (2).
+ scale (Tensor): range of size of the origin size cropped. Shape (2).
+ ratio (Tensor): range of aspect ratio of the origin aspect ratio cropped. Shape (2).
value (float): value to be filled in the erased area.
Returns:
A dict of parameters to be passed for transformation.
- - widths (torch.Tensor): element-wise erasing widths with a shape of (B,).
- - heights (torch.Tensor): element-wise erasing heights with a shape of (B,).
- - xs (torch.Tensor): element-wise erasing x coordinates with a shape of (B,).
- - ys (torch.Tensor): element-wise erasing y coordinates with a shape of (B,).
- - values (torch.Tensor): element-wise filling values with a shape of (B,).
+ - widths (Tensor): element-wise erasing widths with a shape of (B,).
+ - heights (Tensor): element-wise erasing heights with a shape of (B,).
+ - xs (Tensor): element-wise erasing x coordinates with a shape of (B,).
+ - ys (Tensor): element-wise erasing y coordinates with a shape of (B,).
+ - values (Tensor): element-wise filling values with a shape of (B,).
Note:
The generated random numbers are not reproducible across different devices and dtypes. By default,
@@ -32,8 +33,8 @@ class RectangleEraseGenerator(RandomGeneratorBase):
def __init__(
self,
- scale: Union[torch.Tensor, Tuple[float, float]] = (0.02, 0.33),
- ratio: Union[torch.Tensor, Tuple[float, float]] = (0.3, 3.3),
+ scale: Union[Tensor, Tuple[float, float]] = (0.02, 0.33),
+ ratio: Union[Tensor, Tuple[float, float]] = (0.3, 3.3),
value: float = 0.0,
) -> None:
super().__init__()
@@ -46,8 +47,8 @@ class RectangleEraseGenerator(RandomGeneratorBase):
return repr
def make_samplers(self, device: torch.device, dtype: torch.dtype) -> None:
- scale = torch.as_tensor(self.scale, device=device, dtype=dtype)
- ratio = torch.as_tensor(self.ratio, device=device, dtype=dtype)
+ scale = as_tensor(self.scale, device=device, dtype=dtype)
+ ratio = as_tensor(self.ratio, device=device, dtype=dtype)
if not (isinstance(self.value, (int, float)) and self.value >= 0 and self.value <= 1):
raise AssertionError(f"'value' must be a number between 0 - 1. Got {self.value}.")
@@ -60,19 +61,15 @@ class RectangleEraseGenerator(RandomGeneratorBase):
self.ratio_sampler1 = Uniform(ratio[0], 1, validate_args=False)
self.ratio_sampler2 = Uniform(1, ratio[1], validate_args=False)
self.index_sampler = Uniform(
- torch.tensor(0, device=device, dtype=dtype),
- torch.tensor(1, device=device, dtype=dtype),
- validate_args=False,
+ tensor(0, device=device, dtype=dtype), tensor(1, device=device, dtype=dtype), validate_args=False
)
else:
self.ratio_sampler = Uniform(ratio[0], ratio[1], validate_args=False)
self.uniform_sampler = Uniform(
- torch.tensor(0, device=device, dtype=dtype),
- torch.tensor(1, device=device, dtype=dtype),
- validate_args=False,
+ 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, torch.Tensor]: # type:ignore
+ def forward(self, batch_shape: torch.Size, same_on_batch: bool = False) -> Dict[str, Tensor]:
batch_size = batch_shape[0]
height = batch_shape[-2]
width = batch_shape[-1]
@@ -96,7 +93,7 @@ class RectangleEraseGenerator(RandomGeneratorBase):
)
else:
rand_idxs = torch.round(_adapted_rsampling((batch_size,), self.index_sampler, same_on_batch)).bool()
- aspect_ratios = torch.where(rand_idxs, aspect_ratios1, aspect_ratios2)
+ aspect_ratios = where(rand_idxs, aspect_ratios1, aspect_ratios2)
else:
aspect_ratios = _adapted_rsampling((batch_size,), self.ratio_sampler, same_on_batch)
@@ -105,16 +102,16 @@ class RectangleEraseGenerator(RandomGeneratorBase):
# based on target areas and aspect ratios, rectangle params are computed
heights = torch.min(
torch.max(
- torch.round((target_areas * aspect_ratios) ** (1 / 2)), torch.tensor(1.0, device=_device, dtype=_dtype)
+ torch.round((target_areas * aspect_ratios) ** (1 / 2)), tensor(1.0, device=_device, dtype=_dtype)
),
- torch.tensor(height, device=_device, dtype=_dtype),
+ tensor(height, device=_device, dtype=_dtype),
)
widths = torch.min(
torch.max(
- torch.round((target_areas / aspect_ratios) ** (1 / 2)), torch.tensor(1.0, device=_device, dtype=_dtype)
+ torch.round((target_areas / aspect_ratios) ** (1 / 2)), tensor(1.0, device=_device, dtype=_dtype)
),
- torch.tensor(width, device=_device, dtype=_dtype),
+ tensor(width, device=_device, dtype=_dtype),
)
xs_ratio = _adapted_rsampling((batch_size,), self.uniform_sampler, same_on_batch).to(
@@ -132,7 +129,7 @@ class RectangleEraseGenerator(RandomGeneratorBase):
heights=heights.floor(),
xs=xs.floor(),
ys=ys.floor(),
- values=torch.tensor([self.value] * batch_size, device=_device, dtype=_dtype),
+ values=tensor([self.value] * batch_size, device=_device, dtype=_dtype),
)
@@ -141,33 +138,33 @@ def random_rectangles_params_generator(
batch_size: int,
height: int,
width: int,
- scale: torch.Tensor,
- ratio: torch.Tensor,
+ scale: Tensor,
+ ratio: Tensor,
value: float = 0.0,
same_on_batch: bool = False,
device: torch.device = torch.device('cpu'),
dtype: torch.dtype = torch.float32,
-) -> Dict[str, torch.Tensor]:
+) -> Dict[str, Tensor]:
r"""Get parameters for ```erasing``` transformation for erasing transform.
Args:
batch_size (int): the tensor batch size.
height (int) : height of the image.
width (int): width of the image.
- scale (torch.Tensor): range of size of the origin size cropped. Shape (2).
- ratio (torch.Tensor): range of aspect ratio of the origin aspect ratio cropped. Shape (2).
+ scale (Tensor): range of size of the origin size cropped. Shape (2).
+ ratio (Tensor): range of aspect ratio of the origin aspect ratio cropped. Shape (2).
value (float): value to be filled in the erased area.
same_on_batch (bool): apply the same transformation across the batch. Default: False.
device (torch.device): the device on which the random numbers will be generated. Default: cpu.
dtype (torch.dtype): the data type of the generated random numbers. Default: float32.
Returns:
- params Dict[str, torch.Tensor]: parameters to be passed for transformation.
- - widths (torch.Tensor): element-wise erasing widths with a shape of (B,).
- - heights (torch.Tensor): element-wise erasing heights with a shape of (B,).
- - xs (torch.Tensor): element-wise erasing x coordinates with a shape of (B,).
- - ys (torch.Tensor): element-wise erasing y coordinates with a shape of (B,).
- - values (torch.Tensor): element-wise filling values with a shape of (B,).
+ params Dict[str, Tensor]: parameters to be passed for transformation.
+ - widths (Tensor): element-wise erasing widths with a shape of (B,).
+ - heights (Tensor): element-wise erasing heights with a shape of (B,).
+ - xs (Tensor): element-wise erasing x coordinates with a shape of (B,).
+ - ys (Tensor): element-wise erasing y coordinates with a shape of (B,).
+ - values (Tensor): element-wise filling values with a shape of (B,).
Note:
The generated random numbers are not reproducible across different devices and dtypes.
@@ -200,8 +197,8 @@ def random_rectangles_params_generator(
torch.round(
_adapted_uniform(
(1,),
- torch.tensor(0, device=device, dtype=dtype),
- torch.tensor(1, device=device, dtype=dtype),
+ tensor(0, device=device, dtype=dtype),
+ tensor(1, device=device, dtype=dtype),
same_on_batch,
)
)
@@ -212,12 +209,12 @@ def random_rectangles_params_generator(
rand_idxs = torch.round(
_adapted_uniform(
(batch_size,),
- torch.tensor(0, device=device, dtype=dtype),
- torch.tensor(1, device=device, dtype=dtype),
+ tensor(0, device=device, dtype=dtype),
+ tensor(1, device=device, dtype=dtype),
same_on_batch,
)
).bool()
- aspect_ratios = torch.where(rand_idxs, aspect_ratios1, aspect_ratios2)
+ aspect_ratios = where(rand_idxs, aspect_ratios1, aspect_ratios2)
else:
aspect_ratios = _adapted_uniform(
(batch_size,),
@@ -228,39 +225,29 @@ def random_rectangles_params_generator(
# based on target areas and aspect ratios, rectangle params are computed
heights = torch.min(
- torch.max(
- torch.round((target_areas * aspect_ratios) ** (1 / 2)), torch.tensor(1.0, device=device, dtype=dtype)
- ),
- torch.tensor(height, device=device, dtype=dtype),
+ torch.max(torch.round((target_areas * aspect_ratios) ** (1 / 2)), tensor(1.0, device=device, dtype=dtype)),
+ tensor(height, device=device, dtype=dtype),
)
widths = torch.min(
- torch.max(
- torch.round((target_areas / aspect_ratios) ** (1 / 2)), torch.tensor(1.0, device=device, dtype=dtype)
- ),
- torch.tensor(width, device=device, dtype=dtype),
+ torch.max(torch.round((target_areas / aspect_ratios) ** (1 / 2)), tensor(1.0, device=device, dtype=dtype)),
+ tensor(width, device=device, dtype=dtype),
)
xs_ratio = _adapted_uniform(
- (batch_size,),
- torch.tensor(0, device=device, dtype=dtype),
- torch.tensor(1, device=device, dtype=dtype),
- same_on_batch,
+ (batch_size,), tensor(0, device=device, dtype=dtype), tensor(1, device=device, dtype=dtype), same_on_batch
)
ys_ratio = _adapted_uniform(
- (batch_size,),
- torch.tensor(0, device=device, dtype=dtype),
- torch.tensor(1, device=device, dtype=dtype),
- same_on_batch,
+ (batch_size,), tensor(0, device=device, dtype=dtype), tensor(1, device=device, dtype=dtype), same_on_batch
)
- xs = xs_ratio * (torch.tensor(width, device=device, dtype=dtype) - widths + 1)
- ys = ys_ratio * (torch.tensor(height, device=device, dtype=dtype) - heights + 1)
+ xs = xs_ratio * (tensor(width, device=device, dtype=dtype) - widths + 1)
+ ys = ys_ratio * (tensor(height, device=device, dtype=dtype) - heights + 1)
return dict(
widths=widths.floor().to(device=_device, dtype=_dtype),
heights=heights.floor().to(device=_device, dtype=_dtype),
xs=xs.floor().to(device=_device, dtype=_dtype),
ys=ys.floor().to(device=_device, dtype=_dtype),
- values=torch.tensor([value] * batch_size, device=_device, dtype=_dtype),
+ values=tensor([value] * batch_size, device=_device, dtype=_dtype),
)
diff --git a/kornia/augmentation/random_generator/_3d/crop.py b/kornia/augmentation/random_generator/_3d/crop.py
index ecef4cbb8..4e43ccd90 100644
--- a/kornia/augmentation/random_generator/_3d/crop.py
+++ b/kornia/augmentation/random_generator/_3d/crop.py
@@ -5,6 +5,7 @@ from torch.distributions import Uniform
from kornia.augmentation.random_generator.base import RandomGeneratorBase
from kornia.augmentation.utils import _adapted_rsampling, _adapted_uniform, _common_param_check
+from kornia.core import Device, Tensor, tensor, zeros
from kornia.geometry.bbox import bbox_generator3d
from kornia.utils.helpers import _deprecated, _extract_device_dtype
@@ -19,8 +20,8 @@ class CropGenerator3D(RandomGeneratorBase):
Returns:
A dict of parameters to be passed for transformation.
- - src (torch.Tensor): cropping bounding boxes with a shape of (B, 8, 3).
- - dst (torch.Tensor): output bounding boxes with a shape (B, 8, 3).
+ - src (Tensor): cropping bounding boxes with a shape of (B, 8, 3).
+ - dst (Tensor): output bounding boxes with a shape (B, 8, 3).
Note:
The generated random numbers are not reproducible across different devices and dtypes. By default,
@@ -29,7 +30,7 @@ class CropGenerator3D(RandomGeneratorBase):
"""
def __init__(
- self, size: Union[Tuple[int, int, int], torch.Tensor], resize_to: Optional[Tuple[int, int, int]] = None
+ self, size: Union[Tuple[int, int, int], Tensor], resize_to: Optional[Tuple[int, int, int]] = None
) -> None:
super().__init__()
self.size = size
@@ -42,17 +43,15 @@ class CropGenerator3D(RandomGeneratorBase):
return repr
def make_samplers(self, device: torch.device, dtype: torch.dtype) -> None:
- self.rand_sampler = Uniform(
- torch.tensor(0.0, device=device, dtype=dtype), torch.tensor(1.0, device=device, dtype=dtype)
- )
+ 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, torch.Tensor]: # type:ignore
+ def forward(self, batch_shape: torch.Size, 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, torch.Tensor) else None])
+ _device, _dtype = _extract_device_dtype([self.size if isinstance(self.size, Tensor) else None])
- if not isinstance(self.size, torch.Tensor):
- size = torch.tensor(self.size, device=_device, dtype=_dtype).repeat(batch_size, 1)
+ if not isinstance(self.size, Tensor):
+ size = tensor(self.size, device=_device, dtype=_dtype).repeat(batch_size, 1)
else:
size = self.size.to(device=_device, dtype=_dtype)
if size.shape != torch.Size([batch_size, 3]):
@@ -81,8 +80,7 @@ class CropGenerator3D(RandomGeneratorBase):
if batch_size == 0:
return dict(
- src=torch.zeros([0, 8, 3], device=_device, dtype=_dtype),
- dst=torch.zeros([0, 8, 3], device=_device, dtype=_dtype),
+ src=zeros([0, 8, 3], device=_device, dtype=_dtype), dst=zeros([0, 8, 3], device=_device, dtype=_dtype)
)
x_start = _adapted_rsampling((batch_size,), self.rand_sampler, same_on_batch).to(device=_device, dtype=_dtype)
@@ -99,9 +97,9 @@ class CropGenerator3D(RandomGeneratorBase):
if self.resize_to is None:
crop_dst = bbox_generator3d(
- torch.tensor([0] * batch_size, device=_device, dtype=_dtype),
- torch.tensor([0] * batch_size, device=_device, dtype=_dtype),
- torch.tensor([0] * batch_size, device=_device, dtype=_dtype),
+ tensor([0] * batch_size, device=_device, dtype=_dtype),
+ tensor([0] * batch_size, device=_device, dtype=_dtype),
+ tensor([0] * batch_size, device=_device, dtype=_dtype),
size[:, 2] - 1,
size[:, 1] - 1,
size[:, 0] - 1,
@@ -117,7 +115,7 @@ class CropGenerator3D(RandomGeneratorBase):
and self.resize_to[2] > 0
):
raise AssertionError(f"`resize_to` must be a tuple of 3 positive integers. Got {self.resize_to}.")
- crop_dst = torch.tensor(
+ crop_dst = tensor(
[
[
[0, 0, 0],
@@ -143,8 +141,8 @@ def center_crop_generator3d(
height: int,
width: int,
size: Tuple[int, int, int],
- device: torch.device = torch.device('cpu'),
-) -> Dict[str, torch.Tensor]:
+ device: Device = torch.device('cpu'),
+) -> Dict[str, Tensor]:
r"""Get parameters for ```center_crop3d``` transformation for center crop transform.
Args:
@@ -153,12 +151,12 @@ def center_crop_generator3d(
height (int) : height of the image.
width (int): width of the image.
size (tuple): Desired output size of the crop, like (d, h, w).
- device (torch.device): the device on which the random numbers will be generated. Default: cpu.
+ device (Device): the device on which the random numbers will be generated. Default: cpu.
Returns:
- params Dict[str, torch.Tensor]: parameters to be passed for transformation.
- - src (torch.Tensor): cropping bounding boxes with a shape of (B, 8, 3).
- - dst (torch.Tensor): output bounding boxes with a shape (B, 8, 3).
+ params Dict[str, Tensor]: parameters to be passed for transformation.
+ - src (Tensor): cropping bounding boxes with a shape of (B, 8, 3).
+ - dst (Tensor): output bounding boxes with a shape (B, 8, 3).
Note:
No random number will be generated.
@@ -173,7 +171,7 @@ def center_crop_generator3d(
raise AssertionError(f"Crop size must be smaller than input size. Got ({depth}, {height}, {width}) and {size}.")
if batch_size == 0:
- return dict(src=torch.zeros([0, 8, 3]), dst=torch.zeros([0, 8, 3]))
+ return dict(src=zeros([0, 8, 3]), dst=zeros([0, 8, 3]))
# unpack input sizes
dst_d, dst_h, dst_w = size
src_d, src_h, src_w = (depth, height, width)
@@ -198,7 +196,7 @@ def center_crop_generator3d(
# top-left-back, top-right-back, bottom-right-back, bottom-left-back
# Note: DeprecationWarning: an integer is required (got type float).
# Implicit conversion to integers using __int__ is deprecated, and may be removed in a future version of Python.
- points_src: torch.Tensor = torch.tensor(
+ points_src: Tensor = tensor(
[
[
[int(start_x), int(start_y), int(start_z)],
@@ -218,7 +216,7 @@ def center_crop_generator3d(
# [x, y, z] destination
# top-left-front, top-right-front, bottom-right-front, bottom-left-front
# top-left-back, top-right-back, bottom-right-back, bottom-left-back
- points_dst: torch.Tensor = torch.tensor(
+ points_dst: Tensor = tensor(
[
[
[0, 0, 0],
@@ -241,12 +239,12 @@ def center_crop_generator3d(
def random_crop_generator3d(
batch_size: int,
input_size: Tuple[int, int, int],
- size: Union[Tuple[int, int, int], torch.Tensor],
+ size: Union[Tuple[int, int, int], Tensor],
resize_to: Optional[Tuple[int, int, int]] = None,
same_on_batch: bool = False,
device: torch.device = torch.device('cpu'),
dtype: torch.dtype = torch.float32,
-) -> Dict[str, torch.Tensor]:
+) -> Dict[str, Tensor]:
r"""Get parameters for ```crop``` transformation for crop transform.
Args:
@@ -260,16 +258,16 @@ def random_crop_generator3d(
dtype (torch.dtype): the data type of the generated random numbers. Default: float32.
Returns:
- params Dict[str, torch.Tensor]: parameters to be passed for transformation.
- - src (torch.Tensor): cropping bounding boxes with a shape of (B, 8, 3).
- - dst (torch.Tensor): output bounding boxes with a shape (B, 8, 3).
+ params Dict[str, Tensor]: parameters to be passed for transformation.
+ - src (Tensor): cropping bounding boxes with a shape of (B, 8, 3).
+ - dst (Tensor): output bounding boxes with a shape (B, 8, 3).
Note:
The generated random numbers are not reproducible across different devices and dtypes.
"""
- _device, _dtype = _extract_device_dtype([size if isinstance(size, torch.Tensor) else None])
- if not isinstance(size, torch.Tensor):
- size = torch.tensor(size, device=device, dtype=dtype).repeat(batch_size, 1)
+ _device, _dtype = _extract_device_dtype([size if isinstance(size, Tensor) else None])
+ if not isinstance(size, Tensor):
+ size = tensor(size, device=device, dtype=dtype).repeat(batch_size, 1)
else:
size = size.to(device=device, dtype=dtype)
if size.shape != torch.Size([batch_size, 3]):
@@ -297,8 +295,7 @@ def random_crop_generator3d(
if batch_size == 0:
return dict(
- src=torch.zeros([0, 8, 3], device=_device, dtype=_dtype),
- dst=torch.zeros([0, 8, 3], device=_device, dtype=_dtype),
+ src=zeros([0, 8, 3], device=_device, dtype=_dtype), dst=zeros([0, 8, 3], device=_device, dtype=_dtype)
)
if same_on_batch:
@@ -322,9 +319,9 @@ def random_crop_generator3d(
if resize_to is None:
crop_dst = bbox_generator3d(
- torch.tensor([0] * batch_size, device=_device, dtype=_dtype),
- torch.tensor([0] * batch_size, device=_device, dtype=_dtype),
- torch.tensor([0] * batch_size, device=_device, dtype=_dtype),
+ tensor([0] * batch_size, device=_device, dtype=_dtype),
+ tensor([0] * batch_size, device=_device, dtype=_dtype),
+ tensor([0] * batch_size, device=_device, dtype=_dtype),
size[:, 2].to(device=_device, dtype=_dtype) - 1,
size[:, 1].to(device=_device, dtype=_dtype) - 1,
size[:, 0].to(device=_device, dtype=_dtype) - 1,
@@ -340,7 +337,7 @@ def random_crop_generator3d(
and resize_to[2] > 0
):
raise AssertionError(f"`resize_to` must be a tuple of 3 positive integers. Got {resize_to}.")
- crop_dst = torch.tensor(
+ crop_dst = tensor(
[
[
[0, 0, 0],
diff --git a/kornia/augmentation/random_generator/_3d/motion_blur.py b/kornia/augmentation/random_generator/_3d/motion_blur.py
index 13a5ad49f..fd3d601ed 100644
--- a/kornia/augmentation/random_generator/_3d/motion_blur.py
+++ b/kornia/augmentation/random_generator/_3d/motion_blur.py
@@ -12,6 +12,7 @@ from kornia.augmentation.utils import (
_range_bound,
_tuple_range_reader,
)
+from kornia.core import Tensor, stack
from kornia.utils.helpers import _deprecated, _extract_device_dtype
@@ -33,9 +34,9 @@ class MotionBlurGenerator3D(RandomGeneratorBase):
Returns:
A dict of parameters to be passed for transformation.
- - ksize_factor (torch.Tensor): element-wise kernel size factors with a shape of (B,).
- - angle_factor (torch.Tensor): element-wise angle factors with a shape of (B,).
- - direction_factor (torch.Tensor): element-wise direction factors with a shape of (B,).
+ - ksize_factor (Tensor): element-wise kernel size factors with a shape of (B,).
+ - angle_factor (Tensor): element-wise angle factors with a shape of (B,).
+ - direction_factor (Tensor): element-wise direction factors with a shape of (B,).
Note:
The generated random numbers are not reproducible across different devices and dtypes. By default,
@@ -47,12 +48,12 @@ class MotionBlurGenerator3D(RandomGeneratorBase):
self,
kernel_size: Union[int, Tuple[int, int]],
angle: Union[
- torch.Tensor,
+ Tensor,
float,
Tuple[float, float, float],
Tuple[Tuple[float, float], Tuple[float, float], Tuple[float, float]],
],
- direction: Union[torch.Tensor, float, Tuple[float, float]],
+ direction: Union[Tensor, float, Tuple[float, float]],
) -> None:
super().__init__()
self.kernel_size = kernel_size
@@ -64,7 +65,7 @@ class MotionBlurGenerator3D(RandomGeneratorBase):
return repr
def make_samplers(self, device: torch.device, dtype: torch.dtype) -> None:
- angle: torch.Tensor = _tuple_range_reader(self.angle, 3, device=device, dtype=dtype)
+ angle: Tensor = _tuple_range_reader(self.angle, 3, device=device, dtype=dtype)
direction = _range_bound(self.direction, 'direction', center=0.0, bounds=(-1, 1)).to(device=device, dtype=dtype)
if isinstance(self.kernel_size, int):
if not (self.kernel_size >= 3 and self.kernel_size % 2 == 1):
@@ -83,7 +84,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, torch.Tensor]: # type:ignore
+ def forward(self, batch_shape: torch.Size, 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))
@@ -91,7 +92,7 @@ class MotionBlurGenerator3D(RandomGeneratorBase):
yaw_factor = _adapted_rsampling((batch_size,), self.yaw_sampler, same_on_batch)
pitch_factor = _adapted_rsampling((batch_size,), self.pitch_sampler, same_on_batch)
roll_factor = _adapted_rsampling((batch_size,), self.roll_sampler, same_on_batch)
- angle_factor = torch.stack([yaw_factor, pitch_factor, roll_factor], dim=1)
+ angle_factor = stack([yaw_factor, pitch_factor, roll_factor], 1)
direction_factor = _adapted_rsampling((batch_size,), self.direction_sampler, same_on_batch)
ksize_factor = _adapted_rsampling((batch_size,), self.ksize_sampler, same_on_batch).int() * 2 + 1
@@ -107,19 +108,19 @@ class MotionBlurGenerator3D(RandomGeneratorBase):
def random_motion_blur_generator3d(
batch_size: int,
kernel_size: Union[int, Tuple[int, int]],
- angle: torch.Tensor,
- direction: torch.Tensor,
+ angle: Tensor,
+ direction: Tensor,
same_on_batch: bool = False,
device: torch.device = torch.device('cpu'),
dtype: torch.dtype = torch.float32,
-) -> Dict[str, torch.Tensor]:
+) -> Dict[str, Tensor]:
r"""Get parameters for motion blur.
Args:
batch_size (int): the tensor batch size.
kernel_size (int or (int, int)): motion kernel size (odd and positive) or range.
- angle (torch.Tensor): yaw, pitch and roll range of the motion blur in degrees :math:`(3, 2)`.
- direction (torch.Tensor): forward/backward direction of the motion blur.
+ angle (Tensor): yaw, pitch and roll range of the motion blur in degrees :math:`(3, 2)`.
+ direction (Tensor): forward/backward direction of the motion blur.
Lower values towards -1.0 will point the motion blur towards the back (with
angle provided via angle), while higher values towards 1.0 will point the motion
blur forward. A value of 0.0 leads to a uniformly (but still angled) motion blur.
@@ -128,10 +129,10 @@ def random_motion_blur_generator3d(
dtype (torch.dtype): the data type of the generated random numbers. Default: float32.
Returns:
- params Dict[str, torch.Tensor]: parameters to be passed for transformation.
- - ksize_factor (torch.Tensor): element-wise kernel size factors with a shape of (B,).
- - angle_factor (torch.Tensor): element-wise center with a shape of (B,).
- - direction_factor (torch.Tensor): element-wise scales with a shape of (B,).
+ params Dict[str, Tensor]: parameters to be passed for transformation.
+ - ksize_factor (Tensor): element-wise kernel size factors with a shape of (B,).
+ - angle_factor (Tensor): element-wise center with a shape of (B,).
+ - direction_factor (Tensor): element-wise scales with a shape of (B,).
Note:
The generated random numbers are not reproducible across different devices and dtypes.
@@ -158,7 +159,7 @@ def random_motion_blur_generator3d(
yaw = _adapted_uniform((batch_size,), angle[0][0], angle[0][1], same_on_batch)
pitch = _adapted_uniform((batch_size,), angle[1][0], angle[1][1], same_on_batch)
roll = _adapted_uniform((batch_size,), angle[2][0], angle[2][1], same_on_batch)
- angle_factor = torch.stack([yaw, pitch, roll], dim=1)
+ angle_factor = stack([yaw, pitch, roll], 1)
direction = direction.to(device=device, dtype=dtype)
direction_factor = _adapted_uniform((batch_size,), direction[0], direction[1], same_on_batch)
diff --git a/kornia/augmentation/random_generator/_3d/perspective.py b/kornia/augmentation/random_generator/_3d/perspective.py
index 68182f109..79d3b6247 100644
--- a/kornia/augmentation/random_generator/_3d/perspective.py
+++ b/kornia/augmentation/random_generator/_3d/perspective.py
@@ -5,6 +5,7 @@ from torch.distributions import Uniform
from kornia.augmentation.random_generator.base import RandomGeneratorBase
from kornia.augmentation.utils import _adapted_rsampling, _adapted_uniform, _common_param_check
+from kornia.core import Tensor, as_tensor, stack, tensor
from kornia.utils.helpers import _deprecated, _extract_device_dtype
@@ -16,8 +17,8 @@ class PerspectiveGenerator3D(RandomGeneratorBase):
Returns:
A dict of parameters to be passed for transformation.
- - src (torch.Tensor): perspective source bounding boxes with a shape of (B, 8, 3).
- - dst (torch.Tensor): perspective target bounding boxes with a shape (B, 8, 3).
+ - src (Tensor): perspective source bounding boxes with a shape of (B, 8, 3).
+ - dst (Tensor): perspective target bounding boxes with a shape (B, 8, 3).
Note:
The generated random numbers are not reproducible across different devices and dtypes. By default,
@@ -25,7 +26,7 @@ class PerspectiveGenerator3D(RandomGeneratorBase):
``self.set_rng_device_and_dtype(device="cuda", dtype=torch.float64)``.
"""
- def __init__(self, distortion_scale: Union[torch.Tensor, float] = 0.5) -> None:
+ def __init__(self, distortion_scale: Union[Tensor, float] = 0.5) -> None:
super().__init__()
self.distortion_scale = distortion_scale
@@ -34,16 +35,14 @@ class PerspectiveGenerator3D(RandomGeneratorBase):
return repr
def make_samplers(self, device: torch.device, dtype: torch.dtype) -> None:
- self._distortion_scale = torch.as_tensor(self.distortion_scale, device=device, dtype=dtype)
+ self._distortion_scale = as_tensor(self.distortion_scale, device=device, dtype=dtype)
if not (self._distortion_scale.dim() == 0 and 0 <= self._distortion_scale <= 1):
raise AssertionError(f"'distortion_scale' must be a scalar within [0, 1]. Got {self._distortion_scale}")
self.rand_sampler = Uniform(
- torch.tensor(0, device=device, dtype=dtype),
- torch.tensor(1, device=device, dtype=dtype),
- validate_args=False,
+ 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, torch.Tensor]: # type:ignore
+ def forward(self, batch_shape: torch.Size, same_on_batch: bool = False) -> Dict[str, Tensor]:
batch_size = batch_shape[0]
depth = batch_shape[-3]
height = batch_shape[-2]
@@ -52,7 +51,7 @@ class PerspectiveGenerator3D(RandomGeneratorBase):
_common_param_check(batch_size, same_on_batch)
_device, _dtype = _extract_device_dtype([self.distortion_scale])
- start_points: torch.Tensor = torch.tensor(
+ start_points: Tensor = tensor(
[
[
[0.0, 0, 0],
@@ -74,13 +73,13 @@ class PerspectiveGenerator3D(RandomGeneratorBase):
fy = self._distortion_scale * height / 2
fz = self._distortion_scale * depth / 2
- factor = torch.stack([fx, fy, fz], dim=0).view(-1, 1, 3).to(device=_device, dtype=_dtype)
+ factor = stack([fx, fy, fz], 0).view(-1, 1, 3).to(device=_device, dtype=_dtype)
- rand_val: torch.Tensor = _adapted_rsampling(start_points.shape, self.rand_sampler, same_on_batch).to(
+ rand_val: Tensor = _adapted_rsampling(start_points.shape, self.rand_sampler, same_on_batch).to(
device=_device, dtype=_dtype
)
- pts_norm = torch.tensor(
+ pts_norm = tensor(
[[[1, 1, 1], [-1, 1, 1], [-1, -1, 1], [1, -1, 1], [1, 1, -1], [-1, 1, -1], [-1, -1, -1], [1, -1, -1]]],
device=_device,
dtype=_dtype,
@@ -96,11 +95,11 @@ def random_perspective_generator3d(
depth: int,
height: int,
width: int,
- distortion_scale: torch.Tensor,
+ distortion_scale: Tensor,
same_on_batch: bool = False,
device: torch.device = torch.device('cpu'),
dtype: torch.dtype = torch.float32,
-) -> Dict[str, torch.Tensor]:
+) -> Dict[str, Tensor]:
r"""Get parameters for ``perspective`` for a random perspective transform.
Args:
@@ -108,15 +107,15 @@ def random_perspective_generator3d(
depth (int) : depth of the image.
height (int) : height of the image.
width (int): width of the image.
- distortion_scale (torch.Tensor): it controls the degree of distortion and ranges from 0 to 1.
+ distortion_scale (Tensor): it controls the degree of distortion and ranges from 0 to 1.
same_on_batch (bool): apply the same transformation across the batch. Default: False.
device (torch.device): the device on which the random numbers will be generated. Default: cpu.
dtype (torch.dtype): the data type of the generated random numbers. Default: float32.
Returns:
- params Dict[str, torch.Tensor]: parameters to be passed for transformation.
- - src (torch.Tensor): perspective source bounding boxes with a shape of (B, 8, 3).
- - dst (torch.Tensor): perspective target bounding boxes with a shape (B, 8, 3).
+ params Dict[str, Tensor]: parameters to be passed for transformation.
+ - src (Tensor): perspective source bounding boxes with a shape of (B, 8, 3).
+ - dst (Tensor): perspective target bounding boxes with a shape (B, 8, 3).
Note:
The generated random numbers are not reproducible across different devices and dtypes.
@@ -126,7 +125,7 @@ def random_perspective_generator3d(
_device, _dtype = _extract_device_dtype([distortion_scale])
distortion_scale = distortion_scale.to(device=device, dtype=dtype)
- start_points: torch.Tensor = torch.tensor(
+ start_points: Tensor = tensor(
[
[
[0.0, 0, 0],
@@ -148,16 +147,13 @@ def random_perspective_generator3d(
fy = distortion_scale * height / 2
fz = distortion_scale * depth / 2
- factor = torch.stack([fx, fy, fz], dim=0).view(-1, 1, 3)
+ factor = stack([fx, fy, fz], 0).view(-1, 1, 3)
- rand_val: torch.Tensor = _adapted_uniform(
- start_points.shape,
- torch.tensor(0, device=device, dtype=dtype),
- torch.tensor(1, device=device, dtype=dtype),
- same_on_batch,
+ rand_val: Tensor = _adapted_uniform(
+ start_points.shape, tensor(0, device=device, dtype=dtype), tensor(1, device=device, dtype=dtype), same_on_batch
)
- pts_norm = torch.tensor(
+ pts_norm = tensor(
[[[1, 1, 1], [-1, 1, 1], [-1, -1, 1], [1, -1, 1], [1, 1, -1], [-1, 1, -1], [-1, -1, -1], [1, -1, -1]]],
device=device,
dtype=dtype,
diff --git a/kornia/augmentation/random_generator/_3d/rotation.py b/kornia/augmentation/random_generator/_3d/rotation.py
index 327e32c0c..249fb78b3 100644
--- a/kornia/augmentation/random_generator/_3d/rotation.py
+++ b/kornia/augmentation/random_generator/_3d/rotation.py
@@ -5,6 +5,7 @@ from torch.distributions import Uniform
from kornia.augmentation.random_generator.base import RandomGeneratorBase
from kornia.augmentation.utils import _adapted_rsampling, _adapted_uniform, _common_param_check, _tuple_range_reader
+from kornia.core import Tensor
from kornia.utils.helpers import _deprecated, _extract_device_dtype
@@ -23,9 +24,9 @@ class RotationGenerator3D(RandomGeneratorBase):
Returns:
A dict of parameters to be passed for transformation.
- - yaw (torch.Tensor): element-wise rotation yaws with a shape of (B,).
- - pitch (torch.Tensor): element-wise rotation pitches with a shape of (B,).
- - roll (torch.Tensor): element-wise rotation rolls with a shape of (B,).
+ - yaw (Tensor): element-wise rotation yaws with a shape of (B,).
+ - pitch (Tensor): element-wise rotation pitches with a shape of (B,).
+ - roll (Tensor): element-wise rotation rolls with a shape of (B,).
Note:
The generated random numbers are not reproducible across different devices and dtypes. By default,
@@ -36,7 +37,7 @@ class RotationGenerator3D(RandomGeneratorBase):
def __init__(
self,
degrees: Union[
- torch.Tensor,
+ Tensor,
float,
Tuple[float, float, float],
Tuple[Tuple[float, float], Tuple[float, float], Tuple[float, float]],
@@ -55,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, torch.Tensor]: # type:ignore
+ def forward(self, batch_shape: torch.Size, 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])
@@ -70,25 +71,25 @@ class RotationGenerator3D(RandomGeneratorBase):
@_deprecated(replace_with=RotationGenerator3D.__name__)
def random_rotation_generator3d(
batch_size: int,
- degrees: torch.Tensor,
+ degrees: Tensor,
same_on_batch: bool = False,
device: torch.device = torch.device('cpu'),
dtype: torch.dtype = torch.float32,
-) -> Dict[str, torch.Tensor]:
+) -> Dict[str, Tensor]:
r"""Get parameters for ``rotate`` for a random rotate transform.
Args:
batch_size (int): the tensor batch size.
- degrees (torch.Tensor): Ranges of degrees (3, 2) for yaw, pitch and roll.
+ degrees (Tensor): Ranges of degrees (3, 2) for yaw, pitch and roll.
same_on_batch (bool): apply the same transformation across the batch. Default: False.
device (torch.device): the device on which the random numbers will be generated. Default: cpu.
dtype (torch.dtype): the data type of the generated random numbers. Default: float32.
Returns:
- params Dict[str, torch.Tensor]: parameters to be passed for transformation.
- - yaw (torch.Tensor): element-wise rotation yaws with a shape of (B,).
- - pitch (torch.Tensor): element-wise rotation pitches with a shape of (B,).
- - roll (torch.Tensor): element-wise rotation rolls with a shape of (B,).
+ params Dict[str, Tensor]: parameters to be passed for transformation.
+ - yaw (Tensor): element-wise rotation yaws with a shape of (B,).
+ - pitch (Tensor): element-wise rotation pitches with a shape of (B,).
+ - roll (Tensor): element-wise rotation rolls with a shape of (B,).
"""
if degrees.shape != torch.Size([3, 2]):
raise AssertionError(f"'degrees' must be the shape of (3, 2). Got {degrees.shape}.")
diff --git a/kornia/augmentation/random_generator/base.py b/kornia/augmentation/random_generator/base.py
index 50226bcfb..cef44699f 100644
--- a/kornia/augmentation/random_generator/base.py
+++ b/kornia/augmentation/random_generator/base.py
@@ -50,7 +50,7 @@ class RandomGeneratorBase(nn.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]: # type:ignore
+ def forward(self, batch_shape: torch.Size, same_on_batch: bool = False) -> Dict[str, Tensor]:
raise NotImplementedError
diff --git a/kornia/augmentation/utils/helpers.py b/kornia/augmentation/utils/helpers.py
index 909e28762..411c70713 100644
--- a/kornia/augmentation/utils/helpers.py
+++ b/kornia/augmentation/utils/helpers.py
@@ -2,9 +2,9 @@ from functools import wraps
from typing import Any, Callable, Dict, List, Optional, Tuple, Union, cast
import torch
-from torch import Tensor
from torch.distributions import Beta, Uniform
+from kornia.core import Tensor, as_tensor
from kornia.utils import _extract_device_dtype
@@ -155,7 +155,7 @@ def _transform_output_shape(output: Tensor, shape: Tuple) -> Tensor:
raise AssertionError(f'Dimension {dim} of input is ' f'expected to be 1, got {out_tensor.shape[0]}')
out_tensor = out_tensor.squeeze(0)
- return out_tensor # type: ignore
+ return out_tensor
def _validate_shape(shape: Union[Tuple, torch.Size], required_shapes: Tuple[str, ...] = ("BCHW",)) -> None:
@@ -232,8 +232,8 @@ def _adapted_uniform(
device, dtype = _extract_device_dtype(
[low if isinstance(low, Tensor) else None, high if isinstance(high, Tensor) else None]
)
- low = torch.as_tensor(low, device=device, dtype=dtype)
- high = torch.as_tensor(high, device=device, dtype=dtype)
+ low = as_tensor(low, device=device, dtype=dtype)
+ high = as_tensor(high, device=device, dtype=dtype)
# validate_args=False to fix pytorch 1.7.1 error:
# ValueError: Uniform is not defined when low>= high.
dist = Uniform(low, high, validate_args=False)
@@ -255,8 +255,8 @@ def _adapted_beta(
in the same device/dtype as a/b tensor.
"""
device, dtype = _extract_device_dtype([a if isinstance(a, Tensor) else None, b if isinstance(b, Tensor) else None])
- a = torch.as_tensor(a, device=device, dtype=dtype)
- b = torch.as_tensor(b, device=device, dtype=dtype)
+ a = as_tensor(a, device=device, dtype=dtype)
+ b = as_tensor(b, device=device, dtype=dtype)
dist = Beta(a, b, validate_args=False)
return _adapted_rsampling(shape, dist, same_on_batch)
diff --git a/kornia/constants.py b/kornia/constants.py
index 96b856f32..048f06e98 100644
--- a/kornia/constants.py
+++ b/kornia/constants.py
@@ -64,7 +64,7 @@ class DType(ConstantBase):
FLOAT64 = 3
@classmethod
- def get(cls, value: Union[str, int, torch.dtype, Tensor, 'DType']) -> 'DType': # type: ignore[override]
+ def get(cls, value: Union[str, int, torch.dtype, Tensor, 'DType']) -> 'DType':
if isinstance(value, torch.dtype):
value = str(value).upper() # Convert to str
if isinstance(value, Tensor):
diff --git a/kornia/contrib/extract_patches.py b/kornia/contrib/extract_patches.py
index 07fa6c240..ec4c5b094 100644
--- a/kornia/contrib/extract_patches.py
+++ b/kornia/contrib/extract_patches.py
@@ -1,10 +1,10 @@
from typing import Optional, Tuple, Union, cast
import torch
-import torch.nn as nn
-import torch.nn.functional as F
from torch.nn.modules.utils import _pair
+from kornia.core import Module, Tensor, concatenate, pad
+
PadType = Union[Tuple[int, int], Tuple[int, int, int, int]]
@@ -57,7 +57,7 @@ def compute_padding(
return (padt, padb, padl, padr)
-class ExtractTensorPatches(nn.Module):
+class ExtractTensorPatches(Module):
r"""Module that extract patches from tensors and stack them.
In the simplest case, the output value of the operator with input size
@@ -126,11 +126,11 @@ class ExtractTensorPatches(nn.Module):
self.stride: Tuple[int, int] = _pair(stride)
self.padding: PadType = _pair(padding)
- def forward(self, input: torch.Tensor) -> torch.Tensor: # type: ignore
+ def forward(self, input: Tensor) -> Tensor:
return extract_tensor_patches(input, self.window_size, stride=self.stride, padding=self.padding)
-class CombineTensorPatches(nn.Module):
+class CombineTensorPatches(Module):
r"""Module that combine patches from tensors.
In the simplest case, the output value of the operator with input size
@@ -197,19 +197,19 @@ class CombineTensorPatches(nn.Module):
self.window_size: Tuple[int, int] = _pair(window_size)
self.unpadding: PadType = _pair(unpadding)
- def forward(self, input: torch.Tensor) -> torch.Tensor:
+ def forward(self, input: Tensor) -> Tensor:
return combine_tensor_patches(
input, self.original_size, self.window_size, stride=self.window_size, unpadding=self.unpadding
)
def combine_tensor_patches(
- patches: torch.Tensor,
+ patches: Tensor,
original_size: Union[int, Tuple[int, int]],
window_size: Union[int, Tuple[int, int]],
stride: Union[int, Tuple[int, int]],
unpadding: Union[int, PadType] = 0,
-) -> torch.Tensor:
+) -> Tensor:
r"""Restore input from patches.
See :class:`~kornia.contrib.CombineTensorPatches` for details.
@@ -275,18 +275,16 @@ def combine_tensor_patches(
)
patches_tensor = patches.view(-1, window_size[0], window_size[1], *patches.shape[-3:])
- restored_tensor = torch.cat(torch.chunk(patches_tensor, window_size[0], dim=1), -2).squeeze(1)
- restored_tensor = torch.cat(torch.chunk(restored_tensor, window_size[1], dim=1), -1).squeeze(1)
+ restored_tensor = concatenate(torch.chunk(patches_tensor, window_size[0], 1), -2).squeeze(1)
+ restored_tensor = concatenate(torch.chunk(restored_tensor, window_size[1], 1), -1).squeeze(1)
if unpadding:
unpadding = cast(Tuple[int, int, int, int], unpadding)
- restored_tensor = F.pad(restored_tensor, [-i for i in unpadding])
+ restored_tensor = pad(restored_tensor, [-i for i in unpadding])
return restored_tensor
-def _extract_tensor_patchesnd(
- input: torch.Tensor, window_sizes: Tuple[int, ...], strides: Tuple[int, ...]
-) -> torch.Tensor:
+def _extract_tensor_patchesnd(input: Tensor, window_sizes: Tuple[int, ...], strides: Tuple[int, ...]) -> Tensor:
batch_size, num_channels = input.size()[:2]
dims = range(2, input.dim())
for dim, patch_size, stride in zip(dims, window_sizes, strides):
@@ -296,11 +294,11 @@ def _extract_tensor_patchesnd(
def extract_tensor_patches(
- input: torch.Tensor,
+ input: Tensor,
window_size: Union[int, Tuple[int, int]],
stride: Union[int, Tuple[int, int]] = 1,
padding: Union[int, PadType] = 0,
-) -> torch.Tensor:
+) -> Tensor:
r"""Function that extract patches from tensors and stack them.
See :class:`~kornia.contrib.ExtractTensorPatches` for details.
@@ -326,7 +324,7 @@ def extract_tensor_patches(
[6., 7., 8.]]]])
"""
if not torch.is_tensor(input):
- raise TypeError(f"Input input type is not a torch.Tensor. Got {type(input)}")
+ raise TypeError(f"Input input type is not a Tensor. Got {type(input)}")
if len(input.shape) != 4:
raise ValueError(f"Invalid input shape, we expect BxCxHxW. Got: {input.shape}")
@@ -344,6 +342,6 @@ def extract_tensor_patches(
pad_vert = padding[:2]
pad_horz = padding[2:]
padding = cast(Tuple[int, int, int, int], pad_horz + pad_vert)
- input = F.pad(input, padding)
+ input = pad(input, padding)
return _extract_tensor_patchesnd(input, _pair(window_size), _pair(stride))
diff --git a/kornia/enhance/core.py b/kornia/enhance/core.py
index 6d55aed9d..b72af4d8e 100644
--- a/kornia/enhance/core.py
+++ b/kornia/enhance/core.py
@@ -80,5 +80,5 @@ class AddWeighted(Module):
self.beta = beta
self.gamma = gamma
- def forward(self, src1: Tensor, src2: Tensor) -> Tensor: # type: ignore
+ def forward(self, src1: Tensor, src2: Tensor) -> Tensor:
return add_weighted(src1, self.alpha, src2, self.beta, self.gamma)
diff --git a/kornia/enhance/zca.py b/kornia/enhance/zca.py
index 8bb216cf3..c967c77e5 100644
--- a/kornia/enhance/zca.py
+++ b/kornia/enhance/zca.py
@@ -1,12 +1,13 @@
from typing import List, Optional, Tuple
import torch
-import torch.nn as nn
+
+from kornia.core import Module, Tensor, concatenate, tensor
__all__ = ["zca_mean", "zca_whiten", "linear_transform", "ZCAWhitening"]
-class ZCAWhitening(nn.Module):
+class ZCAWhitening(Module):
r"""Compute the ZCA whitening matrix transform and the mean vector and applies the transform to the data.
The data tensor is flattened, and the mean :math:`\mathbf{\mu}`
@@ -80,11 +81,11 @@ class ZCAWhitening(nn.Module):
self.fitted = False
- self.mean_vector: torch.Tensor
- self.transform_matrix: torch.Tensor
- self.transform_inv: Optional[torch.Tensor]
+ self.mean_vector: Tensor
+ self.transform_matrix: Tensor
+ self.transform_inv: Optional[Tensor]
- def fit(self, x: torch.Tensor):
+ def fit(self, x: Tensor):
r"""Fit ZCA whitening matrices to the data.
Args:
@@ -113,7 +114,7 @@ class ZCAWhitening(nn.Module):
return self
- def forward(self, x: torch.Tensor, include_fit: bool = False) -> torch.Tensor:
+ def forward(self, x: Tensor, include_fit: bool = False) -> Tensor:
r"""Apply the whitening transform to the data.
Args:
@@ -134,7 +135,7 @@ class ZCAWhitening(nn.Module):
return x_whiten
- def inverse_transform(self, x: torch.Tensor) -> torch.Tensor:
+ def inverse_transform(self, x: Tensor) -> Tensor:
r"""Apply the inverse transform to the whitened data.
Args:
@@ -150,16 +151,19 @@ class ZCAWhitening(nn.Module):
if not self.compute_inv:
raise RuntimeError("Did not compute inverse ZCA. Please set compute_inv to True")
- mean_inv: torch.Tensor = -self.mean_vector.mm(self.transform_matrix) # type: ignore
+ if self.transform_inv is None:
+ raise TypeError('The transform inverse should be a Tensor. Gotcha None.')
+
+ mean_inv: Tensor = -self.mean_vector.mm(self.transform_matrix)
- y = linear_transform(x, self.transform_inv, mean_inv) # type: ignore
+ y = linear_transform(x, self.transform_inv, mean_inv)
return y
def zca_mean(
- inp: torch.Tensor, dim: int = 0, unbiased: bool = True, eps: float = 1e-6, return_inverse: bool = False
-) -> Tuple[torch.Tensor, torch.Tensor, Optional[torch.Tensor]]:
+ inp: Tensor, dim: int = 0, unbiased: bool = True, eps: float = 1e-6, return_inverse: bool = False
+) -> Tuple[Tensor, Tensor, Optional[Tensor]]:
r"""Compute the ZCA whitening matrix and mean vector.
The output can be used with :py:meth:`~kornia.color.linear_transform`.
@@ -194,8 +198,8 @@ def zca_mean(
>>> # transform_matrix.size() equals (12,12) and the mean vector.size equal (1,12)
"""
- if not isinstance(inp, torch.Tensor):
- raise TypeError(f"Input type is not a torch.Tensor. Got {type(inp)}")
+ if not isinstance(inp, Tensor):
+ raise TypeError(f"Input type is not a Tensor. Got {type(inp)}")
if not isinstance(eps, float):
raise TypeError(f"eps type is not a float. Got{type(eps)}")
@@ -221,21 +225,21 @@ def zca_mean(
if dim < 0:
dim = len(inp_size) + dim
- feat_dims = torch.cat([torch.arange(0, dim), torch.arange(dim + 1, len(inp_size))])
+ feat_dims = concatenate([torch.arange(0, dim), torch.arange(dim + 1, len(inp_size))])
- new_order: List[int] = torch.cat([torch.tensor([dim]), feat_dims]).tolist()
+ new_order: List[int] = concatenate([tensor([dim]), feat_dims]).tolist()
inp_permute = inp.permute(new_order)
N = inp_size[dim]
- feature_sizes = torch.tensor(inp_size[0:dim] + inp_size[dim + 1 : :])
+ feature_sizes = tensor(inp_size[0:dim] + inp_size[dim + 1 : :])
num_features: int = int(torch.prod(feature_sizes).item())
- mean: torch.Tensor = torch.mean(inp_permute, dim=0, keepdim=True)
+ mean: Tensor = torch.mean(inp_permute, dim=0, keepdim=True)
mean = mean.reshape((1, num_features))
- inp_center_flat: torch.Tensor = inp_permute.reshape((N, num_features)) - mean
+ inp_center_flat: Tensor = inp_permute.reshape((N, num_features)) - mean
cov = inp_center_flat.t().mm(inp_center_flat)
@@ -247,17 +251,17 @@ def zca_mean(
U, S, _ = torch.linalg.svd(cov)
S = S.reshape(-1, 1)
- S_inv_root: torch.Tensor = torch.rsqrt(S + eps)
- T: torch.Tensor = (U).mm(S_inv_root * U.t())
+ S_inv_root: Tensor = torch.rsqrt(S + eps)
+ T: Tensor = (U).mm(S_inv_root * U.t())
- T_inv: Optional[torch.Tensor] = None
+ T_inv: Optional[Tensor] = None
if return_inverse:
T_inv = (U).mm(torch.sqrt(S + eps) * U.t())
return T, mean, T_inv
-def zca_whiten(inp: torch.Tensor, dim: int = 0, unbiased: bool = True, eps: float = 1e-6) -> torch.Tensor:
+def zca_whiten(inp: Tensor, dim: int = 0, unbiased: bool = True, eps: float = 1e-6) -> Tensor:
r"""Apply ZCA whitening transform.
See :class:`~kornia.color.ZCAWhitening` for details.
@@ -283,8 +287,8 @@ def zca_whiten(inp: torch.Tensor, dim: int = 0, unbiased: bool = True, eps: floa
[-1.0000, -0.5773]])
"""
- if not isinstance(inp, torch.Tensor):
- raise TypeError(f"Input type is not a torch.Tensor. Got {type(inp)}")
+ if not isinstance(inp, Tensor):
+ raise TypeError(f"Input type is not a Tensor. Got {type(inp)}")
if not isinstance(eps, float):
raise TypeError(f"eps type is not a float. Got{type(eps)}")
@@ -302,9 +306,7 @@ def zca_whiten(inp: torch.Tensor, dim: int = 0, unbiased: bool = True, eps: floa
return inp_whiten
-def linear_transform(
- inp: torch.Tensor, transform_matrix: torch.Tensor, mean_vector: torch.Tensor, dim: int = 0
-) -> torch.Tensor:
+def linear_transform(inp: Tensor, transform_matrix: Tensor, mean_vector: Tensor, dim: int = 0) -> Tensor:
r"""Given a transformation matrix and a mean vector, this function will flatten the input tensor along the given
dimension and subtract the mean vector from it. Then the dot product with the transformation matrix will be
computed and then the resulting tensor is reshaped to the original input shape.
@@ -357,15 +359,15 @@ def linear_transform(
if dim < 0:
dim = len(inp_size) + dim
- feat_dims = torch.cat([torch.arange(0, dim), torch.arange(dim + 1, len(inp_size))])
+ feat_dims = concatenate([torch.arange(0, dim), torch.arange(dim + 1, len(inp_size))])
- perm = torch.cat([torch.tensor([dim]), feat_dims])
+ perm = concatenate([tensor([dim]), feat_dims])
perm_inv = torch.argsort(perm)
new_order: List[int] = perm.tolist()
inv_order: List[int] = perm_inv.tolist()
- feature_sizes = torch.tensor(inp_size[0:dim] + inp_size[dim + 1 : :])
+ feature_sizes = tensor(inp_size[0:dim] + inp_size[dim + 1 : :])
num_features: int = int(torch.prod(feature_sizes).item())
inp_permute = inp.permute(new_order)
diff --git a/kornia/feature/scale_space_detector.py b/kornia/feature/scale_space_detector.py
index 7c43be4c1..3a03c5dc4 100644
--- a/kornia/feature/scale_space_detector.py
+++ b/kornia/feature/scale_space_detector.py
@@ -1,9 +1,9 @@
from typing import List, Optional, Tuple
import torch
-import torch.nn as nn
import torch.nn.functional as F
+from kornia.core import Device, Module, Tensor, concatenate, eye
from kornia.geometry.subpix import ConvSoftArgmax3d
from kornia.geometry.transform import ScalePyramid
@@ -12,7 +12,7 @@ from .orientation import PassLAF
from .responses import BlobHessian
-def _scale_index_to_scale(max_coords: torch.Tensor, sigmas: torch.Tensor, num_levels: int) -> torch.Tensor:
+def _scale_index_to_scale(max_coords: Tensor, sigmas: Tensor, num_levels: int) -> Tensor:
r"""Auxiliary function for ScaleSpaceDetector. Converts scale level index from ConvSoftArgmax3d to the actual
scale, using the sigmas from the ScalePyramid output.
@@ -32,20 +32,20 @@ def _scale_index_to_scale(max_coords: torch.Tensor, sigmas: torch.Tensor, num_le
B, N, _ = max_coords.shape
scale_coords = max_coords[:, :, 0].contiguous().view(-1, 1, 1, 1)
# Replace the scale_x_y
- out = torch.cat(
- [sigmas[0, 0] * torch.pow(2.0, scale_coords / float(num_levels)).view(B, N, 1), max_coords[:, :, 1:]], dim=2
+ out = concatenate(
+ [sigmas[0, 0] * torch.pow(2.0, scale_coords / float(num_levels)).view(B, N, 1), max_coords[:, :, 1:]], 2
)
return out
-def _create_octave_mask(mask: torch.Tensor, octave_shape: List[int]) -> torch.Tensor:
+def _create_octave_mask(mask: Tensor, octave_shape: List[int]) -> Tensor:
r"""Downsample a mask based on the given octave shape."""
mask_shape = octave_shape[-2:]
- mask_octave = F.interpolate(mask, mask_shape, mode='bilinear', align_corners=False) # type: ignore
+ mask_octave = F.interpolate(mask, mask_shape, mode='bilinear', align_corners=False)
return mask_octave.unsqueeze(1)
-class ScaleSpaceDetector(nn.Module):
+class ScaleSpaceDetector(Module):
r"""Module for differentiable local feature detection, as close as possible to classical local feature detectors
like Harris, Hessian-Affine or SIFT (DoG).
@@ -76,13 +76,13 @@ class ScaleSpaceDetector(nn.Module):
self,
num_features: int = 500,
mr_size: float = 6.0,
- scale_pyr_module: nn.Module = ScalePyramid(3, 1.6, 15),
- resp_module: nn.Module = BlobHessian(),
- nms_module: nn.Module = ConvSoftArgmax3d(
+ scale_pyr_module: Module = ScalePyramid(3, 1.6, 15),
+ resp_module: Module = BlobHessian(),
+ nms_module: Module = ConvSoftArgmax3d(
(3, 3, 3), (1, 1, 1), (1, 1, 1), normalized_coordinates=False, output_value=True
),
- ori_module: nn.Module = PassLAF(),
- aff_module: nn.Module = PassLAF(),
+ ori_module: Module = PassLAF(),
+ aff_module: Module = PassLAF(),
minima_are_also_good: bool = False,
scale_space_response=False,
):
@@ -125,14 +125,12 @@ class ScaleSpaceDetector(nn.Module):
+ ')'
)
- def detect(
- self, img: torch.Tensor, num_feats: int, mask: Optional[torch.Tensor] = None
- ) -> Tuple[torch.Tensor, torch.Tensor]:
- dev: torch.device = img.device
+ def detect(self, img: Tensor, num_feats: int, mask: Optional[Tensor] = None) -> Tuple[Tensor, Tensor]:
+ dev: Device = img.device
dtype: torch.dtype = img.dtype
sp, sigmas, _ = self.scale_pyr(img)
- all_responses: List[torch.Tensor] = []
- all_lafs: List[torch.Tensor] = []
+ all_responses: List[Tensor] = []
+ all_lafs: List[Tensor] = []
for oct_idx, octave in enumerate(sp):
sigmas_oct = sigmas[oct_idx]
B, CH, L, H, W = octave.size()
@@ -150,7 +148,7 @@ class ScaleSpaceDetector(nn.Module):
oct_resp = oct_resp[:, :, :-1]
if mask is not None:
- oct_mask: torch.Tensor = _create_octave_mask(mask, oct_resp.shape)
+ oct_mask: Tensor = _create_octave_mask(mask, oct_resp.shape)
oct_resp = oct_mask * oct_resp
# Differentiable nms
@@ -179,13 +177,13 @@ class ScaleSpaceDetector(nn.Module):
)
# Create local affine frames (LAFs)
- rotmat = torch.eye(2, dtype=dtype, device=dev).view(1, 1, 2, 2)
- current_lafs = torch.cat(
+ rotmat = eye(2, dtype=dtype, device=dev).view(1, 1, 2, 2)
+ current_lafs = concatenate(
[
self.mr_size * max_coords_best[:, :, 0].view(B, N, 1, 1) * rotmat,
max_coords_best[:, :, 1:3].view(B, N, 2, 1),
],
- dim=3,
+ 3,
)
# Zero response lafs, which touch the boundary
@@ -199,15 +197,13 @@ class ScaleSpaceDetector(nn.Module):
all_lafs.append(current_lafs)
# Sort and keep best n
- responses: torch.Tensor = torch.cat(all_responses, dim=1)
- lafs: torch.Tensor = torch.cat(all_lafs, dim=1)
+ responses = concatenate(all_responses, 1)
+ lafs = concatenate(all_lafs, 1)
responses, idxs = torch.topk(responses, k=num_feats, dim=1)
lafs = torch.gather(lafs, 1, idxs.unsqueeze(-1).unsqueeze(-1).repeat(1, 1, 2, 3))
return responses, denormalize_laf(lafs, img)
- def forward( # type: ignore
- self, img: torch.Tensor, mask: Optional[torch.Tensor] = None # type: ignore
- ) -> Tuple[torch.Tensor, torch.Tensor]:
+ def forward(self, img: Tensor, mask: Optional[Tensor] = None) -> Tuple[Tensor, Tensor]:
"""Three stage local feature detection. First the location and scale of interest points are determined by
detect function. Then affine shape and orientation.
diff --git a/kornia/feature/siftdesc.py b/kornia/feature/siftdesc.py
index e6dff5a9a..446c421cd 100644
--- a/kornia/feature/siftdesc.py
+++ b/kornia/feature/siftdesc.py
@@ -5,19 +5,20 @@ import torch
import torch.nn as nn
import torch.nn.functional as F
+from kornia.core import Module, Tensor, concatenate, eye
from kornia.filters import get_gaussian_kernel2d, spatial_gradient
from kornia.geometry.conversions import pi
from kornia.testing import KORNIA_CHECK_SHAPE
-def _get_reshape_kernel(kd: int, ky: int, kx: int) -> torch.Tensor:
+def _get_reshape_kernel(kd: int, ky: int, kx: int) -> Tensor:
"""Utility function, which returns neigh2channels conv kernel."""
numel: int = kd * ky * kx
- weight = torch.eye(numel)
+ weight = eye(numel)
return weight.view(numel, kd, ky, kx)
-def get_sift_pooling_kernel(ksize: int = 25) -> torch.Tensor:
+def get_sift_pooling_kernel(ksize: int = 25) -> Tensor:
r"""Return a weighted pooling kernel for SIFT descriptor.
Args:
@@ -27,8 +28,8 @@ def get_sift_pooling_kernel(ksize: int = 25) -> torch.Tensor:
the pooling kernel with shape :math:`(ksize, ksize)`.
"""
ks_2: float = float(ksize) / 2.0
- xc2: torch.Tensor = ks_2 - (torch.arange(ksize).float() + 0.5 - ks_2).abs() # type: ignore
- kernel: torch.Tensor = torch.ger(xc2, xc2) / (ks_2**2)
+ xc2 = ks_2 - (torch.arange(ksize).float() + 0.5 - ks_2).abs()
+ kernel = torch.ger(xc2, xc2) / (ks_2**2)
return kernel
@@ -56,7 +57,7 @@ def get_sift_bin_ksize_stride_pad(patch_size: int, num_spatial_bins: int) -> Tup
return ksize, stride, pad
-class SIFTDescriptor(nn.Module):
+class SIFTDescriptor(Module):
r"""Module which computes SIFT descriptors of given patches.
Args:
@@ -131,13 +132,13 @@ class SIFTDescriptor(nn.Module):
padding=(self.pad, self.pad),
bias=False,
)
- self.pk.weight.data.copy_(nw.reshape(1, 1, nw.size(0), nw.size(1))) # type: ignore
+ self.pk.weight.data.copy_(nw.reshape(1, 1, nw.size(0), nw.size(1)))
return
- def get_pooling_kernel(self) -> torch.Tensor:
+ def get_pooling_kernel(self) -> Tensor:
return self.pk.weight.detach()
- def get_weighting_kernel(self) -> torch.Tensor:
+ def get_weighting_kernel(self) -> Tensor:
return self.gk.detach()
def forward(self, input):
@@ -145,28 +146,28 @@ class SIFTDescriptor(nn.Module):
B: int = input.shape[0]
self.pk = self.pk.to(input.dtype).to(input.device)
- grads: torch.Tensor = spatial_gradient(input, 'diff')
+ grads = spatial_gradient(input, 'diff')
# unpack the edges
- gx: torch.Tensor = grads[:, :, 0]
- gy: torch.Tensor = grads[:, :, 1]
+ gx = grads[:, :, 0]
+ gy = grads[:, :, 1]
- mag: torch.Tensor = torch.sqrt(gx * gx + gy * gy + self.eps)
- ori: torch.Tensor = torch.atan2(gy, gx + self.eps) + 2.0 * pi
+ mag = torch.sqrt(gx * gx + gy * gy + self.eps)
+ ori = torch.atan2(gy, gx + self.eps) + 2.0 * pi
mag = mag * self.gk.expand_as(mag).type_as(mag).to(mag.device)
- o_big: torch.Tensor = float(self.num_ang_bins) * ori / (2.0 * pi)
+ o_big = float(self.num_ang_bins) * ori / (2.0 * pi)
- bo0_big_: torch.Tensor = torch.floor(o_big)
- wo1_big_: torch.Tensor = o_big - bo0_big_
- bo0_big: torch.Tensor = bo0_big_ % self.num_ang_bins
- bo1_big: torch.Tensor = (bo0_big + 1) % self.num_ang_bins
- wo0_big: torch.Tensor = (1.0 - wo1_big_) * mag # type: ignore
- wo1_big: torch.Tensor = wo1_big_ * mag
+ 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 = []
for i in range(0, self.num_ang_bins):
out = self.pk((bo0_big == i).to(input.dtype) * wo0_big + (bo1_big == i).to(input.dtype) * wo1_big)
ang_bins.append(out)
- ang_bins = torch.cat(ang_bins, dim=1)
+ ang_bins = concatenate(ang_bins, 1)
ang_bins = ang_bins.view(B, -1)
ang_bins = F.normalize(ang_bins, p=2)
ang_bins = torch.clamp(ang_bins, 0.0, float(self.clipval))
@@ -177,13 +178,13 @@ class SIFTDescriptor(nn.Module):
def sift_describe(
- input: torch.Tensor,
+ input: Tensor,
patch_size: int = 41,
num_ang_bins: int = 8,
num_spatial_bins: int = 4,
rootsift: bool = True,
clipval: float = 0.2,
-) -> torch.Tensor:
+) -> Tensor:
r"""Computes the sift descriptor.
See :class:`~kornia.feature.SIFTDescriptor` for details.
@@ -191,7 +192,7 @@ def sift_describe(
return SIFTDescriptor(patch_size, num_ang_bins, num_spatial_bins, rootsift, clipval)(input)
-class DenseSIFTDescriptor(nn.Module):
+class DenseSIFTDescriptor(Module):
"""Module, which computes SIFT descriptor densely over the image.
Args:
@@ -205,7 +206,7 @@ class DenseSIFTDescriptor(nn.Module):
padding: default 0
Returns:
- torch.Tensor: DenseSIFT descriptor of the image
+ Tensor: DenseSIFT descriptor of the image
Shape:
- Input: (B, 1, H, W)
@@ -283,7 +284,7 @@ class DenseSIFTDescriptor(nn.Module):
)
return
- def get_pooling_kernel(self) -> torch.Tensor:
+ def get_pooling_kernel(self) -> Tensor:
return self.bin_pooling_kernel.weight.detach()
def forward(self, input):
@@ -292,27 +293,27 @@ class DenseSIFTDescriptor(nn.Module):
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: torch.Tensor = spatial_gradient(input, 'diff')
+ grads: Tensor = spatial_gradient(input, 'diff')
# unpack the edges
- gx: torch.Tensor = grads[:, :, 0]
- gy: torch.Tensor = grads[:, :, 1]
- mag: torch.Tensor = torch.sqrt(gx * gx + gy * gy + self.eps)
- ori: torch.Tensor = torch.atan2(gy, gx + self.eps) + 2.0 * pi
- o_big: torch.Tensor = float(self.num_ang_bins) * ori / (2.0 * pi)
-
- bo0_big_: torch.Tensor = torch.floor(o_big)
- wo1_big_: torch.Tensor = o_big - bo0_big_
- bo0_big: torch.Tensor = bo0_big_ % self.num_ang_bins
- bo1_big: torch.Tensor = (bo0_big + 1) % self.num_ang_bins
- wo0_big: torch.Tensor = (1.0 - wo1_big_) * mag # type: ignore
- wo1_big: torch.Tensor = wo1_big_ * mag
+ 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 = torch.cat(ang_bins, dim=1)
+ ang_bins = concatenate(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)
diff --git a/kornia/filters/sobel.py b/kornia/filters/sobel.py
index ae63edb8c..08b59c83f 100644
--- a/kornia/filters/sobel.py
+++ b/kornia/filters/sobel.py
@@ -1,11 +1,12 @@
import torch
-import torch.nn as nn
import torch.nn.functional as F
+from kornia.core import Module, Tensor, pad
+
from .kernels import get_spatial_gradient_kernel2d, get_spatial_gradient_kernel3d, normalize_kernel2d
-def spatial_gradient(input: torch.Tensor, mode: str = 'sobel', order: int = 1, normalized: bool = True) -> torch.Tensor:
+def spatial_gradient(input: Tensor, mode: str = 'sobel', order: int = 1, normalized: bool = True) -> Tensor:
r"""Compute the first order image derivative in both x and y using a Sobel operator.
.. image:: _static/img/spatial_gradient.png
@@ -29,30 +30,30 @@ def spatial_gradient(input: torch.Tensor, mode: str = 'sobel', order: int = 1, n
>>> output.shape
torch.Size([1, 3, 2, 4, 4])
"""
- if not isinstance(input, torch.Tensor):
- raise TypeError(f"Input type is not a torch.Tensor. Got {type(input)}")
+ if not isinstance(input, Tensor):
+ raise TypeError(f"Input type is not a Tensor. Got {type(input)}")
if not len(input.shape) == 4:
raise ValueError(f"Invalid input shape, we expect BxCxHxW. Got: {input.shape}")
# allocate kernel
- kernel: torch.Tensor = get_spatial_gradient_kernel2d(mode, order)
+ kernel: Tensor = get_spatial_gradient_kernel2d(mode, order)
if normalized:
kernel = normalize_kernel2d(kernel)
# prepare kernel
b, c, h, w = input.shape
- tmp_kernel: torch.Tensor = kernel.to(input).detach()
+ tmp_kernel: Tensor = kernel.to(input).detach()
tmp_kernel = tmp_kernel.unsqueeze(1)
# Pad with "replicate for spatial dims, but with zeros for channel
spatial_pad = [kernel.size(1) // 2, kernel.size(1) // 2, kernel.size(2) // 2, kernel.size(2) // 2]
out_channels: int = 3 if order == 2 else 2
- padded_inp: torch.Tensor = F.pad(input.reshape(b * c, 1, h, w), spatial_pad, 'replicate')
+ padded_inp: Tensor = pad(input.reshape(b * c, 1, h, w), spatial_pad, 'replicate')
out = F.conv2d(padded_inp, tmp_kernel, groups=1, padding=0, stride=1)
return out.reshape(b, c, out_channels, h, w)
-def spatial_gradient3d(input: torch.Tensor, mode: str = 'diff', order: int = 1) -> torch.Tensor:
+def spatial_gradient3d(input: Tensor, mode: str = 'diff', order: int = 1) -> Tensor:
r"""Compute the first and second order volume derivative in x, y and d using a diff operator.
Args:
@@ -70,8 +71,8 @@ def spatial_gradient3d(input: torch.Tensor, mode: str = 'diff', order: int = 1)
>>> output.shape
torch.Size([1, 4, 3, 2, 4, 4])
"""
- if not isinstance(input, torch.Tensor):
- raise TypeError(f"Input type is not a torch.Tensor. Got {type(input)}")
+ if not isinstance(input, Tensor):
+ raise TypeError(f"Input type is not a Tensor. Got {type(input)}")
if not len(input.shape) == 5:
raise ValueError(f"Invalid input shape, we expect BxCxDxHxW. Got: {input.shape}")
@@ -80,7 +81,7 @@ def spatial_gradient3d(input: torch.Tensor, mode: str = 'diff', order: int = 1)
dtype = input.dtype
if (mode == 'diff') and (order == 1):
# we go for the special case implementation due to conv3d bad speed
- x: torch.Tensor = F.pad(input, 6 * [1], 'replicate')
+ x: Tensor = pad(input, 6 * [1], 'replicate')
center = slice(1, -1)
left = slice(0, -2)
right = slice(2, None)
@@ -92,13 +93,13 @@ def spatial_gradient3d(input: torch.Tensor, mode: str = 'diff', order: int = 1)
else:
# prepare kernel
# allocate kernel
- kernel: torch.Tensor = get_spatial_gradient_kernel3d(mode, order)
+ kernel: Tensor = get_spatial_gradient_kernel3d(mode, order)
- tmp_kernel: torch.Tensor = kernel.to(input).detach()
+ tmp_kernel: Tensor = kernel.to(input).detach()
tmp_kernel = tmp_kernel.repeat(c, 1, 1, 1, 1)
# convolve input tensor with grad kernel
- kernel_flip: torch.Tensor = tmp_kernel.flip(-3)
+ kernel_flip: Tensor = tmp_kernel.flip(-3)
# Pad with "replicate for spatial dims, but with zeros for channel
spatial_pad = [
@@ -110,13 +111,13 @@ def spatial_gradient3d(input: torch.Tensor, mode: str = 'diff', order: int = 1)
kernel.size(4) // 2,
]
out_ch: int = 6 if order == 2 else 3
- out = F.conv3d(F.pad(input, spatial_pad, 'replicate'), kernel_flip, padding=0, groups=c).view(
+ out = F.conv3d(pad(input, spatial_pad, 'replicate'), kernel_flip, padding=0, groups=c).view(
b, c, out_ch, d, h, w
)
return out
-def sobel(input: torch.Tensor, normalized: bool = True, eps: float = 1e-6) -> torch.Tensor:
+def sobel(input: Tensor, normalized: bool = True, eps: float = 1e-6) -> Tensor:
r"""Compute the Sobel operator and returns the magnitude per channel.
.. image:: _static/img/sobel.png
@@ -139,26 +140,26 @@ def sobel(input: torch.Tensor, normalized: bool = True, eps: float = 1e-6) -> to
>>> output.shape
torch.Size([1, 3, 4, 4])
"""
- if not isinstance(input, torch.Tensor):
- raise TypeError(f"Input type is not a torch.Tensor. Got {type(input)}")
+ if not isinstance(input, Tensor):
+ raise TypeError(f"Input type is not a Tensor. Got {type(input)}")
if not len(input.shape) == 4:
raise ValueError(f"Invalid input shape, we expect BxCxHxW. Got: {input.shape}")
# comput the x/y gradients
- edges: torch.Tensor = spatial_gradient(input, normalized=normalized)
+ edges: Tensor = spatial_gradient(input, normalized=normalized)
# unpack the edges
- gx: torch.Tensor = edges[:, :, 0]
- gy: torch.Tensor = edges[:, :, 1]
+ gx: Tensor = edges[:, :, 0]
+ gy: Tensor = edges[:, :, 1]
# compute gradient maginitude
- magnitude: torch.Tensor = torch.sqrt(gx * gx + gy * gy + eps)
+ magnitude: Tensor = torch.sqrt(gx * gx + gy * gy + eps)
return magnitude
-class SpatialGradient(nn.Module):
+class SpatialGradient(Module):
r"""Compute the first order image derivative in both x and y using a Sobel operator.
Args:
@@ -190,11 +191,11 @@ class SpatialGradient(nn.Module):
'order=' + str(self.order) + ', ' + 'normalized=' + str(self.normalized) + ', ' + 'mode=' + self.mode + ')'
)
- def forward(self, input: torch.Tensor) -> torch.Tensor:
+ def forward(self, input: Tensor) -> Tensor:
return spatial_gradient(input, self.mode, self.order, self.normalized)
-class SpatialGradient3d(nn.Module):
+class SpatialGradient3d(Module):
r"""Compute the first and second order volume derivative in x, y and d using a diff operator.
Args:
@@ -225,11 +226,11 @@ class SpatialGradient3d(nn.Module):
def __repr__(self) -> str:
return self.__class__.__name__ + '(' 'order=' + str(self.order) + ', ' + 'mode=' + self.mode + ')'
- def forward(self, input: torch.Tensor) -> torch.Tensor: # type: ignore
+ def forward(self, input: Tensor) -> Tensor:
return spatial_gradient3d(input, self.mode, self.order)
-class Sobel(nn.Module):
+class Sobel(Module):
r"""Compute the Sobel operator and returns the magnitude per channel.
Args:
@@ -256,5 +257,5 @@ class Sobel(nn.Module):
def __repr__(self) -> str:
return self.__class__.__name__ + '(' 'normalized=' + str(self.normalized) + ')'
- def forward(self, input: torch.Tensor) -> torch.Tensor:
+ def forward(self, input: Tensor) -> Tensor:
return sobel(input, self.normalized, self.eps)
diff --git a/kornia/geometry/camera/stereo.py b/kornia/geometry/camera/stereo.py
index 13bc8bfea..122bbfb80 100644
--- a/kornia/geometry/camera/stereo.py
+++ b/kornia/geometry/camera/stereo.py
@@ -1,5 +1,6 @@
import torch
+from kornia.core import Tensor, stack, zeros
from kornia.geometry.linalg import transform_points
from kornia.utils.grid import create_meshgrid
@@ -22,11 +23,11 @@ class StereoException(Exception):
final_msg = msg + doc_help
# type ignore because of mypy error:
# Too many arguments for "__init__" of "BaseException"
- super().__init__(final_msg, *args, **kwargs) # type: ignore
+ super().__init__(final_msg, *args, **kwargs)
class StereoCamera:
- def __init__(self, rectified_left_camera: torch.Tensor, rectified_right_camera: torch.Tensor):
+ def __init__(self, rectified_left_camera: Tensor, rectified_right_camera: Tensor):
r"""Class representing a horizontal stereo camera setup.
Args:
@@ -36,16 +37,16 @@ class StereoCamera:
of shape :math:`(B, 3, 4)`
"""
self._check_stereo_camera(rectified_left_camera, rectified_right_camera)
- self.rectified_left_camera: torch.Tensor = rectified_left_camera
- self.rectified_right_camera: torch.Tensor = rectified_right_camera
+ self.rectified_left_camera: Tensor = rectified_left_camera
+ self.rectified_right_camera: Tensor = rectified_right_camera
- self.device: torch.device = self.rectified_left_camera.device
- self.dtype: torch.dtype = self.rectified_left_camera.dtype
+ self.device = self.rectified_left_camera.device
+ self.dtype = self.rectified_left_camera.dtype
self._Q_matrix = self._init_Q_matrix()
@staticmethod
- def _check_stereo_camera(rectified_left_camera: torch.Tensor, rectified_right_camera: torch.Tensor):
+ def _check_stereo_camera(rectified_left_camera: Tensor, rectified_right_camera: Tensor):
r"""Utility function to ensure user specified correct camera matrices.
Args:
@@ -116,7 +117,7 @@ class StereoCamera:
return self.rectified_left_camera.shape[0]
@property
- def fx(self) -> torch.Tensor:
+ def fx(self) -> Tensor:
r"""Return the focal length in the x-direction.
Note that the focal lengths of the rectified left and right
@@ -128,7 +129,7 @@ class StereoCamera:
return self.rectified_left_camera[..., 0, 0]
@property
- def fy(self) -> torch.Tensor:
+ def fy(self) -> Tensor:
r"""Returns the focal length in the y-direction.
Note that the focal lengths of the rectified left and right
@@ -140,7 +141,7 @@ class StereoCamera:
return self.rectified_left_camera[..., 1, 1]
@property
- def cx_left(self) -> torch.Tensor:
+ def cx_left(self) -> Tensor:
r"""Return the x-coordinate of the principal point for the left camera.
Returns:
@@ -149,7 +150,7 @@ class StereoCamera:
return self.rectified_left_camera[..., 0, 2]
@property
- def cx_right(self) -> torch.Tensor:
+ def cx_right(self) -> Tensor:
r"""Return the x-coordinate of the principal point for the right camera.
Returns:
@@ -158,7 +159,7 @@ class StereoCamera:
return self.rectified_right_camera[..., 0, 2]
@property
- def cy(self) -> torch.Tensor:
+ def cy(self) -> Tensor:
r"""Return the y-coordinate of the principal point.
Note that the y-coordinate of the principal points
@@ -170,7 +171,7 @@ class StereoCamera:
return self.rectified_left_camera[..., 1, 2]
@property
- def tx(self) -> torch.Tensor:
+ def tx(self) -> Tensor:
r"""The horizontal baseline between the two cameras.
Returns:
@@ -179,7 +180,7 @@ class StereoCamera:
return -self.rectified_right_camera[..., 0, 3] / self.fx
@property
- def Q(self) -> torch.Tensor:
+ def Q(self) -> Tensor:
r"""The Q matrix of the horizontal stereo setup.
This matrix is used for reprojecting a disparity tensor to
@@ -191,14 +192,14 @@ class StereoCamera:
"""
return self._Q_matrix
- def _init_Q_matrix(self) -> torch.Tensor:
+ def _init_Q_matrix(self) -> Tensor:
r"""Initialized the Q matrix of the horizontal stereo setup. See the Q property.
Returns:
The Q matrix of shape :math:`(B, 4, 4)`.
"""
- Q = torch.zeros((self.batch_size, 4, 4), device=self.device, dtype=self.dtype)
- baseline: torch.Tensor = -self.tx
+ Q = zeros((self.batch_size, 4, 4), device=self.device, dtype=self.dtype)
+ baseline: Tensor = -self.tx
Q[:, 0, 0] = self.fy * baseline
Q[:, 0, 3] = -self.fy * self.cx_left * baseline
Q[:, 1, 1] = self.fx * baseline
@@ -208,7 +209,7 @@ class StereoCamera:
Q[:, 3, 3] = self.fy * (self.cx_left - self.cx_right) # NOTE: This is usually zero.
return Q
- def reproject_disparity_to_3D(self, disparity_tensor: torch.Tensor) -> torch.Tensor:
+ def reproject_disparity_to_3D(self, disparity_tensor: Tensor) -> Tensor:
r"""Reproject the disparity tensor to a 3D point cloud.
Args:
@@ -220,15 +221,15 @@ class StereoCamera:
return reproject_disparity_to_3D(disparity_tensor, self.Q)
-def _check_disparity_tensor(disparity_tensor: torch.Tensor):
+def _check_disparity_tensor(disparity_tensor: Tensor):
r"""Utility function to ensure correct user provided correct disparity tensor.
Args:
disparity_tensor: The disparity tensor of shape :math:`(B, 1, H, W)`.
"""
- if not isinstance(disparity_tensor, torch.Tensor):
+ if not isinstance(disparity_tensor, Tensor):
raise StereoException(
- f"Expected 'disparity_tensor' to be an instance of torch.Tensor but got {type(disparity_tensor)}."
+ f"Expected 'disparity_tensor' to be an instance of Tensor but got {type(disparity_tensor)}."
)
if len(disparity_tensor.shape) != 4:
@@ -247,15 +248,15 @@ def _check_disparity_tensor(disparity_tensor: torch.Tensor):
)
-def _check_Q_matrix(Q_matrix: torch.Tensor):
+def _check_Q_matrix(Q_matrix: Tensor):
r"""Utility function to ensure Q matrix is of correct form.
Args:
Q_matrix: The Q matrix for reprojecting disparity to a point cloud of shape :math:`(B, 4, 4)`
"""
- if not isinstance(Q_matrix, torch.Tensor):
- raise StereoException(f"Expected 'Q_matrix' to be an instance of torch.Tensor but got {type(Q_matrix)}.")
+ if not isinstance(Q_matrix, Tensor):
+ raise StereoException(f"Expected 'Q_matrix' to be an instance of Tensor but got {type(Q_matrix)}.")
if not len(Q_matrix.shape) == 3:
raise StereoException(f"Expected 'Q_matrix' to have 3 dimensions." f"Got {Q_matrix.shape}")
@@ -271,7 +272,7 @@ def _check_Q_matrix(Q_matrix: torch.Tensor):
)
-def reproject_disparity_to_3D(disparity_tensor: torch.Tensor, Q_matrix: torch.Tensor) -> torch.Tensor:
+def reproject_disparity_to_3D(disparity_tensor: Tensor, Q_matrix: Tensor) -> Tensor:
r"""Reproject the disparity tensor to a 3D point cloud.
Args:
@@ -292,7 +293,7 @@ def reproject_disparity_to_3D(disparity_tensor: torch.Tensor, Q_matrix: torch.Te
uv = uv.expand(batch_size, -1, -1, -1)
v, u = torch.unbind(uv, dim=-1)
v, u = torch.unsqueeze(v, -1), torch.unsqueeze(u, -1)
- uvd = torch.stack((u, v, disparity_tensor), 1).reshape(batch_size, 3, -1).permute(0, 2, 1)
+ uvd = stack((u, v, disparity_tensor), 1).reshape(batch_size, 3, -1).permute(0, 2, 1)
points = transform_points(Q_matrix, uvd).reshape(batch_size, rows, cols, 3)
# Final check that everything went well.
diff --git a/kornia/geometry/conversions.py b/kornia/geometry/conversions.py
index b1a490f77..d5c9d50fe 100644
--- a/kornia/geometry/conversions.py
+++ b/kornia/geometry/conversions.py
@@ -6,7 +6,7 @@ import torch
import torch.nn.functional as F
from kornia.constants import pi
-from kornia.core import Tensor, concatenate, stack, tensor
+from kornia.core import Tensor, concatenate, pad, stack, tensor, where
from kornia.testing import KORNIA_CHECK, KORNIA_CHECK_SHAPE
from kornia.utils.helpers import _torch_inverse_cast
@@ -176,7 +176,7 @@ def convert_points_from_homogeneous(points: Tensor, eps: float = 1e-8) -> Tensor
# follow the convention of opencv:
# https://github.com/opencv/opencv/pull/14411/files
mask: Tensor = torch.abs(z_vec) > eps
- scale = torch.where(mask, 1.0 / (z_vec + eps), torch.ones_like(z_vec))
+ scale = where(mask, 1.0 / (z_vec + eps), torch.ones_like(z_vec))
return scale * points[..., :-1]
@@ -200,11 +200,11 @@ def convert_points_to_homogeneous(points: Tensor) -> Tensor:
if len(points.shape) < 2:
raise ValueError(f"Input must be at least a 2D tensor. Got {points.shape}")
- return torch.nn.functional.pad(points, [0, 1], "constant", 1.0)
+ return pad(points, [0, 1], "constant", 1.0)
def _convert_affinematrix_to_homography_impl(A: Tensor) -> Tensor:
- H: Tensor = torch.nn.functional.pad(A, [0, 0, 0, 1], "constant", value=0.0)
+ H: Tensor = pad(A, [0, 0, 0, 1], "constant", value=0.0)
H[..., -1, -1] += 1.0
return H
@@ -420,7 +420,7 @@ def rotation_matrix_to_quaternion(
)
def safe_zero_division(numerator: Tensor, denominator: Tensor) -> Tensor:
- eps: float = torch.finfo(numerator.dtype).tiny # type: ignore
+ eps: float = torch.finfo(numerator.dtype).tiny
return numerator / torch.clamp(denominator, min=eps)
rotation_matrix_vec: Tensor = rotation_matrix.view(*rotation_matrix.shape[:-2], 9)
@@ -469,10 +469,10 @@ def rotation_matrix_to_quaternion(
return concatenate((qx, qy, qz, qw), dim=-1)
return concatenate((qw, qx, qy, qz), dim=-1)
- where_2 = torch.where(m11 > m22, cond_2(), cond_3())
- where_1 = torch.where((m00 > m11) & (m00 > m22), cond_1(), where_2)
+ where_2 = where(m11 > m22, cond_2(), cond_3())
+ where_1 = where((m00 > m11) & (m00 > m22), cond_1(), where_2)
- quaternion: Tensor = torch.where(trace > 0.0, trace_positive_cond(), where_1)
+ quaternion: Tensor = where(trace > 0.0, trace_positive_cond(), where_1)
return quaternion
@@ -649,13 +649,13 @@ def quaternion_to_angle_axis(quaternion: Tensor, order: QuaternionCoeffOrder = Q
sin_squared_theta: Tensor = q1 * q1 + q2 * q2 + q3 * q3
sin_theta: Tensor = torch.sqrt(sin_squared_theta)
- two_theta: Tensor = 2.0 * torch.where(
+ two_theta: Tensor = 2.0 * where(
cos_theta < 0.0, torch.atan2(-sin_theta, -cos_theta), torch.atan2(sin_theta, cos_theta)
)
k_pos: Tensor = two_theta / sin_theta
k_neg: Tensor = 2.0 * torch.ones_like(sin_theta)
- k: Tensor = torch.where(sin_squared_theta > 0.0, k_pos, k_neg)
+ k: Tensor = where(sin_squared_theta > 0.0, k_pos, k_neg)
angle_axis: Tensor = torch.zeros_like(quaternion)[..., :3]
angle_axis[..., 0] += q1 * k
@@ -837,8 +837,8 @@ def angle_axis_to_quaternion(angle_axis: Tensor, order: QuaternionCoeffOrder = Q
k_neg: Tensor = 0.5 * ones
k_pos: Tensor = torch.sin(half_theta) / theta
- k: Tensor = torch.where(mask, k_pos, k_neg)
- w: Tensor = torch.where(mask, torch.cos(half_theta), ones)
+ k: Tensor = where(mask, k_pos, k_neg)
+ w: Tensor = where(mask, torch.cos(half_theta), ones)
quaternion: Tensor = torch.zeros(size=(*angle_axis.shape[:-1], 4), dtype=angle_axis.dtype, device=angle_axis.device)
if order == QuaternionCoeffOrder.XYZW:
diff --git a/kornia/geometry/depth.py b/kornia/geometry/depth.py
index e94f8e64f..6d4181149 100644
--- a/kornia/geometry/depth.py
+++ b/kornia/geometry/depth.py
@@ -2,9 +2,9 @@
from typing import Union
import torch
-import torch.nn as nn
import torch.nn.functional as F
+from kornia.core import Module, Tensor, concatenate, tensor
from kornia.filters.sobel import spatial_gradient
from kornia.utils import create_meshgrid
@@ -15,7 +15,7 @@ from .linalg import compose_transformations, convert_points_to_homogeneous, inve
__all__ = ["depth_to_3d", "depth_to_normals", "warp_frame_depth", "depth_warp", "DepthWarper"]
-def depth_to_3d(depth: torch.Tensor, camera_matrix: torch.Tensor, normalize_points: bool = False) -> torch.Tensor:
+def depth_to_3d(depth: Tensor, camera_matrix: Tensor, normalize_points: bool = False) -> Tensor:
"""Compute a 3d point per pixel given its depth value and the camera intrinsics.
Args:
@@ -33,36 +33,36 @@ def depth_to_3d(depth: torch.Tensor, camera_matrix: torch.Tensor, normalize_poin
>>> depth_to_3d(depth, K).shape
torch.Size([1, 3, 4, 4])
"""
- if not isinstance(depth, torch.Tensor):
- raise TypeError(f"Input depht type is not a torch.Tensor. Got {type(depth)}.")
+ if not isinstance(depth, Tensor):
+ raise TypeError(f"Input depht type is not a Tensor. Got {type(depth)}.")
if not (len(depth.shape) == 4 and depth.shape[-3] == 1):
raise ValueError(f"Input depth musth have a shape (B, 1, H, W). Got: {depth.shape}")
- if not isinstance(camera_matrix, torch.Tensor):
- raise TypeError(f"Input camera_matrix type is not a torch.Tensor. " f"Got {type(camera_matrix)}.")
+ if not isinstance(camera_matrix, Tensor):
+ raise TypeError(f"Input camera_matrix type is not a Tensor. " f"Got {type(camera_matrix)}.")
if not (len(camera_matrix.shape) == 3 and camera_matrix.shape[-2:] == (3, 3)):
raise ValueError(f"Input camera_matrix must have a shape (B, 3, 3). " f"Got: {camera_matrix.shape}.")
# create base coordinates grid
_, _, height, width = depth.shape
- points_2d: torch.Tensor = create_meshgrid(height, width, normalized_coordinates=False) # 1xHxWx2
+ points_2d: Tensor = create_meshgrid(height, width, normalized_coordinates=False) # 1xHxWx2
points_2d = points_2d.to(depth.device).to(depth.dtype)
# depth should come in Bx1xHxW
- points_depth: torch.Tensor = depth.permute(0, 2, 3, 1) # 1xHxWx1
+ points_depth: Tensor = depth.permute(0, 2, 3, 1) # 1xHxWx1
# project pixels to camera frame
- camera_matrix_tmp: torch.Tensor = camera_matrix[:, None, None] # Bx1x1x3x3
- points_3d: torch.Tensor = unproject_points(
+ camera_matrix_tmp: Tensor = camera_matrix[:, None, None] # Bx1x1x3x3
+ points_3d: Tensor = unproject_points(
points_2d, points_depth, camera_matrix_tmp, normalize=normalize_points
) # BxHxWx3
return points_3d.permute(0, 3, 1, 2) # Bx3xHxW
-def depth_to_normals(depth: torch.Tensor, camera_matrix: torch.Tensor, normalize_points: bool = False) -> torch.Tensor:
+def depth_to_normals(depth: Tensor, camera_matrix: Tensor, normalize_points: bool = False) -> Tensor:
"""Compute the normal surface per pixel.
Args:
@@ -80,38 +80,34 @@ def depth_to_normals(depth: torch.Tensor, camera_matrix: torch.Tensor, normalize
>>> depth_to_normals(depth, K).shape
torch.Size([1, 3, 4, 4])
"""
- if not isinstance(depth, torch.Tensor):
- raise TypeError(f"Input depht type is not a torch.Tensor. Got {type(depth)}.")
+ if not isinstance(depth, Tensor):
+ raise TypeError(f"Input depht type is not a Tensor. Got {type(depth)}.")
if not (len(depth.shape) == 4 and depth.shape[-3] == 1):
raise ValueError(f"Input depth musth have a shape (B, 1, H, W). Got: {depth.shape}")
- if not isinstance(camera_matrix, torch.Tensor):
- raise TypeError(f"Input camera_matrix type is not a torch.Tensor. " f"Got {type(camera_matrix)}.")
+ if not isinstance(camera_matrix, Tensor):
+ raise TypeError(f"Input camera_matrix type is not a Tensor. " f"Got {type(camera_matrix)}.")
if not (len(camera_matrix.shape) == 3 and camera_matrix.shape[-2:] == (3, 3)):
raise ValueError(f"Input camera_matrix must have a shape (B, 3, 3). " f"Got: {camera_matrix.shape}.")
# compute the 3d points from depth
- xyz: torch.Tensor = depth_to_3d(depth, camera_matrix, normalize_points) # Bx3xHxW
+ xyz: Tensor = depth_to_3d(depth, camera_matrix, normalize_points) # Bx3xHxW
# compute the pointcloud spatial gradients
- gradients: torch.Tensor = spatial_gradient(xyz) # Bx3x2xHxW
+ gradients: Tensor = spatial_gradient(xyz) # Bx3x2xHxW
# compute normals
a, b = gradients[:, :, 0], gradients[:, :, 1] # Bx3xHxW
- normals: torch.Tensor = torch.cross(a, b, dim=1) # Bx3xHxW
+ normals: Tensor = torch.cross(a, b, dim=1) # Bx3xHxW
return F.normalize(normals, dim=1, p=2)
def warp_frame_depth(
- image_src: torch.Tensor,
- depth_dst: torch.Tensor,
- src_trans_dst: torch.Tensor,
- camera_matrix: torch.Tensor,
- normalize_points: bool = False,
-) -> torch.Tensor:
+ image_src: Tensor, depth_dst: Tensor, src_trans_dst: Tensor, camera_matrix: Tensor, normalize_points: bool = False
+) -> Tensor:
"""Warp a tensor from a source to destination frame by the depth in the destination.
Compute 3d points from the depth, transform them using given transformation, then project the point cloud to an
@@ -128,31 +124,31 @@ def warp_frame_depth(
Return:
the warped tensor in the source frame with shape :math:`(B,3,H,W)`.
"""
- if not isinstance(image_src, torch.Tensor):
- raise TypeError(f"Input image_src type is not a torch.Tensor. Got {type(image_src)}.")
+ if not isinstance(image_src, Tensor):
+ raise TypeError(f"Input image_src type is not a Tensor. Got {type(image_src)}.")
if not len(image_src.shape) == 4:
raise ValueError(f"Input image_src musth have a shape (B, D, H, W). Got: {image_src.shape}")
- if not isinstance(depth_dst, torch.Tensor):
- raise TypeError(f"Input depht_dst type is not a torch.Tensor. Got {type(depth_dst)}.")
+ if not isinstance(depth_dst, Tensor):
+ raise TypeError(f"Input depht_dst type is not a Tensor. Got {type(depth_dst)}.")
if not (len(depth_dst.shape) == 4 and depth_dst.shape[-3] == 1):
raise ValueError(f"Input depth_dst musth have a shape (B, 1, H, W). Got: {depth_dst.shape}")
- if not isinstance(src_trans_dst, torch.Tensor):
- raise TypeError(f"Input src_trans_dst type is not a torch.Tensor. " f"Got {type(src_trans_dst)}.")
+ if not isinstance(src_trans_dst, Tensor):
+ raise TypeError(f"Input src_trans_dst type is not a Tensor. " f"Got {type(src_trans_dst)}.")
if not (len(src_trans_dst.shape) == 3 and src_trans_dst.shape[-2:] == (4, 4)):
raise ValueError(f"Input src_trans_dst must have a shape (B, 4, 4). " f"Got: {src_trans_dst.shape}.")
- if not isinstance(camera_matrix, torch.Tensor):
- raise TypeError(f"Input camera_matrix type is not a torch.Tensor. " f"Got {type(camera_matrix)}.")
+ if not isinstance(camera_matrix, Tensor):
+ raise TypeError(f"Input camera_matrix type is not a Tensor. " f"Got {type(camera_matrix)}.")
if not (len(camera_matrix.shape) == 3 and camera_matrix.shape[-2:] == (3, 3)):
raise ValueError(f"Input camera_matrix must have a shape (B, 3, 3). " f"Got: {camera_matrix.shape}.")
# unproject source points to camera frame
- points_3d_dst: torch.Tensor = depth_to_3d(depth_dst, camera_matrix, normalize_points) # Bx3xHxW
+ points_3d_dst: Tensor = depth_to_3d(depth_dst, camera_matrix, normalize_points) # Bx3xHxW
# transform points from source to destination
points_3d_dst = points_3d_dst.permute(0, 2, 3, 1) # BxHxWx3
@@ -161,17 +157,17 @@ def warp_frame_depth(
points_3d_src = transform_points(src_trans_dst[:, None], points_3d_dst) # BxHxWx3
# project back to pixels
- camera_matrix_tmp: torch.Tensor = camera_matrix[:, None, None] # Bx1x1xHxW
- points_2d_src: torch.Tensor = project_points(points_3d_src, camera_matrix_tmp) # BxHxWx2
+ camera_matrix_tmp: Tensor = camera_matrix[:, None, None] # Bx1x1xHxW
+ points_2d_src: Tensor = project_points(points_3d_src, camera_matrix_tmp) # BxHxWx2
# normalize points between [-1 / 1]
height, width = depth_dst.shape[-2:]
- points_2d_src_norm: torch.Tensor = normalize_pixel_coordinates(points_2d_src, height, width) # BxHxWx2
+ points_2d_src_norm: Tensor = normalize_pixel_coordinates(points_2d_src, height, width) # BxHxWx2
- return F.grid_sample(image_src, points_2d_src_norm, align_corners=True) # type: ignore
+ return F.grid_sample(image_src, points_2d_src_norm, align_corners=True)
-class DepthWarper(nn.Module):
+class DepthWarper(Module):
r"""Warp a patch by depth.
.. math::
@@ -209,13 +205,13 @@ class DepthWarper(nn.Module):
# state members
self._pinhole_dst: PinholeCamera = pinhole_dst
self._pinhole_src: Union[None, PinholeCamera] = None
- self._dst_proj_src: Union[None, torch.Tensor] = None
+ self._dst_proj_src: Union[None, Tensor] = None
- self.grid: torch.Tensor = self._create_meshgrid(height, width)
+ self.grid: Tensor = self._create_meshgrid(height, width)
@staticmethod
- def _create_meshgrid(height: int, width: int) -> torch.Tensor:
- grid: torch.Tensor = create_meshgrid(height, width, normalized_coordinates=False) # 1xHxWx2
+ def _create_meshgrid(height: int, width: int) -> Tensor:
+ grid: Tensor = create_meshgrid(height, width, normalized_coordinates=False) # 1xHxWx2
return convert_points_to_homogeneous(grid) # append ones to last dim
def compute_projection_matrix(self, pinhole_src: PinholeCamera) -> 'DepthWarper':
@@ -231,13 +227,13 @@ class DepthWarper(nn.Module):
)
# compute the relative pose between the non reference and the reference
# camera frames.
- dst_trans_src: torch.Tensor = compose_transformations(
+ dst_trans_src: Tensor = compose_transformations(
self._pinhole_dst.extrinsics, inverse_transformation(pinhole_src.extrinsics)
)
# compute the projection matrix between the non reference cameras and
# the reference.
- dst_proj_src: torch.Tensor = torch.matmul(self._pinhole_dst.intrinsics, dst_trans_src)
+ dst_proj_src: Tensor = torch.matmul(self._pinhole_dst.intrinsics, dst_trans_src)
# update class members
self._pinhole_src = pinhole_src
@@ -248,16 +244,14 @@ class DepthWarper(nn.Module):
if self._dst_proj_src is None or self._pinhole_src is None:
raise ValueError("Please, call compute_projection_matrix.")
- point = torch.tensor(
- [[[x], [y], [invd], [1.0]]], device=self._dst_proj_src.device, dtype=self._dst_proj_src.dtype
- )
+ point = tensor([[[x], [y], [invd], [1.0]]], device=self._dst_proj_src.device, dtype=self._dst_proj_src.dtype)
flow = torch.matmul(self._dst_proj_src, point)
z = 1.0 / flow[:, 2]
x = flow[:, 0] * z
y = flow[:, 1] * z
- return torch.cat([x, y], 1)
+ return concatenate([x, y], 1)
- def compute_subpixel_step(self) -> torch.Tensor:
+ def compute_subpixel_step(self) -> Tensor:
"""Compute the required inverse depth step to achieve sub pixel accurate sampling of the depth cost volume,
per camera.
@@ -272,7 +266,7 @@ class DepthWarper(nn.Module):
# half pixel sampling, we're interested in the min for all cameras
return torch.min(0.5 / dxdd)
- def warp_grid(self, depth_src: torch.Tensor) -> torch.Tensor:
+ def warp_grid(self, depth_src: Tensor) -> Tensor:
"""Compute a grid for warping a given the depth from the reference pinhole camera.
The function `compute_projection_matrix` has to be called beforehand in order to have precomputed the relative
@@ -292,23 +286,23 @@ class DepthWarper(nn.Module):
dtype: torch.dtype = depth_src.dtype
# expand the base coordinate grid according to the input batch size
- pixel_coords: torch.Tensor = self.grid.to(device=device, dtype=dtype).expand(batch_size, -1, -1, -1) # BxHxWx3
+ pixel_coords: Tensor = self.grid.to(device=device, dtype=dtype).expand(batch_size, -1, -1, -1) # BxHxWx3
# reproject the pixel coordinates to the camera frame
- cam_coords_src: torch.Tensor = pixel2cam(
+ cam_coords_src: Tensor = pixel2cam(
depth_src, self._pinhole_src.intrinsics_inverse().to(device=device, dtype=dtype), pixel_coords
) # BxHxWx3
# reproject the camera coordinates to the pixel
- pixel_coords_src: torch.Tensor = cam2pixel(
+ pixel_coords_src: Tensor = cam2pixel(
cam_coords_src, self._dst_proj_src.to(device=device, dtype=dtype)
) # (B*N)xHxWx2
# normalize between -1 and 1 the coordinates
- pixel_coords_src_norm: torch.Tensor = normalize_pixel_coordinates(pixel_coords_src, self.height, self.width)
+ pixel_coords_src_norm: Tensor = normalize_pixel_coordinates(pixel_coords_src, self.height, self.width)
return pixel_coords_src_norm
- def forward(self, depth_src: torch.Tensor, patch_dst: torch.Tensor) -> torch.Tensor:
+ def forward(self, depth_src: Tensor, patch_dst: Tensor) -> Tensor:
"""Warp a tensor from destination frame to reference given the depth in the reference frame.
Args:
@@ -337,7 +331,7 @@ class DepthWarper(nn.Module):
"""
return F.grid_sample(
patch_dst,
- self.warp_grid(depth_src), # type: ignore
+ self.warp_grid(depth_src),
mode=self.mode,
padding_mode=self.padding_mode,
align_corners=self.align_corners,
@@ -347,8 +341,8 @@ class DepthWarper(nn.Module):
def depth_warp(
pinhole_dst: PinholeCamera,
pinhole_src: PinholeCamera,
- depth_src: torch.Tensor,
- patch_dst: torch.Tensor,
+ depth_src: Tensor,
+ patch_dst: Tensor,
height: int,
width: int,
align_corners: bool = True,
diff --git a/kornia/geometry/line.py b/kornia/geometry/line.py
index 05547174d..a034690d7 100644
--- a/kornia/geometry/line.py
+++ b/kornia/geometry/line.py
@@ -1,6 +1,6 @@
# kornia.geometry.line module inspired by Eigen::geometry::ParametrizedLine
# https://gitlab.com/libeigen/eigen/-/blob/master/Eigen/src/Geometry/ParametrizedLine.h
-from typing import Optional, Union
+from typing import Optional, Tuple, Union
import torch
@@ -131,7 +131,7 @@ class ParametrizedLine(Module):
# - intersection_point
# TODO: add tests, and possibly return a mask
- def intersect(self, plane: Hyperplane, eps: float = 1e-6) -> Tensor:
+ def intersect(self, plane: Hyperplane, eps: float = 1e-6) -> Tuple[Tensor, Tensor]:
"""Return the intersection point between the line and a given plane.
Args:
diff --git a/kornia/geometry/ransac.py b/kornia/geometry/ransac.py
index 22e2ece6d..90edf7a40 100644
--- a/kornia/geometry/ransac.py
+++ b/kornia/geometry/ransac.py
@@ -3,9 +3,8 @@ import math
from typing import Optional, Tuple
import torch
-import torch.nn as nn
-from kornia.core import Tensor
+from kornia.core import Device, Module, Tensor, zeros
from kornia.geometry import (
find_fundamental,
find_homography_dlt,
@@ -24,7 +23,7 @@ from kornia.testing import KORNIA_CHECK_SHAPE
__all__ = ["RANSAC"]
-class RANSAC(nn.Module):
+class RANSAC(Module):
"""Module for robust geometry estimation with RANSAC. https://en.wikipedia.org/wiki/Random_sample_consensus.
Args:
@@ -56,9 +55,9 @@ class RANSAC(nn.Module):
self.max_lo_iters = max_lo_iters
self.model_type = model_type
if model_type == 'homography':
- self.error_fn = oneway_transfer_error # type: ignore
- self.minimal_solver = find_homography_dlt # type: ignore
- self.polisher_solver = find_homography_dlt_iterated # type: ignore
+ self.error_fn = oneway_transfer_error
+ self.minimal_solver = find_homography_dlt
+ self.polisher_solver = find_homography_dlt_iterated
self.minimal_sample_size = 4
elif model_type == 'homography_from_linesegments':
self.error_fn = line_segment_transfer_error_one_way # type: ignore
@@ -75,9 +74,7 @@ class RANSAC(nn.Module):
else:
raise NotImplementedError(f"{model_type} is unknown. Try one of {self.supported_models}")
- def sample(
- self, sample_size: int, pop_size: int, batch_size: int, device: torch.device = torch.device('cpu')
- ) -> Tensor:
+ def sample(self, sample_size: int, pop_size: int, batch_size: int, device: Device = torch.device('cpu')) -> Tensor:
"""Minimal sampler, but unlike traditional RANSAC we sample in batches to get benefit of the parallel
processing, esp.
@@ -179,8 +176,8 @@ class RANSAC(nn.Module):
self.validate_inputs(kp1, kp2, weights)
best_score_total: float = float(self.minimal_sample_size)
num_tc: int = len(kp1)
- best_model_total = torch.zeros(3, 3, dtype=kp1.dtype, device=kp1.device)
- inliers_best_total: Tensor = torch.zeros(num_tc, 1, device=kp1.device, dtype=torch.bool)
+ best_model_total = zeros(3, 3, dtype=kp1.dtype, device=kp1.device)
+ inliers_best_total: Tensor = zeros(num_tc, 1, device=kp1.device, dtype=torch.bool)
for i in range(self.max_iter):
# Sample minimal samples in batch to estimate models
idxs = self.sample(self.minimal_sample_size, num_tc, self.batch_size, kp1.device)
diff --git a/kornia/geometry/subpix/nms.py b/kornia/geometry/subpix/nms.py
index 5c64a5caa..8357f2021 100644
--- a/kornia/geometry/subpix/nms.py
+++ b/kornia/geometry/subpix/nms.py
@@ -1,29 +1,30 @@
from typing import Tuple
import torch
-import torch.nn as nn
import torch.nn.functional as F
+from kornia.core import Module, Tensor, eye, pad, zeros
-def _get_nms_kernel2d(kx: int, ky: int) -> torch.Tensor:
+
+def _get_nms_kernel2d(kx: int, ky: int) -> Tensor:
"""Utility function, which returns neigh2channels conv kernel."""
numel: int = ky * kx
center: int = numel // 2
- weight = torch.eye(numel)
+ weight = eye(numel)
weight[center, center] = 0
return weight.view(numel, 1, ky, kx)
-def _get_nms_kernel3d(kd: int, ky: int, kx: int) -> torch.Tensor:
+def _get_nms_kernel3d(kd: int, ky: int, kx: int) -> Tensor:
"""Utility function, which returns neigh2channels conv kernel."""
numel: int = kd * ky * kx
center: int = numel // 2
- weight = torch.eye(numel)
+ weight = eye(numel)
weight[center, center] = 0
return weight.view(numel, 1, kd, ky, kx)
-class NonMaximaSuppression2d(nn.Module):
+class NonMaximaSuppression2d(Module):
r"""Apply non maxima suppression to filter."""
def __init__(self, kernel_size: Tuple[int, int]):
@@ -45,12 +46,12 @@ class NonMaximaSuppression2d(nn.Module):
ky, kx = kernel_size # we assume a cubic kernel
return (pad(ky), pad(ky), pad(kx), pad(kx))
- def forward(self, x: torch.Tensor, mask_only: bool = False) -> torch.Tensor: # type: ignore
+ def forward(self, x: Tensor, mask_only: bool = False) -> Tensor:
if len(x.shape) != 4:
raise AssertionError(x.shape)
B, CH, H, W = x.size()
# find local maximum values
- x_padded = F.pad(x, list(self.padding)[::-1], mode='replicate')
+ x_padded = pad(x, list(self.padding)[::-1], mode='replicate')
B, CH, HP, WP = x_padded.size()
max_non_center = (
@@ -64,7 +65,7 @@ class NonMaximaSuppression2d(nn.Module):
return x * (mask.to(x.dtype))
-class NonMaximaSuppression3d(nn.Module):
+class NonMaximaSuppression3d(Module):
r"""Apply non maxima suppression to filter."""
def __init__(self, kernel_size: Tuple[int, int, int]):
@@ -86,13 +87,13 @@ class NonMaximaSuppression3d(nn.Module):
kd, ky, kx = kernel_size # we assume a cubic kernel
return pad(kd), pad(kd), pad(ky), pad(ky), pad(kx), pad(kx)
- def forward(self, x: torch.Tensor, mask_only: bool = False) -> torch.Tensor: # type: ignore
+ def forward(self, x: Tensor, mask_only: bool = False) -> Tensor:
if len(x.shape) != 5:
raise AssertionError(x.shape)
# find local maximum values
B, CH, D, H, W = x.size()
if self.kernel_size == (3, 3, 3):
- mask = torch.zeros(B, CH, D, H, W, device=x.device, dtype=torch.bool)
+ mask = zeros(B, CH, D, H, W, device=x.device, dtype=torch.bool)
center = slice(1, -1)
left = slice(0, -2)
right = slice(2, None)
@@ -128,7 +129,7 @@ class NonMaximaSuppression3d(nn.Module):
else:
max_non_center = (
F.conv3d(
- F.pad(x, list(self.padding)[::-1], mode='replicate'),
+ pad(x, list(self.padding)[::-1], mode='replicate'),
self.kernel.repeat(CH, 1, 1, 1, 1).to(x.device, x.dtype),
stride=1,
groups=CH,
@@ -145,7 +146,7 @@ class NonMaximaSuppression3d(nn.Module):
# functional api
-def nms2d(input: torch.Tensor, kernel_size: Tuple[int, int], mask_only: bool = False) -> torch.Tensor:
+def nms2d(input: Tensor, kernel_size: Tuple[int, int], mask_only: bool = False) -> Tensor:
r"""Apply non maxima suppression to filter.
See :class:`~kornia.geometry.subpix.NonMaximaSuppression2d` for details.
@@ -153,7 +154,7 @@ def nms2d(input: torch.Tensor, kernel_size: Tuple[int, int], mask_only: bool = F
return NonMaximaSuppression2d(kernel_size)(input, mask_only)
-def nms3d(input: torch.Tensor, kernel_size: Tuple[int, int, int], mask_only: bool = False) -> torch.Tensor:
+def nms3d(input: Tensor, kernel_size: Tuple[int, int, int], mask_only: bool = False) -> Tensor:
r"""Apply non maxima suppression to filter.
See :class:`~kornia.feature.NonMaximaSuppression3d` for details.
diff --git a/kornia/geometry/subpix/spatial_soft_argmax.py b/kornia/geometry/subpix/spatial_soft_argmax.py
index 41a92fd1d..8650ec787 100644
--- a/kornia/geometry/subpix/spatial_soft_argmax.py
+++ b/kornia/geometry/subpix/spatial_soft_argmax.py
@@ -1,9 +1,9 @@
from typing import Tuple, Union
import torch
-import torch.nn as nn
import torch.nn.functional as F
+from kornia.core import Module, Tensor, concatenate, stack, tensor, zeros
from kornia.filters.sobel import spatial_gradient3d
from kornia.geometry.conversions import normalize_pixel_coordinates, normalize_pixel_coordinates3d
from kornia.utils import create_meshgrid, create_meshgrid3d
@@ -14,7 +14,7 @@ from .dsnt import spatial_expectation2d, spatial_softmax2d
from .nms import nms3d
-def _get_window_grid_kernel2d(h: int, w: int, device: torch.device = torch.device('cpu')) -> torch.Tensor:
+def _get_window_grid_kernel2d(h: int, w: int, device: torch.device = torch.device('cpu')) -> Tensor:
r"""Helper function, which generates a kernel to with window coordinates, residual to window center.
Args:
@@ -31,7 +31,7 @@ def _get_window_grid_kernel2d(h: int, w: int, device: torch.device = torch.devic
return conv_kernel
-def _get_center_kernel2d(h: int, w: int, device: torch.device = torch.device('cpu')) -> torch.Tensor:
+def _get_center_kernel2d(h: int, w: int, device: torch.device = torch.device('cpu')) -> Tensor:
r"""Helper function, which generates a kernel to return center coordinates, when applied with F.conv2d to 2d
coordinates grid.
@@ -43,7 +43,7 @@ def _get_center_kernel2d(h: int, w: int, device: torch.device = torch.device('cp
Returns:
conv_kernel [2x2xhxw].
"""
- center_kernel = torch.zeros(2, 2, h, w, device=device)
+ center_kernel = zeros(2, 2, h, w, device=device)
# If the size is odd, we have one pixel for center, if even - 2
if h % 2 != 0:
@@ -62,7 +62,7 @@ def _get_center_kernel2d(h: int, w: int, device: torch.device = torch.device('cp
return center_kernel
-def _get_center_kernel3d(d: int, h: int, w: int, device: torch.device = torch.device('cpu')) -> torch.Tensor:
+def _get_center_kernel3d(d: int, h: int, w: int, device: torch.device = torch.device('cpu')) -> Tensor:
r"""Helper function, which generates a kernel to return center coordinates, when applied with F.conv2d to 3d
coordinates grid.
@@ -75,7 +75,7 @@ def _get_center_kernel3d(d: int, h: int, w: int, device: torch.device = torch.de
Returns:
conv_kernel [3x3xdxhxw].
"""
- center_kernel = torch.zeros(3, 3, d, h, w, device=device)
+ center_kernel = zeros(3, 3, d, h, w, device=device)
# If the size is odd, we have one pixel for center, if even - 2
if h % 2 != 0:
h_i1 = h // 2
@@ -100,7 +100,7 @@ def _get_center_kernel3d(d: int, h: int, w: int, device: torch.device = torch.de
return center_kernel
-def _get_window_grid_kernel3d(d: int, h: int, w: int, device: torch.device = torch.device('cpu')) -> torch.Tensor:
+def _get_window_grid_kernel3d(d: int, h: int, w: int, device: torch.device = torch.device('cpu')) -> Tensor:
r"""Helper function, which generates a kernel to return coordinates, residual to window center.
Args:
@@ -116,13 +116,13 @@ def _get_window_grid_kernel3d(d: int, h: int, w: int, device: torch.device = tor
if d > 1:
z = torch.linspace(-1, 1, d, device=device).view(d, 1, 1, 1)
else: # only onr channel with index == 0
- z = torch.zeros(1, 1, 1, 1, device=device)
- grid3d = torch.cat([z.repeat(1, h, w, 1).contiguous(), grid2d.repeat(d, 1, 1, 1)], dim=3)
+ z = zeros(1, 1, 1, 1, device=device)
+ grid3d = concatenate([z.repeat(1, h, w, 1).contiguous(), grid2d.repeat(d, 1, 1, 1)], 3)
conv_kernel = grid3d.permute(3, 0, 1, 2).unsqueeze(1)
return conv_kernel
-class ConvSoftArgmax2d(nn.Module):
+class ConvSoftArgmax2d(Module):
r"""Module that calculates soft argmax 2d per window.
See :func:`~kornia.geometry.subpix.conv_soft_argmax2d` for details.
@@ -133,7 +133,7 @@ class ConvSoftArgmax2d(nn.Module):
kernel_size: Tuple[int, int] = (3, 3),
stride: Tuple[int, int] = (1, 1),
padding: Tuple[int, int] = (1, 1),
- temperature: Union[torch.Tensor, float] = torch.tensor(1.0),
+ temperature: Union[Tensor, float] = tensor(1.0),
normalized_coordinates: bool = True,
eps: float = 1e-8,
output_value: bool = False,
@@ -174,7 +174,7 @@ class ConvSoftArgmax2d(nn.Module):
+ ')'
)
- def forward(self, x: torch.Tensor): # type: ignore
+ def forward(self, x: Tensor):
return conv_soft_argmax2d(
x,
self.kernel_size,
@@ -187,7 +187,7 @@ class ConvSoftArgmax2d(nn.Module):
)
-class ConvSoftArgmax3d(nn.Module):
+class ConvSoftArgmax3d(Module):
r"""Module that calculates soft argmax 3d per window.
See :func:`~kornia.geometry.subpix.conv_soft_argmax3d` for details.
@@ -198,7 +198,7 @@ class ConvSoftArgmax3d(nn.Module):
kernel_size: Tuple[int, int, int] = (3, 3, 3),
stride: Tuple[int, int, int] = (1, 1, 1),
padding: Tuple[int, int, int] = (1, 1, 1),
- temperature: Union[torch.Tensor, float] = torch.tensor(1.0),
+ temperature: Union[Tensor, float] = tensor(1.0),
normalized_coordinates: bool = False,
eps: float = 1e-8,
output_value: bool = True,
@@ -245,7 +245,7 @@ class ConvSoftArgmax3d(nn.Module):
+ ')'
)
- def forward(self, x: torch.Tensor): # type: ignore
+ def forward(self, x: Tensor):
return conv_soft_argmax3d(
x,
self.kernel_size,
@@ -260,15 +260,15 @@ class ConvSoftArgmax3d(nn.Module):
def conv_soft_argmax2d(
- input: torch.Tensor,
+ input: Tensor,
kernel_size: Tuple[int, int] = (3, 3),
stride: Tuple[int, int] = (1, 1),
padding: Tuple[int, int] = (1, 1),
- temperature: Union[torch.Tensor, float] = torch.tensor(1.0),
+ temperature: Union[Tensor, float] = tensor(1.0),
normalized_coordinates: bool = True,
eps: float = 1e-8,
output_value: bool = False,
-) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]:
+) -> Union[Tensor, Tuple[Tensor, Tensor]]:
r"""Compute the convolutional spatial Soft-Argmax 2D over the windows of a given heatmap.
.. math::
@@ -310,7 +310,7 @@ def conv_soft_argmax2d(
>>> nms_coords, nms_val = conv_soft_argmax2d(input, (3,3), (2,2), (1,1), output_value=True)
"""
if not torch.is_tensor(input):
- raise TypeError(f"Input type is not a torch.Tensor. Got {type(input)}")
+ raise TypeError(f"Input type is not a Tensor. Got {type(input)}")
if not len(input.shape) == 4:
raise ValueError(f"Invalid input shape, we expect BxCxHxW. Got: {input.shape}")
@@ -324,8 +324,8 @@ def conv_soft_argmax2d(
dtype: torch.dtype = input.dtype
input = input.view(b * c, 1, h, w)
- center_kernel: torch.Tensor = _get_center_kernel2d(kx, ky, device).to(dtype)
- window_kernel: torch.Tensor = _get_window_grid_kernel2d(kx, ky, device).to(dtype)
+ center_kernel: Tensor = _get_center_kernel2d(kx, ky, device).to(dtype)
+ window_kernel: Tensor = _get_window_grid_kernel2d(kx, ky, device).to(dtype)
# applies exponential normalization trick
# https://timvieira.github.io/blog/post/2014/02/11/exp-normalize-trick/
@@ -347,13 +347,13 @@ def conv_soft_argmax2d(
# We need to output also coordinates
# Pooled window center coordinates
- grid_global: torch.Tensor = create_meshgrid(h, w, False, device).to(dtype).permute(0, 3, 1, 2)
+ grid_global: Tensor = create_meshgrid(h, w, False, device).to(dtype).permute(0, 3, 1, 2)
grid_global_pooled = F.conv2d(grid_global, center_kernel, stride=stride, padding=padding)
# Coordinates of maxima residual to window center
# prepare kernel
- coords_max: torch.Tensor = F.conv2d(x_exp, window_kernel, stride=stride, padding=padding)
+ coords_max: Tensor = F.conv2d(x_exp, window_kernel, stride=stride, padding=padding)
coords_max = coords_max / den.expand_as(coords_max)
coords_max = coords_max + grid_global_pooled.expand_as(coords_max)
@@ -373,16 +373,16 @@ def conv_soft_argmax2d(
def conv_soft_argmax3d(
- input: torch.Tensor,
+ input: Tensor,
kernel_size: Tuple[int, int, int] = (3, 3, 3),
stride: Tuple[int, int, int] = (1, 1, 1),
padding: Tuple[int, int, int] = (1, 1, 1),
- temperature: Union[torch.Tensor, float] = torch.tensor(1.0),
+ temperature: Union[Tensor, float] = tensor(1.0),
normalized_coordinates: bool = False,
eps: float = 1e-8,
output_value: bool = True,
strict_maxima_bonus: float = 0.0,
-) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]:
+) -> Union[Tensor, Tuple[Tensor, Tensor]]:
r"""Compute the convolutional spatial Soft-Argmax 3D over the windows of a given heatmap.
.. math::
@@ -430,7 +430,7 @@ def conv_soft_argmax3d(
>>> nms_coords, nms_val = conv_soft_argmax3d(input, (3, 3, 3), (1, 2, 2), (0, 1, 1))
"""
if not torch.is_tensor(input):
- raise TypeError(f"Input type is not a torch.Tensor. Got {type(input)}")
+ raise TypeError(f"Input type is not a Tensor. Got {type(input)}")
if not len(input.shape) == 5:
raise ValueError(f"Invalid input shape, we expect BxCxDxHxW. Got: {input.shape}")
@@ -444,8 +444,8 @@ def conv_soft_argmax3d(
dtype: torch.dtype = input.dtype
input = input.view(b * c, 1, d, h, w)
- center_kernel: torch.Tensor = _get_center_kernel3d(kx, ky, kz, device).to(dtype)
- window_kernel: torch.Tensor = _get_window_grid_kernel3d(kx, ky, kz, device).to(dtype)
+ center_kernel: Tensor = _get_center_kernel3d(kx, ky, kz, device).to(dtype)
+ window_kernel: Tensor = _get_window_grid_kernel3d(kx, ky, kz, device).to(dtype)
# applies exponential normalization trick
# https://timvieira.github.io/blog/post/2014/02/11/exp-normalize-trick/
@@ -462,13 +462,13 @@ def conv_soft_argmax3d(
# We need to output also coordinates
# Pooled window center coordinates
- grid_global: torch.Tensor = create_meshgrid3d(d, h, w, False, device=device).to(dtype).permute(0, 4, 1, 2, 3)
+ grid_global: Tensor = create_meshgrid3d(d, h, w, False, device=device).to(dtype).permute(0, 4, 1, 2, 3)
grid_global_pooled = F.conv3d(grid_global, center_kernel, stride=stride, padding=padding)
# Coordinates of maxima residual to window center
# prepare kernel
- coords_max: torch.Tensor = F.conv3d(x_exp, window_kernel, stride=stride, padding=padding)
+ coords_max: Tensor = F.conv3d(x_exp, window_kernel, stride=stride, padding=padding)
coords_max = coords_max / den.expand_as(coords_max)
coords_max = coords_max + grid_global_pooled.expand_as(coords_max)
@@ -493,7 +493,7 @@ def conv_soft_argmax3d(
in_levels: int = input.size(2)
out_levels: int = x_softmaxpool.size(2)
skip_levels: int = (in_levels - out_levels) // 2
- strict_maxima: torch.Tensor = F.avg_pool3d(nms3d(input, kernel_size), 1, stride, 0)
+ strict_maxima: Tensor = F.avg_pool3d(nms3d(input, kernel_size), 1, stride, 0)
strict_maxima = strict_maxima[:, :, skip_levels : out_levels - skip_levels]
x_softmaxpool *= 1.0 + strict_maxima_bonus * strict_maxima
x_softmaxpool = x_softmaxpool.view(b, c, x_softmaxpool.size(2), x_softmaxpool.size(3), x_softmaxpool.size(4))
@@ -501,8 +501,8 @@ def conv_soft_argmax3d(
def spatial_soft_argmax2d(
- input: torch.Tensor, temperature: torch.Tensor = torch.tensor(1.0), normalized_coordinates: bool = True
-) -> torch.Tensor:
+ input: Tensor, temperature: Tensor = tensor(1.0), normalized_coordinates: bool = True
+) -> Tensor:
r"""Compute the Spatial Soft-Argmax 2D of a given input heatmap.
Args:
@@ -523,20 +523,20 @@ def spatial_soft_argmax2d(
>>> spatial_soft_argmax2d(input, normalized_coordinates=False)
tensor([[[1.0000, 1.0000]]])
"""
- input_soft: torch.Tensor = spatial_softmax2d(input, temperature)
- output: torch.Tensor = spatial_expectation2d(input_soft, normalized_coordinates)
+ input_soft: Tensor = spatial_softmax2d(input, temperature)
+ output: Tensor = spatial_expectation2d(input_soft, normalized_coordinates)
return output
-class SpatialSoftArgmax2d(nn.Module):
+class SpatialSoftArgmax2d(Module):
r"""Compute the Spatial Soft-Argmax 2D of a given heatmap.
See :func:`~kornia.geometry.subpix.spatial_soft_argmax2d` for details.
"""
- def __init__(self, temperature: torch.Tensor = torch.tensor(1.0), normalized_coordinates: bool = True) -> None:
+ def __init__(self, temperature: Tensor = tensor(1.0), normalized_coordinates: bool = True) -> None:
super().__init__()
- self.temperature: torch.Tensor = temperature
+ self.temperature: Tensor = temperature
self.normalized_coordinates: bool = normalized_coordinates
def __repr__(self) -> str:
@@ -550,13 +550,11 @@ class SpatialSoftArgmax2d(nn.Module):
+ ')'
)
- def forward(self, input: torch.Tensor) -> torch.Tensor:
+ def forward(self, input: Tensor) -> Tensor:
return spatial_soft_argmax2d(input, self.temperature, self.normalized_coordinates)
-def conv_quad_interp3d(
- input: torch.Tensor, strict_maxima_bonus: float = 10.0, eps: float = 1e-7
-) -> Tuple[torch.Tensor, torch.Tensor]:
+def conv_quad_interp3d(input: Tensor, strict_maxima_bonus: float = 10.0, eps: float = 1e-7) -> Tuple[Tensor, Tensor]:
r"""Compute the single iteration of quadratic interpolation of the extremum (max or min).
Args:
@@ -588,20 +586,20 @@ def conv_quad_interp3d(
>>> nms_coords, nms_val = conv_quad_interp3d(input, 1.0)
"""
if not torch.is_tensor(input):
- raise TypeError(f"Input type is not a torch.Tensor. Got {type(input)}")
+ raise TypeError(f"Input type is not a Tensor. Got {type(input)}")
if not len(input.shape) == 5:
raise ValueError(f"Invalid input shape, we expect BxCxDxHxW. Got: {input.shape}")
B, CH, D, H, W = input.shape
- grid_global: torch.Tensor = create_meshgrid3d(D, H, W, False, device=input.device).permute(0, 4, 1, 2, 3)
+ grid_global: Tensor = create_meshgrid3d(D, H, W, False, device=input.device).permute(0, 4, 1, 2, 3)
grid_global = grid_global.to(input.dtype)
# to determine the location we are solving system of linear equations Ax = b, where b is 1st order gradient
# and A is Hessian matrix
- b: torch.Tensor = spatial_gradient3d(input, order=1, mode='diff') #
+ b: Tensor = spatial_gradient3d(input, order=1, mode='diff') #
b = b.permute(0, 1, 3, 4, 5, 2).reshape(-1, 3, 1)
- A: torch.Tensor = spatial_gradient3d(input, order=2, mode='diff')
+ A: Tensor = spatial_gradient3d(input, order=2, mode='diff')
A = A.permute(0, 1, 3, 4, 5, 2).reshape(-1, 6)
dxx = A[..., 0]
dyy = A[..., 1]
@@ -610,37 +608,37 @@ def conv_quad_interp3d(
dys = 0.25 * A[..., 4] # normalization to match OpenCV implementation
dxs = 0.25 * A[..., 5] # normalization to match OpenCV implementation
- Hes = torch.stack([dxx, dxy, dxs, dxy, dyy, dys, dxs, dys, dss], dim=-1).view(-1, 3, 3)
+ Hes = stack([dxx, dxy, dxs, dxy, dyy, dys, dxs, dys, dss], -1).view(-1, 3, 3)
if not torch_version_geq(1, 10):
# The following is needed to avoid singular cases
Hes += torch.rand(Hes[0].size(), device=Hes.device).abs()[None] * eps
- nms_mask: torch.Tensor = nms3d(input, (3, 3, 3), True)
- x_solved: torch.Tensor = torch.zeros_like(b)
+ nms_mask: Tensor = nms3d(input, (3, 3, 3), True)
+ x_solved: Tensor = torch.zeros_like(b)
x_solved_masked, _, solved_correctly = safe_solve_with_mask(b[nms_mask.view(-1)], Hes[nms_mask.view(-1)])
# Kill those points, where we cannot solve
new_nms_mask = nms_mask.masked_scatter(nms_mask, solved_correctly)
x_solved.masked_scatter_(new_nms_mask.view(-1, 1, 1), x_solved_masked[solved_correctly])
- dx: torch.Tensor = -x_solved
+ dx: Tensor = -x_solved
# Ignore ones, which are far from window center
mask1 = dx.abs().max(dim=1, keepdim=True)[0] > 0.7
dx.masked_fill_(mask1.expand_as(dx), 0)
- dy: torch.Tensor = 0.5 * torch.bmm(b.permute(0, 2, 1), dx)
+ dy: Tensor = 0.5 * torch.bmm(b.permute(0, 2, 1), dx)
y_max = input + dy.view(B, CH, D, H, W)
if strict_maxima_bonus > 0:
y_max += strict_maxima_bonus * new_nms_mask.to(input.dtype)
- dx_res: torch.Tensor = dx.flip(1).reshape(B, CH, D, H, W, 3).permute(0, 1, 5, 2, 3, 4)
- coords_max: torch.Tensor = grid_global.repeat(B, 1, 1, 1, 1).unsqueeze(1)
+ dx_res: Tensor = dx.flip(1).reshape(B, CH, D, H, W, 3).permute(0, 1, 5, 2, 3, 4)
+ coords_max: Tensor = grid_global.repeat(B, 1, 1, 1, 1).unsqueeze(1)
coords_max = coords_max + dx_res
return coords_max, y_max
-class ConvQuadInterp3d(nn.Module):
+class ConvQuadInterp3d(Module):
r"""Calculate soft argmax 3d per window.
See :func:`~kornia.geometry.subpix.conv_quad_interp3d` for details.
@@ -655,5 +653,5 @@ class ConvQuadInterp3d(nn.Module):
def __repr__(self) -> str:
return self.__class__.__name__ + '(' + 'strict_maxima_bonus=' + str(self.strict_maxima_bonus) + ')'
- def forward(self, x: torch.Tensor): # type: ignore
+ def forward(self, x: Tensor):
return conv_quad_interp3d(x, self.strict_maxima_bonus, self.eps)
diff --git a/kornia/geometry/transform/crop2d.py b/kornia/geometry/transform/crop2d.py
index 8daf575da..d9360edb4 100644
--- a/kornia/geometry/transform/crop2d.py
+++ b/kornia/geometry/transform/crop2d.py
@@ -1,8 +1,8 @@
from typing import Optional, Tuple
import torch
-import torch.nn.functional as F
+from kornia.core import Tensor, as_tensor, pad, tensor
from kornia.geometry.bbox import infer_bbox_shape, validate_bbox
from .affwarp import resize
@@ -12,17 +12,17 @@ __all__ = ["crop_and_resize", "crop_by_boxes", "crop_by_transform_mat", "crop_by
def crop_and_resize(
- tensor: torch.Tensor,
- boxes: torch.Tensor,
+ input_tensor: Tensor,
+ boxes: Tensor,
size: Tuple[int, int],
mode: str = 'bilinear',
padding_mode: str = 'zeros',
align_corners: bool = True,
-) -> torch.Tensor:
+) -> Tensor:
r"""Extract crops from 2D images (4D tensor) and resize given a bounding box.
Args:
- tensor: the 2D image tensor with shape (B, C, H, W).
+ input_tensor: the 2D image tensor with shape (B, C, H, W).
boxes : a tensor containing the coordinates of the bounding boxes to be extracted.
The tensor must have the shape of Bx4x2, where each box is defined in the following (clockwise)
order: top-left, top-right, bottom-right and bottom-left. The coordinates must be in the x, y order.
@@ -36,7 +36,7 @@ def crop_and_resize(
align_corners: mode for grid_generation.
Returns:
- torch.Tensor: tensor containing the patches with shape BxCxN1xN2.
+ Tensor: tensor containing the patches with shape BxCxN1xN2.
Example:
>>> input = torch.tensor([[[
@@ -55,45 +55,47 @@ def crop_and_resize(
tensor([[[[ 6., 7.],
[10., 11.]]]])
"""
- if not isinstance(tensor, torch.Tensor):
- raise TypeError(f"Input tensor type is not a torch.Tensor. Got {type(tensor)}")
+ if not isinstance(input_tensor, Tensor):
+ raise TypeError(f"Input tensor type is not a Tensor. Got {type(input_tensor)}")
- if not isinstance(boxes, torch.Tensor):
- raise TypeError(f"Input boxes type is not a torch.Tensor. Got {type(boxes)}")
+ if not isinstance(boxes, Tensor):
+ raise TypeError(f"Input boxes type is not a Tensor. Got {type(boxes)}")
if not isinstance(size, (tuple, list)) and len(size) == 2:
raise ValueError(f"Input size must be a tuple/list of length 2. Got {size}")
- if len(tensor.shape) != 4:
- raise AssertionError(f"Only tensor with shape (B, C, H, W) supported. Got {tensor.shape}.")
+ if len(input_tensor.shape) != 4:
+ raise AssertionError(f"Only tensor with shape (B, C, H, W) supported. Got {input_tensor.shape}.")
# unpack input data
dst_h, dst_w = size
# [x, y] origin
# top-left, top-right, bottom-right, bottom-left
- points_src: torch.Tensor = boxes.to(tensor)
+ points_src = boxes.to(input_tensor)
# [x, y] destination
# top-left, top-right, bottom-right, bottom-left
- points_dst: torch.Tensor = torch.tensor(
- [[[0, 0], [dst_w - 1, 0], [dst_w - 1, dst_h - 1], [0, dst_h - 1]]], device=tensor.device, dtype=tensor.dtype
+ points_dst = tensor(
+ [[[0, 0], [dst_w - 1, 0], [dst_w - 1, dst_h - 1], [0, dst_h - 1]]],
+ device=input_tensor.device,
+ dtype=input_tensor.dtype,
).expand(points_src.shape[0], -1, -1)
- return crop_by_boxes(tensor, points_src, points_dst, mode, padding_mode, align_corners)
+ return crop_by_boxes(input_tensor, points_src, points_dst, mode, padding_mode, align_corners)
def center_crop(
- tensor: torch.Tensor,
+ input_tensor: Tensor,
size: Tuple[int, int],
mode: str = 'bilinear',
padding_mode: str = 'zeros',
align_corners: bool = True,
-) -> torch.Tensor:
+) -> Tensor:
r"""Crop the 2D images (4D tensor) from the center.
Args:
- tensor: the 2D image tensor with shape (B, C, H, W).
+ input_tensor: the 2D image tensor with shape (B, C, H, W).
size: a tuple with the expected height and width
of the output patch.
mode: interpolation mode to calculate output values
@@ -116,18 +118,18 @@ def center_crop(
tensor([[[[ 5., 6., 7., 8.],
[ 9., 10., 11., 12.]]]])
"""
- if not isinstance(tensor, torch.Tensor):
- raise TypeError(f"Input tensor type is not a torch.Tensor. Got {type(tensor)}")
+ if not isinstance(input_tensor, Tensor):
+ raise TypeError(f"Input tensor type is not a Tensor. Got {type(input_tensor)}")
if not isinstance(size, (tuple, list)) and len(size) == 2:
raise ValueError(f"Input size must be a tuple/list of length 2. Got {size}")
- if len(tensor.shape) != 4:
- raise AssertionError(f"Only tensor with shape (B, C, H, W) supported. Got {tensor.shape}.")
+ if len(input_tensor.shape) != 4:
+ raise AssertionError(f"Only tensor with shape (B, C, H, W) supported. Got {input_tensor.shape}.")
# unpack input sizes
dst_h, dst_w = size
- src_h, src_w = tensor.shape[-2:]
+ src_h, src_w = input_tensor.shape[-2:]
# compute start/end offsets
dst_h_half: float = dst_h / 2
@@ -143,30 +145,32 @@ def center_crop(
# [y, x] origin
# top-left, top-right, bottom-right, bottom-left
- points_src: torch.Tensor = torch.tensor(
+ points_src: Tensor = tensor(
[[[start_x, start_y], [end_x, start_y], [end_x, end_y], [start_x, end_y]]],
- device=tensor.device,
- dtype=tensor.dtype,
+ device=input_tensor.device,
+ dtype=input_tensor.dtype,
)
# [y, x] destination
# top-left, top-right, bottom-right, bottom-left
- points_dst: torch.Tensor = torch.tensor(
- [[[0, 0], [dst_w - 1, 0], [dst_w - 1, dst_h - 1], [0, dst_h - 1]]], device=tensor.device, dtype=tensor.dtype
+ points_dst: Tensor = tensor(
+ [[[0, 0], [dst_w - 1, 0], [dst_w - 1, dst_h - 1], [0, dst_h - 1]]],
+ device=input_tensor.device,
+ dtype=input_tensor.dtype,
).expand(points_src.shape[0], -1, -1)
- return crop_by_boxes(tensor, points_src, points_dst, mode, padding_mode, align_corners)
+ return crop_by_boxes(input_tensor, points_src, points_dst, mode, padding_mode, align_corners)
def crop_by_boxes(
- tensor: torch.Tensor,
- src_box: torch.Tensor,
- dst_box: torch.Tensor,
+ input_tensor: Tensor,
+ src_box: Tensor,
+ dst_box: Tensor,
mode: str = 'bilinear',
padding_mode: str = 'zeros',
align_corners: bool = True,
validate_boxes: bool = True,
-) -> torch.Tensor:
+) -> Tensor:
"""Perform crop transform on 2D images (4D tensor) given two bounding boxes.
Given an input tensor, this function selected the interested areas by the provided bounding boxes (src_box).
@@ -175,7 +179,7 @@ def crop_by_boxes(
in a batch must be rectangles with same width and height.
Args:
- tensor: the 2D image tensor with shape (B, C, H, W).
+ input_tensor: the 2D image tensor with shape (B, C, H, W).
src_box: a tensor with shape (B, 4, 2) containing the coordinates of the bounding boxes
to be extracted. The tensor must have the shape of Bx4x2, where each box is defined in the clockwise
order: top-left, top-right, bottom-right and bottom-left. The coordinates must be in x, y order.
@@ -190,7 +194,7 @@ def crop_by_boxes(
validate_boxes: flag to perform validation on boxes.
Returns:
- torch.Tensor: the output tensor with patches.
+ Tensor: the output tensor with patches.
Examples:
>>> input = torch.arange(16, dtype=torch.float32).reshape((1, 1, 4, 4))
@@ -218,14 +222,14 @@ def crop_by_boxes(
validate_bbox(src_box)
validate_bbox(dst_box)
- if len(tensor.shape) != 4:
- raise AssertionError(f"Only tensor with shape (B, C, H, W) supported. Got {tensor.shape}.")
+ if len(input_tensor.shape) != 4:
+ raise AssertionError(f"Only tensor with shape (B, C, H, W) supported. Got {input_tensor.shape}.")
# compute transformation between points and warp
# Note: Tensor.dtype must be float. "solve_cpu" not implemented for 'Long'
- dst_trans_src: torch.Tensor = get_perspective_transform(src_box.to(tensor), dst_box.to(tensor))
+ dst_trans_src: Tensor = get_perspective_transform(src_box.to(input_tensor), dst_box.to(input_tensor))
- bbox: Tuple[torch.Tensor, torch.Tensor] = infer_bbox_shape(dst_box)
+ bbox: Tuple[Tensor, Tensor] = infer_bbox_shape(dst_box)
if not ((bbox[0] == bbox[0][0]).all() and (bbox[1] == bbox[1][0]).all()):
raise AssertionError(
f"Cropping height, width and depth must be exact same in a batch. "
@@ -236,22 +240,22 @@ def crop_by_boxes(
w_out: int = int(bbox[1][0].item())
return crop_by_transform_mat(
- tensor, dst_trans_src, (h_out, w_out), mode=mode, padding_mode=padding_mode, align_corners=align_corners
+ input_tensor, dst_trans_src, (h_out, w_out), mode=mode, padding_mode=padding_mode, align_corners=align_corners
)
def crop_by_transform_mat(
- tensor: torch.Tensor,
- transform: torch.Tensor,
+ input_tensor: Tensor,
+ transform: Tensor,
out_size: Tuple[int, int],
mode: str = 'bilinear',
padding_mode: str = 'zeros',
align_corners: bool = True,
-) -> torch.Tensor:
+) -> Tensor:
"""Perform crop transform on 2D images (4D tensor) given a perspective transformation matrix.
Args:
- tensor: the 2D image tensor with shape (B, C, H, W).
+ input_tensor: the 2D image tensor with shape (B, C, H, W).
transform: a perspective transformation matrix with shape (B, 3, 3).
out_size: size of the output image (height, width).
mode: interpolation mode to calculate output values
@@ -264,24 +268,31 @@ def crop_by_transform_mat(
the output tensor with patches.
"""
# simulate broadcasting
- dst_trans_src = torch.as_tensor(transform.expand(tensor.shape[0], -1, -1), device=tensor.device, dtype=tensor.dtype)
+ dst_trans_src = as_tensor(
+ transform.expand(input_tensor.shape[0], -1, -1), device=input_tensor.device, dtype=input_tensor.dtype
+ )
- patches: torch.Tensor = warp_affine(
- tensor, dst_trans_src[:, :2, :], out_size, mode=mode, padding_mode=padding_mode, align_corners=align_corners
+ patches: Tensor = warp_affine(
+ input_tensor,
+ dst_trans_src[:, :2, :],
+ out_size,
+ mode=mode,
+ padding_mode=padding_mode,
+ align_corners=align_corners,
)
return patches
def crop_by_indices(
- input: torch.Tensor,
- src_box: torch.Tensor,
+ input_tensor: Tensor,
+ src_box: Tensor,
size: Optional[Tuple] = None,
interpolation: str = 'bilinear',
align_corners: Optional[bool] = None,
antialias: bool = False,
shape_compensation: str = "resize",
-) -> torch.Tensor:
+) -> Tensor:
"""Crop tensors with naive indices.
Args:
@@ -300,8 +311,8 @@ def crop_by_indices(
shape_compensation: if the cropped slice sizes are not exactly align `size`, the image can either be padded
or resized.
"""
- B, C, _, _ = input.shape
- src = torch.as_tensor(src_box, device=input.device, dtype=torch.long)
+ B, C, _, _ = input_tensor.shape
+ src = as_tensor(src_box, device=input_tensor.device, dtype=torch.long)
x1 = src[:, 0, 0]
x2 = src[:, 1, 0] + 1
y1 = src[:, 0, 1]
@@ -314,7 +325,7 @@ def crop_by_indices(
== len(y2.unique(sorted=False))
== 1
):
- out = input[..., y1[0] : y2[0], x1[0] : x2[0]] # type:ignore
+ out = input_tensor[..., y1[0] : y2[0], x1[0] : x2[0]] # type: ignore[misc]
if size is not None and out.shape[-2:] != size:
return resize(
out, size, interpolation=interpolation, align_corners=align_corners, side="short", antialias=antialias
@@ -323,14 +334,14 @@ def crop_by_indices(
if size is None:
h, w = infer_bbox_shape(src)
size = h.unique(sorted=False), w.unique(sorted=False)
- out = torch.empty(B, C, *size, device=input.device, dtype=input.dtype)
+ 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[i : i + 1, :, y1[i] : y2[i], x1[i] : x2[i]] # type: ignore[misc]
+ _out = input_tensor[i : i + 1, :, y1[i] : y2[i], x1[i] : x2[i]] # type: ignore[misc]
if _out.shape[-2:] != size:
if shape_compensation == "resize":
out[i] = resize(
- _out, # type:ignore
+ _out,
size,
interpolation=interpolation,
align_corners=align_corners,
@@ -338,7 +349,7 @@ def crop_by_indices(
antialias=antialias,
)
else:
- out[i] = F.pad(_out, [0, size[1] - _out.shape[-1], 0, size[0] - _out.shape[-2]])
+ out[i] = pad(_out, [0, size[1] - _out.shape[-1], 0, size[0] - _out.shape[-2]])
else:
- out[i] = _out # type:ignore
+ out[i] = _out
return out
diff --git a/kornia/geometry/transform/flips.py b/kornia/geometry/transform/flips.py
index cd2dcae01..eae60eea0 100644
--- a/kornia/geometry/transform/flips.py
+++ b/kornia/geometry/transform/flips.py
@@ -1,10 +1,11 @@
import torch
-import torch.nn as nn
+
+from kornia.core import Module, Tensor
__all__ = ["Vflip", "Hflip", "Rot180", "rot180", "hflip", "vflip"]
-class Vflip(nn.Module):
+class Vflip(Module):
r"""Vertically flip a tensor image or a batch of tensor images.
Input must be a tensor of shape (C, H, W) or a batch of tensors :math:`(*, C, H, W)`.
@@ -28,14 +29,14 @@ class Vflip(nn.Module):
[0., 0., 0.]]]])
"""
- def forward(self, input: torch.Tensor) -> torch.Tensor: # type: ignore
+ def forward(self, input: Tensor) -> Tensor:
return vflip(input)
def __repr__(self):
return self.__class__.__name__
-class Hflip(nn.Module):
+class Hflip(Module):
r"""Horizontally flip a tensor image or a batch of tensor images.
Input must be a tensor of shape (C, H, W) or a batch of tensors :math:`(*, C, H, W)`.
@@ -59,14 +60,14 @@ class Hflip(nn.Module):
[1., 1., 0.]]]])
"""
- def forward(self, input: torch.Tensor) -> torch.Tensor: # type: ignore
+ def forward(self, input: Tensor) -> Tensor:
return hflip(input)
def __repr__(self):
return self.__class__.__name__
-class Rot180(nn.Module):
+class Rot180(Module):
r"""Rotate a tensor image or a batch of tensor images 180 degrees.
Input must be a tensor of shape (C, H, W) or a batch of tensors :math:`(*, C, H, W)`.
@@ -87,14 +88,14 @@ class Rot180(nn.Module):
[0., 0., 0.]]]])
"""
- def forward(self, input: torch.Tensor) -> torch.Tensor: # type: ignore
+ def forward(self, input: Tensor) -> Tensor:
return rot180(input)
def __repr__(self):
return self.__class__.__name__
-def rot180(input: torch.Tensor) -> torch.Tensor:
+def rot180(input: Tensor) -> Tensor:
r"""Rotate a tensor image or a batch of tensor images 180 degrees.
.. image:: _static/img/rot180.png
@@ -111,7 +112,7 @@ def rot180(input: torch.Tensor) -> torch.Tensor:
return torch.flip(input, [-2, -1])
-def hflip(input: torch.Tensor) -> torch.Tensor:
+def hflip(input: Tensor) -> Tensor:
r"""Horizontally flip a tensor image or a batch of tensor images.
.. image:: _static/img/hflip.png
@@ -128,7 +129,7 @@ def hflip(input: torch.Tensor) -> torch.Tensor:
return input[..., torch.arange(w - 1, -1, -1, device=input.device)]
-def vflip(input: torch.Tensor) -> torch.Tensor:
+def vflip(input: Tensor) -> Tensor:
r"""Vertically flip a tensor image or a batch of tensor images.
.. image:: _static/img/vflip.png
diff --git a/kornia/geometry/transform/imgwarp.py b/kornia/geometry/transform/imgwarp.py
index fad72c6b6..f7fb46b15 100644
--- a/kornia/geometry/transform/imgwarp.py
+++ b/kornia/geometry/transform/imgwarp.py
@@ -4,7 +4,7 @@ import torch
import torch.nn.functional as F
from torch.nn.functional import grid_sample
-from kornia.core import Tensor, stack
+from kornia.core import Tensor, concatenate, eye, stack, tensor, zeros
from kornia.geometry.conversions import (
angle_axis_to_rotation_matrix,
angle_to_rotation_matrix,
@@ -44,14 +44,14 @@ __all__ = [
def warp_perspective(
- src: torch.Tensor,
- M: torch.Tensor,
+ src: Tensor,
+ M: Tensor,
dsize: Tuple[int, int],
mode: str = 'bilinear',
padding_mode: str = 'zeros',
align_corners: bool = True,
- fill_value: torch.Tensor = torch.zeros(3), # needed for jit
-) -> torch.Tensor:
+ fill_value: Tensor = zeros(3), # needed for jit
+) -> Tensor:
r"""Apply a perspective transformation to an image.
.. image:: https://kornia-tutorials.readthedocs.io/en/latest/_images/warp_perspective_10_1.png
@@ -91,11 +91,11 @@ def warp_perspective(
See a working example `here <https://kornia-tutorials.readthedocs.io/en/
latest/warp_perspective.html>`_.
"""
- if not isinstance(src, torch.Tensor):
- raise TypeError(f"Input src type is not a torch.Tensor. Got {type(src)}")
+ if not isinstance(src, Tensor):
+ raise TypeError(f"Input src type is not a Tensor. Got {type(src)}")
- if not isinstance(M, torch.Tensor):
- raise TypeError(f"Input M type is not a torch.Tensor. Got {type(M)}")
+ if not isinstance(M, Tensor):
+ raise TypeError(f"Input M type is not a Tensor. Got {type(M)}")
if not len(src.shape) == 4:
raise ValueError(f"Input src must be a BxCxHxW tensor. Got {src.shape}")
@@ -112,7 +112,7 @@ def warp_perspective(
h_out, w_out = dsize
# we normalize the 3x3 transformation matrix and convert to 3x4
- dst_norm_trans_src_norm: torch.Tensor = normalize_homography(M, (H, W), (h_out, w_out)) # Bx3x3
+ dst_norm_trans_src_norm: Tensor = normalize_homography(M, (H, W), (h_out, w_out)) # Bx3x3
src_norm_trans_dst_norm = _torch_inverse_cast(dst_norm_trans_src_norm) # Bx3x3
@@ -128,14 +128,14 @@ def warp_perspective(
def warp_affine(
- src: torch.Tensor,
- M: torch.Tensor,
+ src: Tensor,
+ M: Tensor,
dsize: Tuple[int, int],
mode: str = 'bilinear',
padding_mode: str = 'zeros',
align_corners: bool = True,
- fill_value: torch.Tensor = torch.zeros(3), # needed for jit
-) -> torch.Tensor:
+ fill_value: Tensor = zeros(3), # needed for jit
+) -> Tensor:
r"""Apply an affine transformation to a tensor.
.. image:: _static/img/warp_affine.png
@@ -174,11 +174,11 @@ def warp_affine(
>>> print(out.shape)
torch.Size([1, 4, 4, 2])
"""
- if not isinstance(src, torch.Tensor):
- raise TypeError(f"Input src type is not a torch.Tensor. Got {type(src)}")
+ if not isinstance(src, Tensor):
+ raise TypeError(f"Input src type is not a Tensor. Got {type(src)}")
- if not isinstance(M, torch.Tensor):
- raise TypeError(f"Input M type is not a torch.Tensor. Got {type(M)}")
+ if not isinstance(M, Tensor):
+ raise TypeError(f"Input M type is not a Tensor. Got {type(M)}")
if not len(src.shape) == 4:
raise ValueError(f"Input src must be a BxCxHxW tensor. Got {src.shape}")
@@ -194,8 +194,8 @@ def warp_affine(
B, C, H, W = src.size()
# we generate a 3x3 transformation matrix from 2x3 affine
- M_3x3: torch.Tensor = convert_affinematrix_to_homography(M)
- dst_norm_trans_src_norm: torch.Tensor = normalize_homography(M_3x3, (H, W), dsize)
+ M_3x3: Tensor = convert_affinematrix_to_homography(M)
+ dst_norm_trans_src_norm: Tensor = normalize_homography(M_3x3, (H, W), dsize)
# src_norm_trans_dst_norm = torch.inverse(dst_norm_trans_src_norm)
src_norm_trans_dst_norm = _torch_inverse_cast(dst_norm_trans_src_norm)
@@ -207,9 +207,7 @@ def warp_affine(
return F.grid_sample(src, grid, align_corners=align_corners, mode=mode, padding_mode=padding_mode)
-def _fill_and_warp(
- src: torch.Tensor, grid: torch.Tensor, mode: str, align_corners: bool, fill_value: torch.Tensor
-) -> torch.Tensor:
+def _fill_and_warp(src: Tensor, grid: Tensor, mode: str, align_corners: bool, fill_value: Tensor) -> Tensor:
r"""Warp a mask of ones, then multiple with fill_value and add to default warp.
Args:
@@ -229,7 +227,7 @@ def _fill_and_warp(
return F.grid_sample(src, grid, align_corners=align_corners, mode=mode, padding_mode="zeros") + inv_color_mask
-def warp_grid(grid: torch.Tensor, src_homo_dst: torch.Tensor) -> torch.Tensor:
+def warp_grid(grid: Tensor, src_homo_dst: Tensor) -> Tensor:
r"""Compute the grid to warp the coordinates grid by the homography/ies.
Args:
@@ -249,11 +247,11 @@ def warp_grid(grid: torch.Tensor, src_homo_dst: torch.Tensor) -> torch.Tensor:
src_homo_dst = src_homo_dst.view(batch_size, 1, 3, 3) # Nx1x3x3
# perform the actual grid transformation,
# the grid is copied to input device and casted to the same type
- flow: torch.Tensor = transform_points(src_homo_dst, grid.to(src_homo_dst)) # NxHxWx2
+ flow: Tensor = transform_points(src_homo_dst, grid.to(src_homo_dst)) # NxHxWx2
return flow.view(batch_size, height, width, 2) # NxHxWx2
-def warp_grid3d(grid: torch.Tensor, src_homo_dst: torch.Tensor) -> torch.Tensor:
+def warp_grid3d(grid: Tensor, src_homo_dst: Tensor) -> Tensor:
r"""Compute the grid to warp the coordinates grid by the homography/ies.
Args:
@@ -273,7 +271,7 @@ def warp_grid3d(grid: torch.Tensor, src_homo_dst: torch.Tensor) -> torch.Tensor:
src_homo_dst = src_homo_dst.view(batch_size, 1, 4, 4) # Nx1x3x3
# perform the actual grid transformation,
# the grid is copied to input device and casted to the same type
- flow: torch.Tensor = transform_points(src_homo_dst, grid.to(src_homo_dst)) # NxDxHxWx3
+ flow: Tensor = transform_points(src_homo_dst, grid.to(src_homo_dst)) # NxDxHxWx3
return flow.view(batch_size, depth, height, width, 3) # NxDxHxWx3
@@ -344,15 +342,15 @@ def get_perspective_transform(points_src: Tensor, points_dst: Tensor) -> Tensor:
A = torch.empty(B, 8, 8, device=points_src.device, dtype=points_src.dtype)
# we need to perform in batch
- zeros = torch.zeros(B, device=points_src.device, dtype=points_src.dtype)
- ones = torch.ones(B, device=points_src.device, dtype=points_src.dtype)
+ _zeros = zeros(B, device=points_src.device, dtype=points_src.dtype)
+ _ones = torch.ones(B, device=points_src.device, dtype=points_src.dtype)
for i in range(4):
x1, y1 = points_src[..., i, 0], points_src[..., i, 1] # Bx4
x2, y2 = points_dst[..., i, 0], points_dst[..., i, 1] # Bx4
- A[:, 2 * i] = stack([x1, y1, ones, zeros, zeros, zeros, -x1 * x2, -y1 * x2], -1)
- A[:, 2 * i + 1] = stack([zeros, zeros, zeros, x1, y1, ones, -x1 * y2, -y1 * y2], -1)
+ A[:, 2 * i] = stack([x1, y1, _ones, _zeros, _zeros, _zeros, -x1 * x2, -y1 * x2], -1)
+ A[:, 2 * i + 1] = stack([_zeros, _zeros, _zeros, x1, y1, _ones, -x1 * y2, -y1 * y2], -1)
# the rhs tensor
b = points_dst.view(-1, 8, 1)
@@ -369,7 +367,7 @@ def get_perspective_transform(points_src: Tensor, points_dst: Tensor) -> Tensor:
# TODO: move to kornia.geometry.affine
-def get_rotation_matrix2d(center: torch.Tensor, angle: torch.Tensor, scale: torch.Tensor) -> torch.Tensor:
+def get_rotation_matrix2d(center: Tensor, angle: Tensor, scale: Tensor) -> Tensor:
r"""Calculate an affine matrix of 2D rotation.
The function calculates the following matrix:
@@ -402,7 +400,7 @@ def get_rotation_matrix2d(center: torch.Tensor, angle: torch.Tensor, scale: torc
the affine matrix of 2D rotation with shape :math:`(B, 2, 3)`.
Example:
- >>> center = torch.zeros(1, 2)
+ >>> center = zeros(1, 2)
>>> scale = torch.ones((1, 2))
>>> angle = 45. * torch.ones(1)
>>> get_rotation_matrix2d(center, angle, scale)
@@ -412,14 +410,14 @@ def get_rotation_matrix2d(center: torch.Tensor, angle: torch.Tensor, scale: torc
.. note::
This function is often used in conjunction with :func:`warp_affine`.
"""
- if not isinstance(center, torch.Tensor):
- raise TypeError(f"Input center type is not a torch.Tensor. Got {type(center)}")
+ if not isinstance(center, Tensor):
+ raise TypeError(f"Input center type is not a Tensor. Got {type(center)}")
- if not isinstance(angle, torch.Tensor):
- raise TypeError(f"Input angle type is not a torch.Tensor. Got {type(angle)}")
+ if not isinstance(angle, Tensor):
+ raise TypeError(f"Input angle type is not a Tensor. Got {type(angle)}")
- if not isinstance(scale, torch.Tensor):
- raise TypeError(f"Input scale type is not a torch.Tensor. Got {type(scale)}")
+ if not isinstance(scale, Tensor):
+ raise TypeError(f"Input scale type is not a Tensor. Got {type(scale)}")
if not (len(center.shape) == 2 and center.shape[1] == 2):
raise ValueError(f"Input center must be a Bx2 tensor. Got {center.shape}")
@@ -530,7 +528,7 @@ def remap(
return grid_sample(image, map_xy, mode=mode, padding_mode=padding_mode, align_corners=align_corners)
-def invert_affine_transform(matrix: torch.Tensor) -> torch.Tensor:
+def invert_affine_transform(matrix: Tensor) -> Tensor:
r"""Invert an affine transformation.
The function computes an inverse affine transformation represented by
@@ -554,26 +552,26 @@ def invert_affine_transform(matrix: torch.Tensor) -> torch.Tensor:
.. note::
This function is often used in conjunction with :func:`warp_affine`.
"""
- if not isinstance(matrix, torch.Tensor):
- raise TypeError(f"Input matrix type is not a torch.Tensor. Got {type(matrix)}")
+ if not isinstance(matrix, Tensor):
+ raise TypeError(f"Input matrix type is not a Tensor. Got {type(matrix)}")
if not (len(matrix.shape) == 3 and matrix.shape[-2:] == (2, 3)):
raise ValueError(f"Input matrix must be a Bx2x3 tensor. Got {matrix.shape}")
- matrix_tmp: torch.Tensor = convert_affinematrix_to_homography(matrix)
- matrix_inv: torch.Tensor = _torch_inverse_cast(matrix_tmp)
+ matrix_tmp: Tensor = convert_affinematrix_to_homography(matrix)
+ matrix_inv: Tensor = _torch_inverse_cast(matrix_tmp)
return matrix_inv[..., :2, :3]
def get_affine_matrix2d(
- translations: torch.Tensor,
- center: torch.Tensor,
- scale: torch.Tensor,
- angle: torch.Tensor,
- sx: Optional[torch.Tensor] = None,
- sy: Optional[torch.Tensor] = None,
-) -> torch.Tensor:
+ translations: Tensor,
+ center: Tensor,
+ scale: Tensor,
+ angle: Tensor,
+ sx: Optional[Tensor] = None,
+ sy: Optional[Tensor] = None,
+) -> Tensor:
r"""Compose affine matrix from the components.
Args:
@@ -590,7 +588,7 @@ def get_affine_matrix2d(
.. note::
This function is often used in conjunction with :func:`warp_affine`, :func:`warp_perspective`.
"""
- transform: torch.Tensor = get_rotation_matrix2d(center, -angle, scale)
+ transform: Tensor = get_rotation_matrix2d(center, -angle, scale)
transform[..., 2] += translations # tx/ty
# pad transform to get Bx3x3
@@ -603,7 +601,7 @@ def get_affine_matrix2d(
return transform_h
-def get_shear_matrix2d(center: torch.Tensor, sx: Optional[torch.Tensor] = None, sy: Optional[torch.Tensor] = None):
+def get_shear_matrix2d(center: Tensor, sx: Optional[Tensor] = None, sy: Optional[Tensor] = None):
r"""Compose shear matrix Bx4x4 from the components.
Note: Ordered shearing, shear x-axis then y-axis.
@@ -636,35 +634,35 @@ def get_shear_matrix2d(center: torch.Tensor, sx: Optional[torch.Tensor] = None,
.. note::
This function is often used in conjunction with :func:`warp_affine`, :func:`warp_perspective`.
"""
- sx = torch.tensor([0.0]).repeat(center.size(0)) if sx is None else sx
- sy = torch.tensor([0.0]).repeat(center.size(0)) if sy is None else sy
+ sx = tensor([0.0]).repeat(center.size(0)) if sx is None else sx
+ sy = tensor([0.0]).repeat(center.size(0)) if sy is None else sy
x, y = torch.split(center, 1, dim=-1)
x, y = x.view(-1), y.view(-1)
- sx_tan = torch.tan(sx) # type: ignore
- sy_tan = torch.tan(sy) # type: ignore
- ones = torch.ones_like(sx) # type: ignore
- shear_mat = torch.stack(
- [ones, -sx_tan, sx_tan * y, -sy_tan, ones + sx_tan * sy_tan, sy_tan * (sx_tan * y + x)], dim=-1 # type: ignore
- ).view(-1, 2, 3)
+ sx_tan = torch.tan(sx)
+ sy_tan = torch.tan(sy)
+ ones = torch.ones_like(sx)
+ shear_mat = stack([ones, -sx_tan, sx_tan * y, -sy_tan, ones + sx_tan * sy_tan, sy_tan * (sx_tan * y + x)], -1).view(
+ -1, 2, 3
+ )
shear_mat = convert_affinematrix_to_homography(shear_mat)
return shear_mat
def get_affine_matrix3d(
- translations: torch.Tensor,
- center: torch.Tensor,
- scale: torch.Tensor,
- angles: torch.Tensor,
- sxy: Optional[torch.Tensor] = None,
- sxz: Optional[torch.Tensor] = None,
- syx: Optional[torch.Tensor] = None,
- syz: Optional[torch.Tensor] = None,
- szx: Optional[torch.Tensor] = None,
- szy: Optional[torch.Tensor] = None,
-) -> torch.Tensor:
+ translations: Tensor,
+ center: Tensor,
+ scale: Tensor,
+ angles: Tensor,
+ sxy: Optional[Tensor] = None,
+ sxz: Optional[Tensor] = None,
+ syx: Optional[Tensor] = None,
+ syz: Optional[Tensor] = None,
+ szx: Optional[Tensor] = None,
+ szy: Optional[Tensor] = None,
+) -> Tensor:
r"""Compose 3d affine matrix from the components.
Args:
@@ -687,7 +685,7 @@ def get_affine_matrix3d(
.. note::
This function is often used in conjunction with :func:`warp_perspective`.
"""
- transform: torch.Tensor = get_projective_transform(center, -angles, scale)
+ transform: Tensor = get_projective_transform(center, -angles, scale)
transform[..., 3] += translations # tx/ty/tz
# pad transform to get Bx3x3
@@ -700,13 +698,13 @@ def get_affine_matrix3d(
def get_shear_matrix3d(
- center: torch.Tensor,
- sxy: Optional[torch.Tensor] = None,
- sxz: Optional[torch.Tensor] = None,
- syx: Optional[torch.Tensor] = None,
- syz: Optional[torch.Tensor] = None,
- szx: Optional[torch.Tensor] = None,
- szy: Optional[torch.Tensor] = None,
+ center: Tensor,
+ sxy: Optional[Tensor] = None,
+ sxz: Optional[Tensor] = None,
+ syx: Optional[Tensor] = None,
+ syz: Optional[Tensor] = None,
+ szx: Optional[Tensor] = None,
+ szy: Optional[Tensor] = None,
):
r"""Compose shear matrix Bx4x4 from the components.
Note: Ordered shearing, shear x-axis then y-axis then z-axis.
@@ -755,22 +753,22 @@ def get_shear_matrix3d(
.. note::
This function is often used in conjunction with :func:`warp_perspective3d`.
"""
- sxy = torch.tensor([0.0]).repeat(center.size(0)) if sxy is None else sxy
- sxz = torch.tensor([0.0]).repeat(center.size(0)) if sxz is None else sxz
- syx = torch.tensor([0.0]).repeat(center.size(0)) if syx is None else syx
- syz = torch.tensor([0.0]).repeat(center.size(0)) if syz is None else syz
- szx = torch.tensor([0.0]).repeat(center.size(0)) if szx is None else szx
- szy = torch.tensor([0.0]).repeat(center.size(0)) if szy is None else szy
+ sxy = tensor([0.0]).repeat(center.size(0)) if sxy is None else sxy
+ sxz = tensor([0.0]).repeat(center.size(0)) if sxz is None else sxz
+ syx = tensor([0.0]).repeat(center.size(0)) if syx is None else syx
+ syz = tensor([0.0]).repeat(center.size(0)) if syz is None else syz
+ szx = tensor([0.0]).repeat(center.size(0)) if szx is None else szx
+ szy = tensor([0.0]).repeat(center.size(0)) if szy is None else szy
x, y, z = torch.split(center, 1, dim=-1)
x, y, z = x.view(-1), y.view(-1), z.view(-1)
# Prepare parameters
- sxy_tan = torch.tan(sxy) # type: ignore
- sxz_tan = torch.tan(sxz) # type: ignore
- syx_tan = torch.tan(syx) # type: ignore
- syz_tan = torch.tan(syz) # type: ignore
- szx_tan = torch.tan(szx) # type: ignore
- szy_tan = torch.tan(szy) # type: ignore
+ sxy_tan = torch.tan(sxy)
+ sxz_tan = torch.tan(sxz)
+ syx_tan = torch.tan(syx)
+ syz_tan = torch.tan(syz)
+ szx_tan = torch.tan(szx)
+ szy_tan = torch.tan(szy)
# compute translation matrix
m00, m10, m20, m01, m11, m21, m02, m12, m22 = _compute_shear_matrix_3d(
@@ -787,14 +785,14 @@ def get_shear_matrix3d(
sxy_tan, sxz_tan, syx_tan, syz_tan, szx_tan, szy_tan
)
- shear_mat = torch.stack([m00, m01, m02, m03, m10, m11, m12, m13, m20, m21, m22, m23], dim=-1).view(-1, 3, 4)
+ shear_mat = stack([m00, m01, m02, m03, m10, m11, m12, m13, m20, m21, m22, m23], -1).view(-1, 3, 4)
shear_mat = convert_affinematrix_to_homography3d(shear_mat)
return shear_mat
def _compute_shear_matrix_3d(sxy_tan, sxz_tan, syx_tan, syz_tan, szx_tan, szy_tan):
- ones = torch.ones_like(sxy_tan) # type: ignore
+ ones = torch.ones_like(sxy_tan)
m00, m10, m20 = ones, sxy_tan, sxz_tan
m01, m11, m21 = syx_tan, sxy_tan * syx_tan + ones, sxz_tan * syx_tan + syz_tan
@@ -805,13 +803,13 @@ def _compute_shear_matrix_3d(sxy_tan, sxz_tan, syx_tan, syz_tan, szx_tan, szy_ta
def warp_affine3d(
- src: torch.Tensor,
- M: torch.Tensor,
+ src: Tensor,
+ M: Tensor,
dsize: Tuple[int, int, int],
flags: str = 'bilinear',
padding_mode: str = 'zeros',
align_corners: bool = True,
-) -> torch.Tensor:
+) -> Tensor:
r"""Apply a projective transformation a to 3d tensor.
.. warning::
@@ -828,7 +826,7 @@ def warp_affine3d(
align_corners : mode for grid_generation.
Returns:
- torch.Tensor: the warped 3d tensor with shape :math:`(B, C, D, H, W)`.
+ Tensor: the warped 3d tensor with shape :math:`(B, C, D, H, W)`.
.. note::
This function is often used in conjunction with :func:`get_perspective_transform3d`.
@@ -847,20 +845,18 @@ def warp_affine3d(
M_4x4 = convert_affinematrix_to_homography3d(M) # Bx4x4
# we need to normalize the transformation since grid sample needs -1/1 coordinates
- dst_norm_trans_src_norm: torch.Tensor = normalize_homography3d(M_4x4, size_src, size_out) # Bx4x4
+ dst_norm_trans_src_norm: Tensor = normalize_homography3d(M_4x4, size_src, size_out) # Bx4x4
src_norm_trans_dst_norm = _torch_inverse_cast(dst_norm_trans_src_norm)
- P_norm: torch.Tensor = src_norm_trans_dst_norm[:, :3] # Bx3x4
+ P_norm: Tensor = src_norm_trans_dst_norm[:, :3] # Bx3x4
# compute meshgrid and apply to input
dsize_out: List[int] = [B, C] + list(size_out)
- grid = torch.nn.functional.affine_grid(P_norm, dsize_out, align_corners=align_corners)
- return torch.nn.functional.grid_sample(
- src, grid, align_corners=align_corners, mode=flags, padding_mode=padding_mode
- )
+ grid = F.affine_grid(P_norm, dsize_out, align_corners=align_corners)
+ return grid_sample(src, grid, align_corners=align_corners, mode=flags, padding_mode=padding_mode)
-def projection_from_Rt(rmat: torch.Tensor, tvec: torch.Tensor) -> torch.Tensor:
+def projection_from_Rt(rmat: Tensor, tvec: Tensor) -> Tensor:
r"""Compute the projection matrix from Rotation and translation.
.. warning::
@@ -880,10 +876,10 @@ def projection_from_Rt(rmat: torch.Tensor, tvec: torch.Tensor) -> torch.Tensor:
if not (len(tvec.shape) >= 2 and tvec.shape[-2:] == (3, 1)):
raise AssertionError(tvec.shape)
- return torch.cat([rmat, tvec], dim=-1) # Bx3x4
+ return concatenate([rmat, tvec], -1) # Bx3x4
-def get_projective_transform(center: torch.Tensor, angles: torch.Tensor, scales: torch.Tensor) -> torch.Tensor:
+def get_projective_transform(center: Tensor, angles: Tensor, scales: Tensor) -> Tensor:
r"""Calculate the projection matrix for a 3D rotation.
.. warning::
@@ -914,14 +910,14 @@ def get_projective_transform(center: torch.Tensor, angles: torch.Tensor, scales:
raise AssertionError(center.dtype, angles.dtype)
# create rotation matrix
- angle_axis_rad: torch.Tensor = deg2rad(angles)
- rmat: torch.Tensor = angle_axis_to_rotation_matrix(angle_axis_rad) # Bx3x3
- scaling_matrix: torch.Tensor = eye_like(3, rmat)
+ angle_axis_rad: Tensor = deg2rad(angles)
+ rmat: Tensor = angle_axis_to_rotation_matrix(angle_axis_rad) # Bx3x3
+ scaling_matrix: Tensor = eye_like(3, rmat)
scaling_matrix = scaling_matrix * scales.unsqueeze(dim=1)
rmat = rmat @ scaling_matrix.to(rmat)
# define matrix to move forth and back to origin
- from_origin_mat = torch.eye(4)[None].repeat(rmat.shape[0], 1, 1).type_as(center) # Bx4x4
+ from_origin_mat = eye(4)[None].repeat(rmat.shape[0], 1, 1).type_as(center) # Bx4x4
from_origin_mat[..., :3, -1] += center
to_origin_mat = from_origin_mat.clone()
@@ -937,7 +933,7 @@ def get_projective_transform(center: torch.Tensor, angles: torch.Tensor, scales:
return proj_mat[..., :3, :] # Bx3x4
-def get_perspective_transform3d(src: torch.Tensor, dst: torch.Tensor) -> torch.Tensor:
+def get_perspective_transform3d(src: Tensor, dst: Tensor) -> Tensor:
r"""Calculate a 3d perspective transform from four pairs of the corresponding points.
The function calculates the matrix of a perspective transform so that:
@@ -1006,11 +1002,11 @@ def get_perspective_transform3d(src: torch.Tensor, dst: torch.Tensor) -> torch.T
.. note::
This function is often used in conjunction with :func:`warp_perspective3d`.
"""
- if not isinstance(src, (torch.Tensor)):
- raise TypeError(f"Input type is not a torch.Tensor. Got {type(src)}")
+ if not isinstance(src, (Tensor)):
+ raise TypeError(f"Input type is not a Tensor. Got {type(src)}")
- if not isinstance(dst, (torch.Tensor)):
- raise TypeError(f"Input type is not a torch.Tensor. Got {type(dst)}")
+ if not isinstance(dst, (Tensor)):
+ raise TypeError(f"Input type is not a Tensor. Got {type(dst)}")
if not src.shape[-2:] == (8, 3):
raise ValueError(f"Inputs must be a Bx8x3 tensor. Got {src.shape}")
@@ -1039,10 +1035,10 @@ def get_perspective_transform3d(src: torch.Tensor, dst: torch.Tensor) -> torch.T
p.append(_build_perspective_param3d(src[:, i], dst[:, i], 'z'))
# A is Bx15x15
- A = torch.stack(p, dim=1)
+ A = stack(p, 1)
# b is a Bx15x1
- b = torch.stack(
+ b = stack(
[
dst[:, 0:1, 0],
dst[:, 0:1, 1],
@@ -1063,7 +1059,7 @@ def get_perspective_transform3d(src: torch.Tensor, dst: torch.Tensor) -> torch.T
dst[:, 7:8, 1],
dst[:, 7:8, 2],
],
- dim=1,
+ 1,
)
# solve the system Ax = b
@@ -1078,12 +1074,12 @@ def get_perspective_transform3d(src: torch.Tensor, dst: torch.Tensor) -> torch.T
return M.view(-1, 4, 4) # Bx4x4
-def _build_perspective_param3d(p: torch.Tensor, q: torch.Tensor, axis: str) -> torch.Tensor:
+def _build_perspective_param3d(p: Tensor, q: Tensor, axis: str) -> Tensor:
ones = torch.ones_like(p)[..., 0:1]
zeros = torch.zeros_like(p)[..., 0:1]
if axis == 'x':
- return torch.cat(
+ return concatenate(
[
p[:, 0:1],
p[:, 1:2],
@@ -1101,11 +1097,11 @@ def _build_perspective_param3d(p: torch.Tensor, q: torch.Tensor, axis: str) -> t
-p[:, 1:2] * q[:, 0:1],
-p[:, 2:3] * q[:, 0:1],
],
- dim=1,
+ 1,
)
if axis == 'y':
- return torch.cat(
+ return concatenate(
[
zeros,
zeros,
@@ -1123,11 +1119,11 @@ def _build_perspective_param3d(p: torch.Tensor, q: torch.Tensor, axis: str) -> t
-p[:, 1:2] * q[:, 1:2],
-p[:, 2:3] * q[:, 1:2],
],
- dim=1,
+ 1,
)
if axis == 'z':
- return torch.cat(
+ return concatenate(
[
zeros,
zeros,
@@ -1145,20 +1141,20 @@ def _build_perspective_param3d(p: torch.Tensor, q: torch.Tensor, axis: str) -> t
-p[:, 1:2] * q[:, 2:3],
-p[:, 2:3] * q[:, 2:3],
],
- dim=1,
+ 1,
)
raise NotImplementedError(f"perspective params for axis `{axis}` is not implemented.")
def warp_perspective3d(
- src: torch.Tensor,
- M: torch.Tensor,
+ src: Tensor,
+ M: Tensor,
dsize: Tuple[int, int, int],
flags: str = 'bilinear',
border_mode: str = 'zeros',
align_corners: bool = False,
-) -> torch.Tensor:
+) -> Tensor:
r"""Apply a perspective transformation to an image.
The function warp_perspective transforms the source image using
@@ -1186,11 +1182,11 @@ def warp_perspective3d(
.. note::
This function is often used in conjunction with :func:`get_perspective_transform3d`.
"""
- if not isinstance(src, torch.Tensor):
- raise TypeError(f"Input src type is not a torch.Tensor. Got {type(src)}")
+ if not isinstance(src, Tensor):
+ raise TypeError(f"Input src type is not a Tensor. Got {type(src)}")
- if not isinstance(M, torch.Tensor):
- raise TypeError(f"Input M type is not a torch.Tensor. Got {type(M)}")
+ if not isinstance(M, Tensor):
+ raise TypeError(f"Input M type is not a Tensor. Got {type(M)}")
if not len(src.shape) == 5:
raise ValueError(f"Input src must be a BxCxDxHxW tensor. Got {src.shape}")
@@ -1204,15 +1200,15 @@ def warp_perspective3d(
def homography_warp(
- patch_src: torch.Tensor,
- src_homo_dst: torch.Tensor,
+ patch_src: Tensor,
+ src_homo_dst: Tensor,
dsize: Tuple[int, int],
mode: str = 'bilinear',
padding_mode: str = 'zeros',
align_corners: bool = False,
normalized_coordinates: bool = True,
normalized_homography: bool = True,
-) -> torch.Tensor:
+) -> Tensor:
r"""Warp image patches or tensors by normalized 2D homographies.
See :class:`~kornia.geometry.warp.HomographyWarper` for details.
@@ -1265,30 +1261,30 @@ def homography_warp(
def _transform_warp_impl3d(
- src: torch.Tensor,
- dst_pix_trans_src_pix: torch.Tensor,
+ src: Tensor,
+ dst_pix_trans_src_pix: Tensor,
dsize_src: Tuple[int, int, int],
dsize_dst: Tuple[int, int, int],
grid_mode: str,
padding_mode: str,
align_corners: bool,
-) -> torch.Tensor:
+) -> Tensor:
"""Compute the transform in normalized coordinates and perform the warping."""
- dst_norm_trans_src_norm: torch.Tensor = normalize_homography3d(dst_pix_trans_src_pix, dsize_src, dsize_dst)
+ dst_norm_trans_src_norm: Tensor = normalize_homography3d(dst_pix_trans_src_pix, dsize_src, dsize_dst)
src_norm_trans_dst_norm = torch.inverse(dst_norm_trans_src_norm)
return homography_warp3d(src, src_norm_trans_dst_norm, dsize_dst, grid_mode, padding_mode, align_corners, True)
def homography_warp3d(
- patch_src: torch.Tensor,
- src_homo_dst: torch.Tensor,
+ patch_src: Tensor,
+ src_homo_dst: Tensor,
dsize: Tuple[int, int, int],
mode: str = 'bilinear',
padding_mode: str = 'zeros',
align_corners: bool = False,
normalized_coordinates: bool = True,
-) -> torch.Tensor:
+) -> Tensor:
r"""Warp image patches or tensors by normalized 3D homographies.
Args:
diff --git a/kornia/geometry/transform/pyramid.py b/kornia/geometry/transform/pyramid.py
index 767837a6d..3f4a5db9d 100644
--- a/kornia/geometry/transform/pyramid.py
+++ b/kornia/geometry/transform/pyramid.py
@@ -2,10 +2,9 @@ import math
from typing import List, Tuple
import torch
-import torch.nn as nn
import torch.nn.functional as F
-from kornia.core import Tensor
+from kornia.core import Module, Tensor, pad, stack, tensor
from kornia.filters import filter2d, gaussian_blur2d
from kornia.testing import KORNIA_CHECK, KORNIA_CHECK_SHAPE
@@ -15,7 +14,7 @@ __all__ = ["PyrDown", "PyrUp", "ScalePyramid", "pyrdown", "pyrup", "build_pyrami
def _get_pyramid_gaussian_kernel() -> Tensor:
"""Utility function that return a pre-computed gaussian kernel."""
return (
- torch.tensor(
+ tensor(
[
[
[1.0, 4.0, 6.0, 4.0, 1.0],
@@ -30,7 +29,7 @@ def _get_pyramid_gaussian_kernel() -> Tensor:
)
-class PyrDown(nn.Module):
+class PyrDown(Module):
r"""Blur a tensor and downsamples it.
Args:
@@ -62,7 +61,7 @@ class PyrDown(nn.Module):
return pyrdown(input, self.border_type, self.align_corners, self.factor)
-class PyrUp(nn.Module):
+class PyrUp(Module):
r"""Upsample a tensor and then blurs it.
Args:
@@ -92,7 +91,7 @@ class PyrUp(nn.Module):
return pyrup(input, self.border_type, self.align_corners)
-class ScalePyramid(nn.Module):
+class ScalePyramid(Module):
r"""Create an scale pyramid of image, usually used for local feature detection.
Images are consequently smoothed with Gaussian blur and downscaled.
@@ -186,7 +185,7 @@ class ScalePyramid(nn.Module):
cur_level = x
return cur_level, cur_sigma, pixel_distance
- def forward(self, x: Tensor) -> Tuple[List, List, List]: # type: ignore
+ def forward(self, x: Tensor) -> Tuple[List, List, List]:
bs, _, _, _ = x.size()
cur_level, cur_sigma, pixel_distance = self.get_first_level(x)
@@ -225,7 +224,7 @@ class ScalePyramid(nn.Module):
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] = torch.stack(pyr[i], dim=2) # type: ignore
+ pyr[i] = stack(pyr[i], 2) # type: ignore
return pyr, sigmas, pixel_dists
@@ -394,8 +393,8 @@ def build_laplacian_pyramid(
if require_padding:
# in case of arbitrary shape tensor image need to be padded.
# Reference: https://stackoverflow.com/a/29967555
- pad = (0, find_next_powerof_two(w) - w, 0, find_next_powerof_two(h) - h)
- input = F.pad(input, pad, "reflect")
+ padding = (0, find_next_powerof_two(w) - w, 0, find_next_powerof_two(h) - h)
+ input = pad(input, padding, "reflect")
# create gaussian pyramid
gaussian_pyramid: List[Tensor] = build_pyramid(input, max_level, border_type, align_corners)
diff --git a/kornia/io/io.py b/kornia/io/io.py
index f7af35228..294b4cb03 100644
--- a/kornia/io/io.py
+++ b/kornia/io/io.py
@@ -7,6 +7,7 @@ import os
from enum import Enum
import torch
+from torch.utils import dlpack # TODO: remove this if kornia relies on torch>=1.10
from kornia.color import rgb_to_grayscale, rgba_to_rgb
from kornia.color.gray import grayscale_to_rgb
@@ -34,7 +35,7 @@ def load_image_to_tensor(path_file: str, device: str) -> Tensor:
# for convenience use the torch dlpack parser to get a zero copy torch.Tensor
# TODO: evaluate other potential API so that we can return in numpy, jax, mxnet since
# the kornia_rs cv::Tensor has this ability.
- th_tensor = torch.utils.dlpack.from_dlpack(cv_tensor) # type: ignore # HxWx3
+ th_tensor = dlpack.from_dlpack(cv_tensor) # HxWx3
# move the tensor to the desired device, move the data layout to CHW and clone
# to return an owned data tensor.
return th_tensor.to(torch.device(device)).permute(2, 0, 1).clone() # CxHxW
diff --git a/kornia/nerf/camera_utils.py b/kornia/nerf/camera_utils.py
index dd6a7c669..5660ec353 100755
--- a/kornia/nerf/camera_utils.py
+++ b/kornia/nerf/camera_utils.py
@@ -1,5 +1,5 @@
import math
-from typing import List, Tuple
+from typing import List, Tuple, Union
import torch
@@ -110,7 +110,7 @@ def parse_colmap_output(
return img_names, cameras
-def cameras_for_ids(cameras: PinholeCamera, camera_ids: List[int]) -> PinholeCamera:
+def cameras_for_ids(cameras: PinholeCamera, camera_ids: Union[List[int], Tensor]) -> PinholeCamera:
r"""Takes a PinholeCamera camera object and a set of camera indices and creates a new PinholeCamera object for
the requested cameras.
diff --git a/kornia/nerf/data_utils.py b/kornia/nerf/data_utils.py
index 835071ae7..2a16d6e9d 100755
--- a/kornia/nerf/data_utils.py
+++ b/kornia/nerf/data_utils.py
@@ -1,7 +1,8 @@
-from typing import List, Optional, Tuple, Union
+from typing import List, Optional, Sequence, Tuple, Union
import torch
from torch.utils.data import BatchSampler, DataLoader, Dataset, RandomSampler, SequentialSampler
+from typing_extensions import TypeGuard
from kornia.core import Device, Tensor
from kornia.geometry.camera import PinholeCamera
@@ -12,6 +13,14 @@ from kornia.nerf.rays import RandomRaySampler, RaySampler, UniformRaySampler
RayGroup = Tuple[Tensor, Tensor, Optional[Tensor]]
+def _is_list_of_str(lst: Sequence[object]) -> TypeGuard[List[str]]:
+ return isinstance(lst, list) and all(isinstance(x, str) for x in lst)
+
+
+def _is_list_of_tensors(lst: Sequence[object]) -> TypeGuard[List[Tensor]]:
+ return isinstance(lst, list) and all(isinstance(x, Tensor) for x in lst)
+
+
class RayDataset(Dataset):
r"""Class to represent a dataset of rays.
@@ -56,15 +65,18 @@ class RayDataset(Dataset):
imgs: List of image tensors or image paths: Images
"""
self._check_image_type_consistency(imgs)
- if isinstance(imgs[0], str): # Load images from disk
- self._imgs = self._load_images(imgs)
+
+ if _is_list_of_str(imgs): # Load images from disk
+ images = self._load_images(imgs)
+ elif _is_list_of_tensors(imgs):
+ images = imgs # Take images provided on input
else:
- self._imgs = imgs # Take images provided on input
- self._check_dimensions(self._imgs)
+ raise TypeError(f'Expected a list of image tensors or image paths. Gotcha {type(imgs)}.')
+
+ self._check_dimensions(images)
# Move images to defined device
- if self._imgs is not None:
- self._imgs = [img.to(self._device) for img in self._imgs]
+ self._imgs = [img.to(self._device) for img in images]
def _init_random_ray_dataset(self, num_img_rays: Tensor) -> None:
r"""Initializes a random ray sampler and calculates dataset ray parameters.
diff --git a/kornia/nerf/nerf_solver.py b/kornia/nerf/nerf_solver.py
index c12f56645..3336f1273 100755
--- a/kornia/nerf/nerf_solver.py
+++ b/kornia/nerf/nerf_solver.py
@@ -4,9 +4,8 @@ from typing import Optional, Union
import torch
import torch.nn.functional as F
import torch.optim as optim
-from torch import nn
-from kornia.core import Module, Tensor, tensor
+from kornia.core import Module, Tensor, tensor, zeros
from kornia.geometry.camera import PinholeCamera
from kornia.metrics import psnr
from kornia.nerf.core import Images, ImageTensors
@@ -19,7 +18,7 @@ class NerfSolver:
r"""NeRF solver class.
Args:
- device: device for class tensors: Union[str, torch.device]
+ device: device for class tensors: Union[str, Device]
dtype: type for all floating point calculations: torch.dtype
"""
_nerf_model: Module
@@ -99,24 +98,25 @@ class NerfSolver:
self._opt_nerf = optim.Adam(self._nerf_model.parameters(), lr=lr)
@property
- def nerf_model(self) -> nn.Module:
+ def nerf_model(self) -> Module:
return self._nerf_model
# FIXME: Remove this function - consistency is checked in
- @staticmethod
- def _check_camera_image_consistency(cameras: PinholeCamera, imgs: Images):
- if cameras is None:
- raise ValueError('Invalid camera object')
- if imgs is None:
- raise ValueError('Invalid image list object')
- if cameras.batch_size != len(imgs):
- raise ValueError('Number of cameras must match number of input images')
- if not all(img.shape[0] == 3 for img in imgs):
- raise ValueError('All images must have three RGB channels')
- if not all(height == img.shape[1] for height, img in zip(cameras.height.tolist(), imgs)):
- raise ValueError('All image heights must match camera heights')
- if not all(width == img.shape[2] for width, img in zip(cameras.width.tolist(), imgs)):
- raise ValueError('All image widths must match camera widths')
+ # @staticmethod
+ # def _check_camera_image_consistency(cameras: PinholeCamera, imgs: Images):
+ # if cameras is None:
+ # raise TypeError('Invalid camera object')
+ # if imgs is None:
+ # raise TypeError('Invalid image list object')
+ # if cameras.batch_size != len(imgs):
+ # raise ValueError('Number of cameras must match number of input images')
+
+ # if not all(img.shape[0] == 3 for img in imgs):
+ # raise ValueError('All images must have three RGB channels')
+ # if not all(height == img.shape[1] for height, img in zip(cameras.height.tolist(), imgs)):
+ # raise ValueError('All image heights must match camera heights')
+ # if not all(width == img.shape[2] for width, img in zip(cameras.width.tolist(), imgs)):
+ # raise ValueError('All image widths must match camera widths')
def _train_one_epoch(self) -> float:
r"""Trains one epoch. A dataset of rays is initialized, and sent over to a data loader. The data loader
@@ -138,11 +138,23 @@ class NerfSolver:
Returns:
Average psnr over all epoch rays
"""
+ if self._cameras is None:
+ raise TypeError('The camera should be a PinholeCamera. Gotcha None. You init the training before train?')
+
ray_dataset = RayDataset(
self._cameras, self._min_depth, self._max_depth, self._ndc, device=self._device, dtype=self._dtype
)
+
+ if isinstance(self._num_img_rays, int):
+ raise TypeError(
+ 'The number of images of Ray should be a tensor. Gotcha an integer. You init the training before train?'
+ )
ray_dataset.init_ray_dataset(self._num_img_rays)
+
+ if self._imgs is None:
+ raise TypeError('Invalid image list object')
ray_dataset.init_images_for_training(self._imgs) # FIXME: Do we need to load the same images on each Epoch?
+
ray_data_loader = instantiate_ray_dataloader(ray_dataset, self._batch_size, shuffle=True)
total_psnr = tensor(0.0, device=self._device, dtype=self._dtype)
for i_batch, (origins, directions, rgbs) in enumerate(ray_data_loader):
@@ -187,7 +199,7 @@ class NerfSolver:
batch_size = 4096 # FIXME: Consider exposing this value to the user
for height, width in zip(cameras.height.int().tolist(), cameras.width.int().tolist()):
bsz = batch_size if batch_size != -1 else height * width
- img = torch.zeros((height * width, 3), dtype=torch.uint8)
+ img = zeros((height * width, 3), dtype=torch.uint8)
idx0_camera = idx0
for idx0 in range(idx0, idx0 + height * width, bsz):
idxe = min(idx0 + bsz, idx0_camera + height * width)
diff --git a/kornia/testing/__init__.py b/kornia/testing/__init__.py
index 6bd3caf0c..e837d7adc 100644
--- a/kornia/testing/__init__.py
+++ b/kornia/testing/__init__.py
@@ -5,11 +5,11 @@ import math
from abc import ABC, abstractmethod
from copy import deepcopy
from itertools import product
-from typing import Any, Dict, List, Optional, Tuple, cast
+from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, cast
import torch
-from kornia.core import Tensor
+from kornia.core import Tensor, eye, tensor
__all__ = [
"tensor_to_gradcheck_var",
@@ -46,7 +46,7 @@ def is_mps_tensor_safe(x: Tensor) -> bool:
# TODO: Isn't this function duplicated with eye_like?
def create_eye_batch(batch_size, eye_size, device=None, dtype=None):
"""Create a batch of identity matrices of shape Bx3x3."""
- return torch.eye(eye_size, device=device, dtype=dtype).view(1, eye_size, eye_size).expand(batch_size, -1, -1)
+ return eye(eye_size, device=device, dtype=dtype).view(1, eye_size, eye_size).expand(batch_size, -1, -1)
def create_random_homography(batch_size, eye_size, std_val=1e-3):
@@ -69,7 +69,7 @@ def tensor_to_gradcheck_var(tensor, dtype=torch.float64, requires_grad=True):
def dict_to(data: dict, device: torch.device, dtype: torch.dtype) -> dict:
out: dict = {}
for key, val in data.items():
- out[key] = val.to(device, dtype) if isinstance(val, torch.Tensor) else val
+ out[key] = val.to(device, dtype) if isinstance(val, Tensor) else val
return out
@@ -80,13 +80,13 @@ def compute_patch_error(x, y, h, w):
def check_is_tensor(obj):
"""Check whether the supplied object is a tensor."""
- if not isinstance(obj, torch.Tensor):
- raise TypeError(f"Input type is not a torch.Tensor. Got {type(obj)}")
+ if not isinstance(obj, Tensor):
+ raise TypeError(f"Input type is not a Tensor. Got {type(obj)}")
def create_rectified_fundamental_matrix(batch_size):
"""Create a batch of rectified fundamental matrices of shape Bx3x3."""
- F_rect = torch.tensor([[0.0, 0.0, 0.0], [0.0, 0.0, -1.0], [0.0, 1.0, 0.0]]).view(1, 3, 3)
+ F_rect = tensor([[0.0, 0.0, 0.0], [0.0, 0.0, -1.0], [0.0, 1.0, 0.0]]).view(1, 3, 3)
F_repeat = F_rect.repeat(batch_size, 1, 1)
return F_repeat
@@ -167,13 +167,13 @@ class BaseTester(ABC):
def generate_two_view_random_scene(
device: torch.device = torch.device("cpu"), dtype: torch.dtype = torch.float32
-) -> Dict[str, torch.Tensor]:
+) -> Dict[str, Tensor]:
from kornia.geometry import epipolar as epi
num_views: int = 2
num_points: int = 30
- scene: Dict[str, torch.Tensor] = epi.generate_scene(num_views, num_points)
+ scene: Dict[str, Tensor] = epi.generate_scene(num_views, num_points)
# internal parameters (same K)
K1 = scene['K'].to(device, dtype)
@@ -255,41 +255,48 @@ def _default_tolerances(*inputs: Any) -> Tuple[float, float]:
return max(rtols), max(atols)
-try:
- # torch.testing.assert_close is only available for torch>=1.9
- from torch.testing import assert_close as _assert_close # type: ignore
-
+if TYPE_CHECKING:
+ # TODO: remove this branch if kornia relies on torch>=1.9
def assert_close(
- actual: torch.Tensor,
- expected: torch.Tensor,
- *,
- rtol: Optional[float] = None,
- atol: Optional[float] = None,
- **kwargs: Any,
+ actual: Tensor, expected: Tensor, *, rtol: Optional[float] = None, atol: Optional[float] = None, **kwargs: Any
) -> None:
- if rtol is None and atol is None:
- # `torch.testing.assert_close` used different default tolerances than `torch.testing.assert_allclose`.
- # TODO: remove this special handling as soon as https://github.com/kornia/kornia/issues/1134 is resolved.
- # Basically, this whole wrapper function can be removed and `torch.testing.assert_close` can be used
- # directly.
- rtol, atol = _default_tolerances(actual, expected)
-
- return _assert_close(
- actual,
- expected,
- rtol=rtol,
- atol=atol,
- # this is the default value for torch>=1.10, but not for torch==1.9
- # TODO: remove this if kornia relies on torch>=1.10
- check_stride=False,
- equal_nan=True,
- **kwargs,
- )
-
-except ImportError:
- # TODO: remove this branch if kornia relies on torch>=1.9
- from torch.testing import assert_allclose as assert_close # type: ignore
-
+ ...
+
+else:
+ try:
+ # torch.testing.assert_close is only available for torch>=1.9
+ from torch.testing import assert_close as _assert_close
+
+ def assert_close(
+ actual: Tensor,
+ expected: Tensor,
+ *,
+ rtol: Optional[float] = None,
+ atol: Optional[float] = None,
+ **kwargs: Any,
+ ) -> None:
+ if rtol is None and atol is None:
+ # `torch.testing.assert_close` used different default tolerances than `torch.testing.assert_allclose`.
+ # TODO: remove this special handling as soon as https://github.com/kornia/kornia/issues/1134 is resolved
+ # Basically, this whole wrapper function can be removed and `torch.testing.assert_close` can be used
+ # directly.
+ rtol, atol = _default_tolerances(actual, expected)
+
+ return _assert_close(
+ actual,
+ expected,
+ rtol=rtol,
+ atol=atol,
+ # this is the default value for torch>=1.10, but not for torch==1.9
+ # TODO: remove this if kornia relies on torch>=1.10
+ check_stride=False,
+ equal_nan=True,
+ **kwargs,
+ )
+
+ except ImportError:
+ # TODO: remove this branch if kornia relies on torch>=1.9
+ from torch.testing import assert_allclose as assert_close
# Logger api
diff --git a/kornia/utils/helpers.py b/kornia/utils/helpers.py
index 1887338f6..5a570f5e5 100644
--- a/kornia/utils/helpers.py
+++ b/kornia/utils/helpers.py
@@ -51,7 +51,7 @@ def _deprecated(func: Optional[Callable] = None, replace_with: Optional[str] = N
def _extract_device_dtype(tensor_list: List[Optional[Any]]) -> Tuple[torch.device, torch.dtype]:
- """Check if all the input are in the same device (only if when they are torch.Tensor).
+ """Check if all the input are in the same device (only if when they are Tensor).
If so, it would return a tuple of (device, dtype). Default: (cpu, ``get_default_dtype()``).
@@ -61,7 +61,7 @@ def _extract_device_dtype(tensor_list: List[Optional[Any]]) -> Tuple[torch.devic
device, dtype = None, None
for tensor in tensor_list:
if tensor is not None:
- if not isinstance(tensor, (torch.Tensor,)):
+ if not isinstance(tensor, (Tensor,)):
continue
_device = tensor.device
_dtype = tensor.dtype
@@ -81,35 +81,35 @@ def _extract_device_dtype(tensor_list: List[Optional[Any]]) -> Tuple[torch.devic
return (device, dtype)
-def _torch_inverse_cast(input: torch.Tensor) -> torch.Tensor:
+def _torch_inverse_cast(input: Tensor) -> Tensor:
"""Helper function to make torch.inverse work with other than fp32/64.
The function torch.inverse is only implemented for fp32/64 which makes impossible to be used by fp16 or others. What
this function does, is cast input data type to fp32, apply torch.inverse, and cast back to the input dtype.
"""
- if not isinstance(input, torch.Tensor):
- raise AssertionError(f"Input must be torch.Tensor. Got: {type(input)}.")
+ if not isinstance(input, Tensor):
+ raise AssertionError(f"Input must be Tensor. Got: {type(input)}.")
dtype: torch.dtype = input.dtype
if dtype not in (torch.float32, torch.float64):
dtype = torch.float32
return torch.inverse(input.to(dtype)).to(input.dtype)
-def _torch_histc_cast(input: torch.Tensor, bins: int, min: int, max: int) -> torch.Tensor:
+def _torch_histc_cast(input: Tensor, bins: int, min: int, max: int) -> Tensor:
"""Helper function to make torch.histc work with other than fp32/64.
The function torch.histc is only implemented for fp32/64 which makes impossible to be used by fp16 or others. What
this function does, is cast input data type to fp32, apply torch.inverse, and cast back to the input dtype.
"""
- if not isinstance(input, torch.Tensor):
- raise AssertionError(f"Input must be torch.Tensor. Got: {type(input)}.")
+ if not isinstance(input, Tensor):
+ raise AssertionError(f"Input must be Tensor. Got: {type(input)}.")
dtype: torch.dtype = input.dtype
if dtype not in (torch.float32, torch.float64):
dtype = torch.float32
return torch.histc(input.to(dtype), bins, min, max).to(input.dtype)
-def _torch_svd_cast(input: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
+def _torch_svd_cast(input: Tensor) -> Tuple[Tensor, Tensor, Tensor]:
"""Helper function to make torch.svd work with other than fp32/64.
The function torch.svd is only implemented for fp32/64 which makes
@@ -118,8 +118,8 @@ def _torch_svd_cast(input: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor, to
NOTE: in torch 1.8.1 this function is recommended to use as torch.linalg.svd
"""
- if not isinstance(input, torch.Tensor):
- raise AssertionError(f"Input must be torch.Tensor. Got: {type(input)}.")
+ if not isinstance(input, Tensor):
+ raise AssertionError(f"Input must be Tensor. Got: {type(input)}.")
dtype: torch.dtype = input.dtype
if dtype not in (torch.float32, torch.float64):
dtype = torch.float32
@@ -132,7 +132,7 @@ def _torch_svd_cast(input: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor, to
return (out1.to(input.dtype), out2.to(input.dtype), out3.to(input.dtype))
-def _torch_linalg_svdvals(input: torch.Tensor) -> torch.Tensor:
+def _torch_linalg_svdvals(input: Tensor) -> Tensor:
"""Helper function to make torch.linalg.svdvals work with other than fp32/64.
The function torch.svd is only implemented for fp32/64 which makes
@@ -141,8 +141,8 @@ def _torch_linalg_svdvals(input: torch.Tensor) -> torch.Tensor:
NOTE: in torch 1.8.1 this function is recommended to use as torch.linalg.svd
"""
- if not isinstance(input, torch.Tensor):
- raise AssertionError(f"Input must be torch.Tensor. Got: {type(input)}.")
+ if not isinstance(input, Tensor):
+ raise AssertionError(f"Input must be Tensor. Got: {type(input)}.")
dtype: torch.dtype = input.dtype
if dtype not in (torch.float32, torch.float64):
dtype = torch.float32
@@ -153,7 +153,7 @@ def _torch_linalg_svdvals(input: torch.Tensor) -> torch.Tensor:
return out.to(input.dtype)
-# TODO: return only `torch.Tensor` and review all the calls to adjust
+# TODO: return only `Tensor` and review all the calls to adjust
def _torch_solve_cast(A: Tensor, B: Tensor) -> Tensor:
"""Helper function to make torch.solve work with other than fp32/64.
@@ -169,7 +169,7 @@ def _torch_solve_cast(A: Tensor, B: Tensor) -> Tensor:
return out.to(A.dtype)
-def safe_solve_with_mask(B: torch.Tensor, A: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
+def safe_solve_with_mask(B: Tensor, A: Tensor) -> Tuple[Tensor, Tensor, Tensor]:
r"""Helper function, which avoids crashing because of singular matrix input and outputs the mask of valid
solution."""
if not torch_version_geq(1, 10):
@@ -177,8 +177,8 @@ def safe_solve_with_mask(B: torch.Tensor, A: torch.Tensor) -> Tuple[torch.Tensor
warnings.warn('PyTorch version < 1.10, solve validness mask maybe not correct', RuntimeWarning)
return sol, sol, torch.ones(len(A), dtype=torch.bool, device=A.device)
# Based on https://github.com/pytorch/pytorch/issues/31546#issuecomment-694135622
- if not isinstance(B, torch.Tensor):
- raise AssertionError(f"B must be torch.Tensor. Got: {type(B)}.")
+ if not isinstance(B, Tensor):
+ raise AssertionError(f"B must be Tensor. Got: {type(B)}.")
dtype: torch.dtype = B.dtype
if dtype not in (torch.float32, torch.float64):
dtype = torch.float32
@@ -187,7 +187,7 @@ def safe_solve_with_mask(B: torch.Tensor, A: torch.Tensor) -> Tuple[torch.Tensor
else:
A_LU, pivots, info = torch.linalg.lu_factor_ex(A.to(dtype))
- valid_mask: torch.Tensor = info == 0
+ valid_mask: Tensor = info == 0
n_dim_B = len(B.shape)
n_dim_A = len(A.shape)
if n_dim_A - n_dim_B == 1:
@@ -200,7 +200,7 @@ def safe_solve_with_mask(B: torch.Tensor, A: torch.Tensor) -> Tuple[torch.Tensor
return X.to(B.dtype), A_LU.to(A.dtype), valid_mask
-def safe_inverse_with_mask(A: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
+def safe_inverse_with_mask(A: Tensor) -> Tuple[Tensor, Tensor]:
r"""Helper function, which avoids crashing because of non-invertable matrix input and outputs the mask of valid
solution."""
# Based on https://github.com/pytorch/pytorch/issues/31546#issuecomment-694135622
@@ -208,14 +208,14 @@ def safe_inverse_with_mask(A: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]
inv = _torch_inverse_cast(A)
warnings.warn('PyTorch version < 1.9, inverse validness mask maybe not correct', RuntimeWarning)
return inv, torch.ones(len(A), dtype=torch.bool, device=A.device)
- if not isinstance(A, torch.Tensor):
- raise AssertionError(f"A must be torch.Tensor. Got: {type(A)}.")
+ if not isinstance(A, Tensor):
+ raise AssertionError(f"A must be Tensor. Got: {type(A)}.")
dtype_original: torch.dtype = A.dtype
if dtype_original not in (torch.float32, torch.float64):
dtype = torch.float32
else:
dtype = dtype_original
- from torch.linalg import inv_ex # type: ignore # (not available in 1.8.1)
+ from torch.linalg import inv_ex # (not available in 1.8.1)
inverse, info = inv_ex(A.to(dtype))
mask = info == 0
diff --git a/setup.cfg b/setup.cfg
index 0466a2eda..5d3becb8a 100644
--- a/setup.cfg
+++ b/setup.cfg
@@ -121,6 +121,7 @@ pretty = True
show_error_codes = True
ignore_missing_imports = True
no_implicit_optional = True
+warn_unused_ignores = True
[pydocstyle]
match = .*\.py