Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix some typing annotations (#1967)

João Gustavo A. Amorimdeb66dfb3013
diff --git a/kornia/augmentation/_2d/geometric/affine.py b/kornia/augmentation/_2d/geometric/affine.py
index 8ff9d1b8f..bd169514a 100644
--- a/kornia/augmentation/_2d/geometric/affine.py
+++ b/kornia/augmentation/_2d/geometric/affine.py
@@ -1,11 +1,11 @@
from typing import Any, Dict, Optional, Tuple, Union, cast
import torch
-from torch import Tensor
from kornia.augmentation import random_generator as rg
from kornia.augmentation._2d.geometric.base import GeometricAugmentationBase2D
from kornia.constants import Resample, SamplePadding
+from kornia.core import Tensor
from kornia.geometry.conversions import deg2rad
from kornia.geometry.transform import get_affine_matrix2d, warp_affine
@@ -91,7 +91,7 @@ class RandomAffine(GeometricAugmentationBase2D):
return_transform: Optional[bool] = None,
) -> None:
super().__init__(p=p, return_transform=return_transform, same_on_batch=same_on_batch, keepdim=keepdim)
- self._param_generator = cast(rg.AffineGenerator, rg.AffineGenerator(degrees, translate, scale, shear))
+ self._param_generator: rg.AffineGenerator = rg.AffineGenerator(degrees, translate, scale, shear)
self.flags = dict(
resample=Resample.get(resample), padding_mode=SamplePadding.get(padding_mode), align_corners=align_corners
)
diff --git a/kornia/augmentation/_2d/mix/cutmix.py b/kornia/augmentation/_2d/mix/cutmix.py
index bc560748c..86c3e25ef 100644
--- a/kornia/augmentation/_2d/mix/cutmix.py
+++ b/kornia/augmentation/_2d/mix/cutmix.py
@@ -1,5 +1,5 @@
import warnings
-from typing import Any, Dict, List, Optional, Tuple, Union, cast
+from typing import Any, Dict, List, Optional, Tuple, Union
import torch
@@ -108,7 +108,7 @@ class RandomCutMix(MixAugmentationBase):
"The height and width arguments will be removed finally.",
category=DeprecationWarning,
)
- self._param_generator = cast(rg.CutmixGenerator, rg.CutmixGenerator(cut_size, beta, num_mix, p=p))
+ self._param_generator: rg.CutmixGenerator = rg.CutmixGenerator(cut_size, beta, num_mix, p=p)
warnings.warn("`RandomCutMix` is deprecated. Please use `RandomCutMixV2` instead.")
def apply_transform( # type: ignore
@@ -209,7 +209,7 @@ class RandomCutMixV2(MixAugmentationBaseV2):
data_keys: List[Union[str, int, DataKey]] = [DataKey.INPUT],
) -> None:
super().__init__(p=1.0, p_batch=p, same_on_batch=same_on_batch, keepdim=keepdim, data_keys=data_keys)
- self._param_generator = cast(rg.CutmixGenerator, rg.CutmixGenerator(cut_size, beta, num_mix, p=p))
+ self._param_generator: rg.CutmixGenerator = rg.CutmixGenerator(cut_size, beta, num_mix, p=p)
def apply_transform_class(self, input: Tensor, params: Dict[str, Tensor], flags: Dict[str, Any]) -> Tensor:
height, width = params["image_shape"]
diff --git a/kornia/augmentation/random_generator/_2d/resize.py b/kornia/augmentation/random_generator/_2d/resize.py
index 3d39a40db..40db27b41 100644
--- a/kornia/augmentation/random_generator/_2d/resize.py
+++ b/kornia/augmentation/random_generator/_2d/resize.py
@@ -1,9 +1,10 @@
-from typing import Dict, Optional, Tuple, Union
+from typing import Dict, Tuple, Union
import torch
from kornia.augmentation.random_generator.base import RandomGeneratorBase
from kornia.augmentation.utils import _common_param_check
+from kornia.core import Device, Tensor, tensor
from kornia.geometry.bbox import bbox_generator
from kornia.geometry.transform.affwarp import _side_to_image_size
@@ -17,9 +18,9 @@ class ResizeGenerator(RandomGeneratorBase):
Returns:
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).
- - input_size (torch.Tensor): (h, w) from batch input.
+ - src (Tensor): cropping bounding boxes with a shape of (B, 4, 2).
+ - dst (Tensor): output bounding boxes with a shape (B, 4, 2).
+ - input_size (Tensor): (h, w) from batch input.
- resize_to (tuple): new (h, w) for batch input.
Note:
@@ -32,19 +33,17 @@ class ResizeGenerator(RandomGeneratorBase):
super().__init__()
self.output_size = resize_to
self.side = side
- self.device: Optional[torch.device] = None
- self.dtype: Optional[torch.dtype] = None
def __repr__(self) -> str:
repr = f"output_size={self.output_size}"
return repr
- def make_samplers(self, device: torch.device, dtype: torch.dtype) -> None:
+ def make_samplers(self, device: Device, dtype: torch.dtype) -> None:
self.device = device
self.dtype = dtype
pass
- def forward(self, batch_shape: torch.Size, same_on_batch: bool = False) -> Dict[str, torch.Tensor]:
+ 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 = self.device
@@ -59,10 +58,10 @@ class ResizeGenerator(RandomGeneratorBase):
input_size = h, w = (batch_shape[-2], batch_shape[-1])
src = bbox_generator(
- torch.tensor(0, device=_device, dtype=_dtype),
- torch.tensor(0, device=_device, dtype=_dtype),
- torch.tensor(input_size[1], device=_device, dtype=_dtype),
- torch.tensor(input_size[0], device=_device, dtype=_dtype),
+ tensor(0, device=_device, dtype=_dtype),
+ tensor(0, device=_device, dtype=_dtype),
+ tensor(input_size[1], device=_device, dtype=_dtype),
+ tensor(input_size[0], device=_device, dtype=_dtype),
).repeat(batch_size, 1, 1)
if isinstance(self.output_size, int):
@@ -79,13 +78,13 @@ class ResizeGenerator(RandomGeneratorBase):
raise AssertionError(f"`resize_to` must be a tuple of 2 positive integers. Got {self.output_size}.")
dst = bbox_generator(
- torch.tensor(0, device=_device, dtype=_dtype),
- torch.tensor(0, device=_device, dtype=_dtype),
- torch.tensor(self.output_size[1], device=_device, dtype=_dtype),
- torch.tensor(self.output_size[0], device=_device, dtype=_dtype),
+ tensor(0, device=_device, dtype=_dtype),
+ tensor(0, device=_device, dtype=_dtype),
+ tensor(self.output_size[1], device=_device, dtype=_dtype),
+ tensor(self.output_size[0], device=_device, dtype=_dtype),
).repeat(batch_size, 1, 1)
- _input_size = torch.tensor(input_size, device=_device, dtype=torch.long).expand(batch_size, -1)
- _output_size = torch.tensor(self.output_size, device=_device, dtype=torch.long).expand(batch_size, -1)
+ _input_size = tensor(input_size, device=_device, dtype=torch.long).expand(batch_size, -1)
+ _output_size = tensor(self.output_size, device=_device, dtype=torch.long).expand(batch_size, -1)
return dict(src=src, dst=dst, input_size=_input_size, output_size=_output_size)
diff --git a/kornia/augmentation/random_generator/base.py b/kornia/augmentation/random_generator/base.py
index 038df7519..50226bcfb 100644
--- a/kornia/augmentation/random_generator/base.py
+++ b/kornia/augmentation/random_generator/base.py
@@ -4,6 +4,8 @@ import torch
import torch.nn as nn
from torch.distributions import Distribution
+from kornia.core import Device, Tensor
+
class _PostInitInjectionMetaClass(type):
"""To inject the ``__post_init__`` function after the creation of each instance."""
@@ -17,10 +19,11 @@ class _PostInitInjectionMetaClass(type):
class RandomGeneratorBase(nn.Module, metaclass=_PostInitInjectionMetaClass):
"""Base class for generating random augmentation parameters."""
+ device: Optional[Device] = None
+ dtype: torch.dtype
+
def __init__(self) -> None:
super().__init__()
- self.device = None
- self.dtype = None
def __post_init__(self) -> None:
self.set_rng_device_and_dtype()
@@ -47,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, torch.Tensor]: # type:ignore
+ def forward(self, batch_shape: torch.Size, same_on_batch: bool = False) -> Dict[str, Tensor]: # type:ignore
raise NotImplementedError
@@ -76,23 +79,23 @@ class DistributionWithMapper(Distribution):
tensor([0.8236, 0.4272, 0.1017, 0.6384, 0.2527, 0.1980, 0.5995, 0.6980])
"""
- def __init__(self, dist: Distribution, map_fn: Optional[Callable] = None) -> None:
+ def __init__(self, dist: Distribution, map_fn: Optional[Callable[[Tensor], Tensor]] = None) -> None:
self.dist = dist
self.map_fn = map_fn
- def rsample(self, sample_shape: torch.Size) -> torch.Tensor: # type:ignore
+ def rsample(self, sample_shape: torch.Size) -> Tensor: # type: ignore[override]
out = self.dist.rsample(sample_shape)
if self.map_fn is not None:
out = self.map_fn(out)
return out
- def sample(self, sample_shape: torch.Size) -> torch.Tensor: # type:ignore
+ def sample(self, sample_shape: torch.Size) -> Tensor: # type: ignore[override]
out = self.dist.sample(sample_shape)
if self.map_fn is not None:
out = self.map_fn(out)
return out
- def sample_n(self, n) -> torch.Tensor:
+ def sample_n(self, n) -> Tensor:
out = self.dist.sample_n(n)
if self.map_fn is not None:
out = self.map_fn(out)
diff --git a/kornia/constants.py b/kornia/constants.py
index 3b15b7428..96b856f32 100644
--- a/kornia/constants.py
+++ b/kornia/constants.py
@@ -1,83 +1,88 @@
from enum import Enum, EnumMeta
-from typing import TypeVar, Union, cast
+from typing import Any, Iterator, Union
import torch
-from torch import Tensor
+
+from kornia.core import Tensor
__all__ = ['pi', 'DType', 'Resample', 'BorderType', 'SamplePadding']
pi = torch.tensor(3.14159265358979323846)
-T = TypeVar('T', bound='ConstantBase')
-class ConstantBase:
- @classmethod
- def get(cls, value: Union[str, int, T]) -> T: # type: ignore
- if type(value) is str:
- return cls[value.upper()] # type: ignore
- if type(value) is int:
- return cls(value) # type: ignore
- if type(value) is cls:
- return value # type: ignore
- raise TypeError()
+class EnumMetaFlags(EnumMeta):
+ def __iter__(self) -> Iterator[Enum]: # type: ignore[override]
+ return super().__iter__()
+ def __contains__(self, other: Union[str, int, Enum]) -> bool: # type: ignore[override]
+ if isinstance(other, str):
+ return any(val.name == other.upper() for val in self)
+ elif isinstance(other, int):
+ return any(val.value == other for val in self)
-class EnumMetaFlags(EnumMeta):
- def __contains__(self, other: Union[str, int, T]) -> bool: # type: ignore
- if type(other) is str:
- other = cast(str, other)
- return any(val.name == other.upper() for val in self) # type: ignore
- if type(other) is int:
- return any(val.value == other for val in self) # type: ignore
- return any(val == other for val in self) # type: ignore
+ return any(val == other for val in self)
def __repr__(self):
return ' | '.join(f"{self.__name__}.{val.name}" for val in self)
-class Resample(ConstantBase, Enum, metaclass=EnumMetaFlags):
+class ConstantBase(Enum, metaclass=EnumMetaFlags):
+ @classmethod
+ def get(cls, value: Union[str, int, Any]) -> Any:
+ if isinstance(value, str):
+ return cls[value.upper()]
+ if isinstance(value, int):
+ return cls(value)
+ if isinstance(value, cls):
+ return value
+ raise TypeError()
+
+
+class Resample(ConstantBase):
NEAREST = 0
BILINEAR = 1
BICUBIC = 2
-class BorderType(ConstantBase, Enum, metaclass=EnumMetaFlags):
+class BorderType(ConstantBase):
CONSTANT = 0
REFLECT = 1
REPLICATE = 2
CIRCULAR = 3
-class SamplePadding(ConstantBase, Enum, metaclass=EnumMetaFlags):
+class SamplePadding(ConstantBase):
ZEROS = 0
BORDER = 1
REFLECTION = 2
-class DType(ConstantBase, Enum, metaclass=EnumMetaFlags):
+class DType(ConstantBase):
INT64 = 0
FLOAT16 = 1
FLOAT32 = 2
FLOAT64 = 3
@classmethod
- def get(cls, value: Union[str, int, torch.dtype, Tensor, T]) -> T: # type: ignore
- if type(value) is torch.dtype:
+ def get(cls, value: Union[str, int, torch.dtype, Tensor, 'DType']) -> 'DType': # type: ignore[override]
+ if isinstance(value, torch.dtype):
value = str(value).upper() # Convert to str
- if type(value) is Tensor:
- value = value.item() # Convert to int
- if type(value) is str:
+ if isinstance(value, Tensor):
+ value = int(value.item()) # Convert to int
+
+ if isinstance(value, str):
if value.upper().startswith("TORCH."):
- return cls[value.upper()[6:]] # type: ignore
- return cls[value.upper()] # type: ignore
- if type(value) is int:
- return cls(value) # type: ignore
- if type(value) is cls:
- return value # type: ignore
+ return cls[value.upper()[6:]]
+ return cls[value.upper()]
+
+ if isinstance(value, int):
+ return cls(value)
+ if isinstance(value, cls):
+ return value
raise TypeError(f"Invalid identifier {value}.")
@classmethod
- def to_torch(cls, value: Union[str, int, T]) -> T: # type: ignore
+ def to_torch(cls, value: Union[str, int, 'DType']) -> torch.dtype:
data = cls.get(value=value)
if data == DType.INT64:
return torch.long
@@ -91,7 +96,7 @@ class DType(ConstantBase, Enum, metaclass=EnumMetaFlags):
# TODO: (low-priority) add INPUT3D, MASK3D, BBOX3D, LAFs etc.
-class DataKey(ConstantBase, Enum, metaclass=EnumMetaFlags):
+class DataKey(ConstantBase):
INPUT = 0
MASK = 1
BBOX = 2
diff --git a/kornia/geometry/camera/pinhole.py b/kornia/geometry/camera/pinhole.py
index bf3e684a4..72a60ea07 100644
--- a/kornia/geometry/camera/pinhole.py
+++ b/kornia/geometry/camera/pinhole.py
@@ -1,7 +1,8 @@
-from typing import Iterable, List, Optional
+from typing import Iterable, List
import torch
+from kornia.core import Device, Tensor
from kornia.geometry.conversions import convert_points_from_homogeneous, convert_points_to_homogeneous
from kornia.geometry.linalg import inverse_transformation, transform_points
from kornia.testing import KORNIA_CHECK_SAME_DEVICE
@@ -24,9 +25,7 @@ class PinholeCamera:
advantage of PyTorch parallelism to boost computing performance.
"""
- def __init__(
- self, intrinsics: torch.Tensor, extrinsics: torch.Tensor, height: torch.Tensor, width: torch.Tensor
- ) -> None:
+ def __init__(self, intrinsics: Tensor, extrinsics: Tensor, height: Tensor, width: Tensor) -> None:
# verify batch size and shapes
self._check_valid([intrinsics, extrinsics, height, width])
self._check_valid_params(intrinsics, "intrinsics")
@@ -35,19 +34,19 @@ class PinholeCamera:
self._check_valid_shape(width, "width")
self._check_consistent_device([intrinsics, extrinsics, height, width])
# set class attributes
- self.height: torch.Tensor = height
- self.width: torch.Tensor = width
- self._intrinsics: torch.Tensor = intrinsics
- self._extrinsics: torch.Tensor = extrinsics
+ self.height: Tensor = height
+ self.width: Tensor = width
+ self._intrinsics: Tensor = intrinsics
+ self._extrinsics: Tensor = extrinsics
@staticmethod
- def _check_valid(data_iter: Iterable[torch.Tensor]) -> bool:
+ def _check_valid(data_iter: Iterable[Tensor]) -> bool:
if not all(data.shape[0] for data in data_iter):
raise ValueError("Arguments shapes must match")
return True
@staticmethod
- def _check_valid_params(data: torch.Tensor, data_name: str) -> bool:
+ def _check_valid_params(data: Tensor, data_name: str) -> bool:
if len(data.shape) not in (3, 4) and data.shape[-2:] != (4, 4): # Shouldn't this be an OR logic than AND?
raise ValueError(
"Argument {} shape must be in the following shape"
@@ -56,7 +55,7 @@ class PinholeCamera:
return True
@staticmethod
- def _check_valid_shape(data: torch.Tensor, data_name: str) -> bool:
+ def _check_valid_shape(data: Tensor, data_name: str) -> bool:
if not len(data.shape) == 1:
raise ValueError(
"Argument {} shape must be in the following shape" " B. Got {}".format(data_name, data.shape)
@@ -64,7 +63,7 @@ class PinholeCamera:
return True
@staticmethod
- def _check_consistent_device(data_iter: List[torch.Tensor]) -> None:
+ def _check_consistent_device(data_iter: List[Tensor]) -> None:
first = data_iter[0]
for data in data_iter:
KORNIA_CHECK_SAME_DEVICE(data, first)
@@ -78,7 +77,7 @@ class PinholeCamera:
return self._intrinsics.device
@property
- def intrinsics(self) -> torch.Tensor:
+ def intrinsics(self) -> Tensor:
r"""The full 4x4 intrinsics matrix.
Returns:
@@ -89,7 +88,7 @@ class PinholeCamera:
return self._intrinsics
@property
- def extrinsics(self) -> torch.Tensor:
+ def extrinsics(self) -> Tensor:
r"""The full 4x4 extrinsics matrix.
Returns:
@@ -109,7 +108,7 @@ class PinholeCamera:
return self.intrinsics.shape[0]
@property
- def fx(self) -> torch.Tensor:
+ def fx(self) -> Tensor:
r"""Return the focal length in the x-direction.
Returns:
@@ -118,7 +117,7 @@ class PinholeCamera:
return self.intrinsics[..., 0, 0]
@property
- def fy(self) -> torch.Tensor:
+ def fy(self) -> Tensor:
r"""Return the focal length in the y-direction.
Returns:
@@ -127,7 +126,7 @@ class PinholeCamera:
return self.intrinsics[..., 1, 1]
@property
- def cx(self) -> torch.Tensor:
+ def cx(self) -> Tensor:
r"""Return the x-coordinate of the principal point.
Returns:
@@ -136,7 +135,7 @@ class PinholeCamera:
return self.intrinsics[..., 0, 2]
@property
- def cy(self) -> torch.Tensor:
+ def cy(self) -> Tensor:
r"""Return the y-coordinate of the principal point.
Returns:
@@ -145,7 +144,7 @@ class PinholeCamera:
return self.intrinsics[..., 1, 2]
@property
- def tx(self) -> torch.Tensor:
+ def tx(self) -> Tensor:
r"""Return the x-coordinate of the translation vector.
Returns:
@@ -160,7 +159,7 @@ class PinholeCamera:
return self
@property
- def ty(self) -> torch.Tensor:
+ def ty(self) -> Tensor:
r"""Return the y-coordinate of the translation vector.
Returns:
@@ -175,7 +174,7 @@ class PinholeCamera:
return self
@property
- def tz(self) -> torch.Tensor:
+ def tz(self) -> Tensor:
r"""Returns the z-coordinate of the translation vector.
Returns:
@@ -190,7 +189,7 @@ class PinholeCamera:
return self
@property
- def rt_matrix(self) -> torch.Tensor:
+ def rt_matrix(self) -> Tensor:
r"""Return the 3x4 rotation-translation matrix.
Returns:
@@ -199,7 +198,7 @@ class PinholeCamera:
return self.extrinsics[..., :3, :4]
@property
- def camera_matrix(self) -> torch.Tensor:
+ def camera_matrix(self) -> Tensor:
r"""Return the 3x3 camera matrix containing the intrinsics.
Returns:
@@ -208,7 +207,7 @@ class PinholeCamera:
return self.intrinsics[..., :3, :3]
@property
- def rotation_matrix(self) -> torch.Tensor:
+ def rotation_matrix(self) -> Tensor:
r"""Return the 3x3 rotation matrix from the extrinsics.
Returns:
@@ -217,7 +216,7 @@ class PinholeCamera:
return self.extrinsics[..., :3, :3]
@property
- def translation_vector(self) -> torch.Tensor:
+ def translation_vector(self) -> Tensor:
r"""Return the translation vector from the extrinsics.
Returns:
@@ -227,13 +226,13 @@ class PinholeCamera:
def clone(self) -> 'PinholeCamera':
r"""Return a deep copy of the current object instance."""
- height: torch.Tensor = self.height.clone()
- width: torch.Tensor = self.width.clone()
- intrinsics: torch.Tensor = self.intrinsics.clone()
- extrinsics: torch.Tensor = self.extrinsics.clone()
+ height: Tensor = self.height.clone()
+ width: Tensor = self.width.clone()
+ intrinsics: Tensor = self.intrinsics.clone()
+ extrinsics: Tensor = self.extrinsics.clone()
return PinholeCamera(intrinsics, extrinsics, height, width)
- def intrinsics_inverse(self) -> torch.Tensor:
+ def intrinsics_inverse(self) -> Tensor:
r"""Return the inverse of the 4x4 instrisics matrix.
Returns:
@@ -253,14 +252,14 @@ class PinholeCamera:
the camera model with scaled parameters.
"""
# scale the intrinsic parameters
- intrinsics: torch.Tensor = self.intrinsics.clone()
+ intrinsics: Tensor = self.intrinsics.clone()
intrinsics[..., 0, 0] *= scale_factor
intrinsics[..., 1, 1] *= scale_factor
intrinsics[..., 0, 2] *= scale_factor
intrinsics[..., 1, 2] *= scale_factor
# scale the image height/width
- height: torch.Tensor = scale_factor * self.height.clone()
- width: torch.Tensor = scale_factor * self.width.clone()
+ height: Tensor = scale_factor * self.height.clone()
+ width: Tensor = scale_factor * self.width.clone()
return PinholeCamera(intrinsics, self.extrinsics, height, width)
def scale_(self, scale_factor) -> 'PinholeCamera':
@@ -284,7 +283,7 @@ class PinholeCamera:
self.width *= scale_factor
return self
- def project(self, point_3d: torch.Tensor) -> torch.Tensor:
+ def project(self, point_3d: Tensor) -> Tensor:
r"""Project a 3d point in world coordinates onto the 2d camera plane.
Args:
@@ -308,7 +307,7 @@ class PinholeCamera:
P = self.intrinsics @ self.extrinsics
return convert_points_from_homogeneous(transform_points(P, point_3d))
- def unproject(self, point_2d: torch.Tensor, depth: torch.Tensor):
+ def unproject(self, point_2d: Tensor, depth: Tensor):
r"""Unproject a 2d point in 3d.
Transform coordinates in the pixel frame to the world frame.
@@ -344,19 +343,7 @@ class PinholeCamera:
# NOTE: just for test. Decide if we keep it.
@classmethod
def from_parameters(
- self,
- fx,
- fy,
- cx,
- cy,
- height,
- width,
- tx,
- ty,
- tz,
- batch_size=1,
- device: Optional[torch.device] = None,
- dtype: Optional[torch.dtype] = None,
+ self, fx, fy, cx, cy, height, width, tx, ty, tz, batch_size, device: Device, dtype: torch.dtype
):
# create the camera matrix
intrinsics = torch.zeros(batch_size, 4, 4, device=device, dtype=dtype)
@@ -412,10 +399,10 @@ class PinholeCamerasList(PinholeCamera):
intrinsics.append(pinhole.intrinsics)
extrinsics.append(pinhole.extrinsics)
# contatenate and set members. We will assume BxNx4x4
- self.height: torch.Tensor = torch.stack(height, dim=1)
- self.width: torch.Tensor = torch.stack(width, dim=1)
- self._intrinsics: torch.Tensor = torch.stack(intrinsics, dim=1)
- self._extrinsics: torch.Tensor = torch.stack(extrinsics, dim=1)
+ self.height: Tensor = torch.stack(height, dim=1)
+ self.width: Tensor = torch.stack(width, dim=1)
+ self._intrinsics: Tensor = torch.stack(intrinsics, dim=1)
+ self._extrinsics: Tensor = torch.stack(extrinsics, dim=1)
return self
@property
@@ -428,14 +415,14 @@ class PinholeCamerasList(PinholeCamera):
def get_pinhole(self, idx: int) -> PinholeCamera:
r"""Return a PinholeCamera object with parameters such as Bx4x4."""
- height: torch.Tensor = self.height[..., idx]
- width: torch.Tensor = self.width[..., idx]
- intrinsics: torch.Tensor = self.intrinsics[:, idx]
- extrinsics: torch.Tensor = self.extrinsics[:, idx]
+ height: Tensor = self.height[..., idx]
+ width: Tensor = self.width[..., idx]
+ intrinsics: Tensor = self.intrinsics[:, idx]
+ extrinsics: Tensor = self.extrinsics[:, idx]
return PinholeCamera(intrinsics, extrinsics, height, width)
-def pinhole_matrix(pinholes: torch.Tensor, eps: float = 1e-6) -> torch.Tensor:
+def pinhole_matrix(pinholes: Tensor, eps: float = 1e-6) -> Tensor:
r"""Function that returns the pinhole matrix from a pinhole model.
.. note::
@@ -479,7 +466,7 @@ def pinhole_matrix(pinholes: torch.Tensor, eps: float = 1e-6) -> torch.Tensor:
return k
-def inverse_pinhole_matrix(pinhole: torch.Tensor, eps: float = 1e-6) -> torch.Tensor:
+def inverse_pinhole_matrix(pinhole: Tensor, eps: float = 1e-6) -> Tensor:
r"""Return the inverted pinhole matrix from a pinhole model.
.. note::
@@ -523,7 +510,7 @@ def inverse_pinhole_matrix(pinhole: torch.Tensor, eps: float = 1e-6) -> torch.Te
return k
-def scale_pinhole(pinholes: torch.Tensor, scale: torch.Tensor) -> torch.Tensor:
+def scale_pinhole(pinholes: Tensor, scale: Tensor) -> Tensor:
r"""Scale the pinhole matrix for each pinhole model.
.. note::
@@ -561,7 +548,7 @@ def scale_pinhole(pinholes: torch.Tensor, scale: torch.Tensor) -> torch.Tensor:
return pinholes_scaled
-def get_optical_pose_base(pinholes: torch.Tensor) -> torch.Tensor:
+def get_optical_pose_base(pinholes: Tensor) -> Tensor:
"""Compute extrinsic transformation matrices for pinholes.
Args:
@@ -582,7 +569,7 @@ def get_optical_pose_base(pinholes: torch.Tensor) -> torch.Tensor:
# return rtvec_to_pose(optical_pose_parent) type: ignore
-def homography_i_H_ref(pinhole_i: torch.Tensor, pinhole_ref: torch.Tensor) -> torch.Tensor:
+def homography_i_H_ref(pinhole_i: Tensor, pinhole_ref: Tensor) -> Tensor:
r"""Homography from reference to ith pinhole.
.. note::
@@ -633,7 +620,7 @@ def homography_i_H_ref(pinhole_i: torch.Tensor, pinhole_ref: torch.Tensor) -> to
# https://github.com/ClementPinard/SfmLearner-Pytorch/blob/master/inverse_warp.py#L26
-def pixel2cam(depth: torch.Tensor, intrinsics_inv: torch.Tensor, pixel_coords: torch.Tensor) -> torch.Tensor:
+def pixel2cam(depth: Tensor, intrinsics_inv: Tensor, pixel_coords: Tensor) -> Tensor:
r"""Transform coordinates in the pixel frame to the camera frame.
Args:
@@ -650,7 +637,7 @@ def pixel2cam(depth: torch.Tensor, intrinsics_inv: torch.Tensor, pixel_coords: t
raise ValueError("Input intrinsics_inv has to be in the shape of " "Bx4x4. Got {}".format(intrinsics_inv.shape))
if not len(pixel_coords.shape) == 4 and pixel_coords.shape[3] == 3:
raise ValueError("Input pixel_coords has to be in the shape of " "BxHxWx3. Got {}".format(intrinsics_inv.shape))
- cam_coords: torch.Tensor = transform_points(intrinsics_inv[:, None], pixel_coords)
+ cam_coords: Tensor = transform_points(intrinsics_inv[:, None], pixel_coords)
return cam_coords * depth.permute(0, 2, 3, 1)
@@ -658,7 +645,7 @@ def pixel2cam(depth: torch.Tensor, intrinsics_inv: torch.Tensor, pixel_coords: t
# https://github.com/ClementPinard/SfmLearner-Pytorch/blob/master/inverse_warp.py#L43
-def cam2pixel(cam_coords_src: torch.Tensor, dst_proj_src: torch.Tensor, eps: float = 1e-12) -> torch.Tensor:
+def cam2pixel(cam_coords_src: Tensor, dst_proj_src: Tensor, eps: float = 1e-12) -> Tensor:
r"""Transform coordinates in the camera frame to the pixel frame.
Args:
@@ -677,17 +664,17 @@ def cam2pixel(cam_coords_src: torch.Tensor, dst_proj_src: torch.Tensor, eps: flo
if not len(dst_proj_src.shape) == 3 and dst_proj_src.shape[-2:] == (4, 4):
raise ValueError("Input dst_proj_src has to be in the shape of " "Bx4x4. Got {}".format(dst_proj_src.shape))
# apply projection matrix to points
- point_coords: torch.Tensor = transform_points(dst_proj_src[:, None], cam_coords_src)
- x_coord: torch.Tensor = point_coords[..., 0]
- y_coord: torch.Tensor = point_coords[..., 1]
- z_coord: torch.Tensor = point_coords[..., 2]
+ point_coords: Tensor = transform_points(dst_proj_src[:, None], cam_coords_src)
+ x_coord: Tensor = point_coords[..., 0]
+ y_coord: Tensor = point_coords[..., 1]
+ z_coord: Tensor = point_coords[..., 2]
# compute pixel coordinates
- u_coord: torch.Tensor = x_coord / (z_coord + eps)
- v_coord: torch.Tensor = y_coord / (z_coord + eps)
+ u_coord: Tensor = x_coord / (z_coord + eps)
+ v_coord: Tensor = y_coord / (z_coord + eps)
# stack and return the coordinates, that's the actual flow
- pixel_coords_dst: torch.Tensor = torch.stack([u_coord, v_coord], dim=-1)
+ pixel_coords_dst: Tensor = torch.stack([u_coord, v_coord], dim=-1)
return pixel_coords_dst # BxHxWx2
diff --git a/kornia/geometry/quaternion.py b/kornia/geometry/quaternion.py
index 1ef8034c8..858f52dad 100644
--- a/kornia/geometry/quaternion.py
+++ b/kornia/geometry/quaternion.py
@@ -138,7 +138,7 @@ class Quaternion(Module):
def __truediv__(self, right: 'Quaternion') -> 'Quaternion':
return self.__div__(right)
- def __pow__(self, t: 'int') -> 'Quaternion':
+ def __pow__(self, t: Union[int, float]) -> 'Quaternion':
"""Return the power of a quaternion raised to exponent t.
Args:
diff --git a/kornia/nerf/data_utils.py b/kornia/nerf/data_utils.py
index b2fe7ddb6..835071ae7 100755
--- a/kornia/nerf/data_utils.py
+++ b/kornia/nerf/data_utils.py
@@ -63,7 +63,8 @@ class RayDataset(Dataset):
self._check_dimensions(self._imgs)
# Move images to defined device
- self._imgs = [img.to(self._device) for img in self._imgs]
+ if self._imgs is not None:
+ self._imgs = [img.to(self._device) for img in self._imgs]
def _init_random_ray_dataset(self, num_img_rays: Tensor) -> None:
r"""Initializes a random ray sampler and calculates dataset ray parameters.
@@ -121,10 +122,14 @@ class RayDataset(Dataset):
A ray parameter object that includes ray origins, directions, and rgb values at the ray 2d pixel
coordinates: RayGroup
"""
+ if not isinstance(self._ray_sampler, RaySampler):
+ raise TypeError('Ray sampler is not initiate yet, please run self.init_ray_dataset() before use it.')
+
origins = self._ray_sampler.origins[idxs]
directions = self._ray_sampler.directions[idxs]
if self._imgs is None:
return origins, directions, None
+
camerd_ids = self._ray_sampler.camera_ids[idxs]
points_2d = self._ray_sampler.points_2d[idxs]
rgbs = None
@@ -136,7 +141,7 @@ class RayDataset(Dataset):
return origins, directions, rgbs
-def instantiate_ray_dataloader(dataset: RayDataset, batch_size: int = 1, shuffle: bool = True) -> None:
+def instantiate_ray_dataloader(dataset: RayDataset, batch_size: int = 1, shuffle: bool = True) -> DataLoader:
r"""Initializes a dataloader to manage a ray dataset.
Args:
diff --git a/kornia/nerf/nerf_solver.py b/kornia/nerf/nerf_solver.py
index 9421e2f6c..c12f56645 100755
--- a/kornia/nerf/nerf_solver.py
+++ b/kornia/nerf/nerf_solver.py
@@ -6,7 +6,7 @@ import torch.nn.functional as F
import torch.optim as optim
from torch import nn
-from kornia.core import Device
+from kornia.core import Module, Tensor, tensor
from kornia.geometry.camera import PinholeCamera
from kornia.metrics import psnr
from kornia.nerf.core import Images, ImageTensors
@@ -22,25 +22,24 @@ class NerfSolver:
device: device for class tensors: Union[str, torch.device]
dtype: type for all floating point calculations: torch.dtype
"""
+ _nerf_model: Module
+ _opt_nerf: optim.Optimizer
- def __init__(self, device: Device, dtype: torch.dtype) -> None:
+ def __init__(self, device: torch.device, dtype: torch.dtype) -> None:
self._cameras: Optional[PinholeCamera] = None
self._min_depth: float = 0.0
self._max_depth: float = 0.0
self._ndc: bool = True
self._imgs: Optional[Images] = None
- self._num_img_rays: Optional[int] = None
+ self._num_img_rays: Optional[Union[Tensor, int]] = None
self._batch_size: int = 0
- self._nerf_model: Optional[nn.Module] = None
self._num_ray_points: int = 0
self._nerf_optimizaer: Optional[optim.Optimizer] = None
- self._opt_nerf: optim.Optimizer = None
-
self._device = device
self._dtype = dtype
@@ -51,7 +50,7 @@ class NerfSolver:
max_depth: float,
ndc: bool,
imgs: Images,
- num_img_rays: Optional[Union[torch.tensor, int]],
+ num_img_rays: Optional[Union[Tensor, int]],
batch_size: int,
num_ray_points: int,
irregular_ray_sampling: bool = True,
@@ -81,13 +80,15 @@ class NerfSolver:
self._ndc = ndc
self._imgs = imgs
- self._num_img_rays = None
- if isinstance(num_img_rays, int):
- self._num_img_rays = torch.tensor([num_img_rays] * cameras.batch_size)
+
+ if num_img_rays is None:
+ self._num_img_rays = None
+ elif isinstance(num_img_rays, int):
+ self._num_img_rays = tensor([num_img_rays] * cameras.batch_size)
elif torch.is_tensor(num_img_rays):
self._num_img_rays = num_img_rays
- elif num_img_rays is not None:
- raise TypeError('num_img_rays can be either an int or a torch.tensor')
+ else:
+ raise TypeError('num_img_rays can be either an int or a Tensor')
self._batch_size = batch_size
@@ -143,17 +144,17 @@ class NerfSolver:
ray_dataset.init_ray_dataset(self._num_img_rays)
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 = 0.0
+ total_psnr = tensor(0.0, device=self._device, dtype=self._dtype)
for i_batch, (origins, directions, rgbs) in enumerate(ray_data_loader):
rgbs_model = self._nerf_model(origins, directions)
loss = F.mse_loss(rgbs_model, rgbs)
- total_psnr += psnr(rgbs_model, rgbs, 1.0)
+ total_psnr = psnr(rgbs_model, rgbs, 1.0) + total_psnr
self._opt_nerf.zero_grad()
loss.backward()
self._opt_nerf.step()
- return total_psnr / (i_batch + 1)
+ return float(total_psnr / (i_batch + 1))
def run(self, num_epochs: int = 1) -> None:
r"""Runs training epochs.
diff --git a/kornia/nerf/positional_encoder.py b/kornia/nerf/positional_encoder.py
index 425977aef..eaa5dbb9c 100755
--- a/kornia/nerf/positional_encoder.py
+++ b/kornia/nerf/positional_encoder.py
@@ -1,9 +1,19 @@
+from functools import partial
+
import torch
from torch import nn
from kornia.core import Tensor
+def _torch_sin(x: Tensor, freq: Tensor) -> Tensor:
+ return (x * freq).sin() # FIXME: PI?
+
+
+def _torch_cos(x: Tensor, freq: Tensor) -> Tensor:
+ return (x * freq).cos()
+
+
class PositionalEncoder(nn.Module):
r"""Sine-cosine positional encoder for input points.
@@ -19,6 +29,7 @@ class PositionalEncoder(nn.Module):
self._embed_fns = [lambda x: x]
# Define frequencies in either linear or log scale
+ freq_bands: Tensor
if log_space:
freq_bands = 2.0 ** torch.linspace(0.0, num_freqs - 1, num_freqs)
else:
@@ -26,8 +37,8 @@ class PositionalEncoder(nn.Module):
# Alternate sin and cos
for freq in freq_bands:
- self._embed_fns.append(lambda x, freq=freq: torch.sin(x * freq)) # FIXME: PI?
- self._embed_fns.append(lambda x, freq=freq: torch.cos(x * freq))
+ self._embed_fns.append(partial(_torch_sin, freq=freq))
+ self._embed_fns.append(partial(_torch_cos, freq=freq))
self._num_encoded_dims = self._num_dims * len(self._embed_fns)
diff --git a/kornia/nerf/rays.py b/kornia/nerf/rays.py
index 8c46068f3..985dc365a 100755
--- a/kornia/nerf/rays.py
+++ b/kornia/nerf/rays.py
@@ -1,9 +1,9 @@
import math
-from typing import Dict, List, Optional, Tuple
+from typing import Dict, List, Tuple
import torch
-from kornia.core import Device, Tensor
+from kornia.core import Device, Tensor, tensor
from kornia.geometry.camera import PinholeCamera
from kornia.nerf.camera_utils import cameras_for_ids
from kornia.utils._compat import torch_meshgrid
@@ -19,12 +19,12 @@ class RaySampler:
ndc: convert ray parameters to normalized device coordinates: bool
device: device for ray tensors: Union[str, torch.device]
"""
- _origins: Optional[Tensor] = None # Ray origins in world coordinates (*, 3)
- _directions: Optional[Tensor] = None # Ray directions in world coordinates (*, 3)
- _directions_cam: Optional[Tensor] = None # Ray directions in camera coordinates (*, 3)
- _origins_cam: Optional[Tensor] = None # Ray origins in camera coordinates (*, 3)
- _camera_ids: Optional[Tensor] = None # Ray camera ID
- _points_2d: Optional[Tensor] = None # Ray intersection with image plane in camera coordinates
+ _origins: Tensor # Ray origins in world coordinates (*, 3)
+ _directions: Tensor # Ray directions in world coordinates (*, 3)
+ _directions_cam: Tensor # Ray directions in camera coordinates (*, 3)
+ _origins_cam: Tensor # Ray origins in camera coordinates (*, 3)
+ _camera_ids: Tensor # Ray camera ID
+ _points_2d: Tensor # Ray intersection with image plane in camera coordinates
def __init__(self, min_depth: float, max_depth: float, ndc: bool, device: Device, dtype: torch.dtype) -> None:
self._min_depth = min_depth
@@ -125,7 +125,7 @@ class RaySampler:
directions_cam.append(self._calc_ray_directions_cam(cams, obj._points_2d))
origins_cam.append(directions_cam[-1] * self._min_depth)
camera_ids.append(
- torch.tensor(obj.camera_ids).repeat(num_points_per_cam_group, 1).permute(1, 0).reshape(1, -1).squeeze(0)
+ tensor(obj.camera_ids).repeat(num_points_per_cam_group, 1).permute(1, 0).reshape(1, -1).squeeze(0)
)
points_2d.append(obj._points_2d.reshape(-1, 2).int())
self._origins = torch.cat(origins)
@@ -199,11 +199,7 @@ class RaySampler:
@staticmethod
def _add_points2d_as_flat_tensors_to_num_ray_dict(
- n: int,
- x: torch.tensor,
- y: torch.tensor,
- camera_id: int,
- points2d_as_flat_tensors: Dict[int, Points2D_FlatTensors],
+ n: int, x: Tensor, y: Tensor, camera_id: int, points2d_as_flat_tensors: Dict[int, Points2D_FlatTensors]
) -> None:
r"""Adds x/y pixel coordinates for all rays casted by a scene camera to dictionary of pixel coordinates
grouped by total number of rays."""
diff --git a/kornia/nerf/renderer.py b/kornia/nerf/renderer.py
index 495293ce7..064c94fcd 100755
--- a/kornia/nerf/renderer.py
+++ b/kornia/nerf/renderer.py
@@ -29,7 +29,7 @@ class VolumeRenderer(torch.nn.Module):
return rgbs_rendered
- def forward(self, rgbs: Tensor, densities: Tensor, points_3d: torch.tensor) -> Tensor:
+ def forward(self, rgbs: Tensor, densities: Tensor, points_3d: Tensor) -> Tensor:
raise NotImplementedError
@@ -37,7 +37,7 @@ class IrregularRenderer(VolumeRenderer):
def __init__(self, shift: int = 1) -> None:
super().__init__(shift)
- def forward(self, rgbs: Tensor, densities: Tensor, points_3d: torch.tensor) -> Tensor:
+ def forward(self, rgbs: Tensor, densities: Tensor, points_3d: Tensor) -> Tensor:
r"""Renders 3D irregularly sampled points along rays.
Args:
@@ -62,7 +62,7 @@ class RegularRenderer(VolumeRenderer):
def __init__(self, shift: int = 1) -> None:
super().__init__(shift)
- def forward(self, rgbs: Tensor, densities: Tensor, points_3d: torch.tensor) -> Tensor:
+ def forward(self, rgbs: Tensor, densities: Tensor, points_3d: Tensor) -> Tensor:
r"""Renders 3D regularly sampled points along rays.
Args: