Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

Bug fixes for RandomRotation3D & Initiated RandomAffine3D

Jian S5d05c6c590e8
diff --git a/kornia/augmentation/augmentation3d.py b/kornia/augmentation/augmentation3d.py
index 0e2edef5b..6a8d0819e 100644
--- a/kornia/augmentation/augmentation3d.py
+++ b/kornia/augmentation/augmentation3d.py
@@ -5,11 +5,11 @@ import torch.nn as nn
from torch.nn.functional import pad
from kornia.constants import Resample, BorderType
-from .augmentation import AugmentationBase
-from . import functional3d as F
-from . import random_generator as rg
-from . import random_generator3d as rg3
-from .utils import (
+from kornia.augmentation.augmentation import AugmentationBase
+from kornia.augmentation import functional3d as F
+from kornia.augmentation import random_generator as rg
+from kornia.augmentation import random_generator3d as rg3
+from kornia.augmentation.utils import (
_infer_batch_shape3d
)
@@ -189,6 +189,69 @@ class RandomDepthicalFlip3D(AugmentationBase3D):
return F.apply_dflip3d(input, params)
+class RandomAffine3D(AugmentationBase3D):
+ r"""Random 3D affine transformation of the image keeping center invariant.
+
+ Args:
+ degrees (float or tuple or list): Range of degrees to select from.
+ If degrees is a number, then yaw, pitch, roll will be generated from the range of (-degrees, +degrees).
+ If degrees is a tuple of (min, max), then yaw, pitch, roll will be generated from the range of (min, max).
+ If degrees is a list of floats [a, b, c], then yaw, pitch, roll will be generated from (-a, a), (-b, b)
+ and (-c, c).
+ If degrees is a list of tuple ((a, b), (m, n), (x, y)), then yaw, pitch, roll will be generated from
+ (a, b), (m, n) and (x, y).
+ Set to 0 to deactivate rotations.
+ translate (tuple, 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
+ randomly sampled in the range -img_height * b < dy < img_height * b. Will not translate by default.
+ scale (tuple, optional): scaling factor interval, e.g (a, b), then scale is
+ randomly sampled from the range a <= scale <= b. Will keep original scale by default.
+ shear (sequence or float, optional): Range of degrees to select from.
+ If shear is a number, a shear parallel to the x axis in the range (-shear, +shear)
+ will be apllied. Else if shear is a tuple or list of 2 values a shear parallel to the x axis in the
+ range (shear[0], shear[1]) will be applied. Else if shear is a tuple or list of 4 values,
+ a x-axis shear in (shear[0], shear[1]) and y-axis shear in (shear[2], shear[3]) will be applied.
+ Will not apply shear by default
+ resample (int, str or kornia.Resample): Default: Resample.BILINEAR
+ return_transform (bool): if ``True`` return the matrix describing the transformation
+ applied to each. Default: False.
+ same_on_batch (bool): apply the same transformation across the batch. Default: False
+ """
+
+ def __init__(
+ self, degrees: Union[float, Tuple[float, float, float]],
+ translate: Optional[Tuple[float, float, float]] = None, scale: Optional[Tuple[float, float]] = None,
+ shear: Optional[Union[float, Tuple[float, float]]] = None,
+ resample: Union[str, int, Resample] = Resample.BILINEAR.name,
+ return_transform: bool = False, same_on_batch: bool = False, align_corners: bool = False
+ ) -> None:
+ super(RandomAffine3D, self).__init__(return_transform)
+ self.degrees = degrees
+ self.translate = translate
+ self.scale = scale
+ self.shear = shear
+ self.resample: Resample = Resample.get(resample)
+ self.same_on_batch = same_on_batch
+ self.align_corners = align_corners
+
+ def __repr__(self) -> str:
+ repr = f"(degrees={self.degrees}, translate={self.translate}, scale={self.scale}, shear={self.shear}, "
+ f"resample={self.resample.name}, return_transform={self.return_transform}, same_on_batch={self.same_on_batch}"
+ return self.__class__.__name__ + repr
+
+ def generate_parameters(self, batch_shape: torch.Size) -> Dict[str, torch.Tensor]:
+ return rg3.random_affine_generator3d(
+ batch_shape[0], batch_shape[-3], batch_shape[-2], batch_shape[-1], self.degrees,
+ self.translate, self.scale, self.shear, self.resample, self.same_on_batch, self.align_corners)
+
+ def compute_transformation(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:
+ return F.compute_affine_transformation3d(input, params)
+
+ def apply_transform(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:
+ return F.apply_affine3d(input, params)
+
+
class RandomRotation3D(AugmentationBase3D):
r"""Rotate a tensor image or a batch of tensor images a random amount of degrees.
@@ -212,6 +275,26 @@ class RandomRotation3D(AugmentationBase3D):
input tensor. If ``False`` and the input is a tuple the applied transformation
wont be concatenated
same_on_batch (bool): apply the same transformation across the batch. Default: False
+
+ Examples:
+ >>> rng = torch.manual_seed(0)
+ >>> input = torch.rand(1, 1, 3, 3, 3)
+ >>> aug = RandomRotation3D((15., 20., 20.), return_transform=True)
+ >>> aug(input)
+ (tensor([[[[[0.4963, 0.5013, 0.2314],
+ [0.1015, 0.3624, 0.4779],
+ [0.2669, 0.5749, 0.4081]],
+ <BLANKLINE>
+ [[0.4426, 0.4198, 0.2713],
+ [0.2911, 0.1689, 0.4538],
+ [0.3939, 0.6022, 0.6166]],
+ <BLANKLINE>
+ [[0.1496, 0.3740, 0.3151],
+ [0.4169, 0.4803, 0.5804],
+ [0.3856, 0.4253, 0.9527]]]]]), tensor([[[ 0.9722, 0.1131, -0.2049, 0.1196],
+ [-0.0603, 0.9669, 0.2478, -0.1545],
+ [ 0.2262, -0.2286, 0.9469, 0.0556],
+ [ 0.0000, 0.0000, 0.0000, 1.0000]]]))
"""
def __init__(
self, degrees: Union[torch.Tensor, float, Tuple[float, float, float],
diff --git a/kornia/augmentation/functional3d.py b/kornia/augmentation/functional3d.py
index 14faad0cb..de20835ce 100644
--- a/kornia/augmentation/functional3d.py
+++ b/kornia/augmentation/functional3d.py
@@ -5,9 +5,14 @@ import torch
from . import random_generator as rg
from .utils import _transform_input3d, _validate_input_dtype
from kornia.constants import Resample, BorderType, pi
-from kornia.geometry.transform.affwarp import _compute_rotation_matrix3d, _compute_tensor_center3d
+from kornia.geometry.transform.affwarp import (
+ _compute_rotation_matrix3d, _compute_tensor_center3d
+)
+from kornia.geometry.transform.projwarp import warp_projective
from kornia.geometry import (
- rotate3d
+ rotate3d,
+ get_affine_matrix3d,
+ deg2rad
)
@@ -229,6 +234,77 @@ def compute_dflip_transformation3d(input: torch.Tensor, params: Dict[str, torch.
return trans_mat
+def apply_affine3d(input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:
+ r"""Random affine transformation of the image keeping center invariant.
+
+ Args:
+ input (torch.Tensor): Tensor to be transformed with shape (D, H, W), (C, D, H, W), (B, C, D, H, W).
+ params (Dict[str, torch.Tensor]):
+ - params['angles']: Degrees of rotation with the shape of :math: `(*, 3)` for yaw, pitch, roll.
+ - params['translations']: Horizontal and vertical translations.
+ - params['center']: Rotation center.
+ - params['scale']: Scaling params.
+ - params['sx']: Shear param toward x-axis.
+ - params['sy']: Shear param toward y-axis.
+ - params['sz']: Shear param toward y-axis.
+ - params['resample']: Integer tensor. NEAREST = 0, BILINEAR = 1.
+ - params['align_corners']: Boolean tensor.
+
+ Returns:
+ torch.Tensor: The transfromed input
+ """
+
+ if not torch.is_tensor(input):
+ raise TypeError(f"Input type is not a torch.Tensor. Got {type(input)}")
+
+ input = _transform_input3d(input)
+ _validate_input_dtype(input, accepted_dtypes=[torch.float16, torch.float32, torch.float64])
+
+ # arrange input data
+ x_data: torch.Tensor = input.view(-1, *input.shape[-4:])
+
+ depth, height, width = x_data.shape[-3:]
+
+ # concatenate transforms
+ transform: torch.Tensor = compute_affine_transformation3d(input, params)
+
+ resample_name: str = Resample(params['resample'].item()).name.lower()
+ align_corners: bool = cast(bool, params['align_corners'].item())
+
+ out_data: torch.Tensor = warp_projective(x_data, transform[:, :3, :],
+ (depth, height, width), resample_name,
+ align_corners=align_corners)
+ return out_data.view_as(input)
+
+
+def compute_affine_transformation3d(input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:
+ r"""Compute the applied transformation matrix :math: `(*, 4, 4)`.
+
+ Args:
+ input (torch.Tensor): Tensor to be transformed with shape (D, H, W), (C, D, H, W), (B, C, D, H, W).
+ params (Dict[str, torch.Tensor]):
+ - params['angles']: Degrees of rotation with the shape of :math: `(*, 3)` for yaw, pitch, roll.
+ - params['translations']: Depthical, Horizontal and vertical translations.
+ - params['center']: Rotation center.
+ - params['scale']: Scaling params.
+ - params['sx']: Shear param toward x-axis.
+ - params['sy']: Shear param toward y-axis.
+ - params['sz']: Shear param toward y-axis.
+ - params['resample']: Integer tensor. NEAREST = 0, BILINEAR = 1.
+ - params['align_corners']: Boolean tensor.
+
+ Returns:
+ torch.Tensor: The applied transformation matrix :math: `(*, 4, 4)`
+ """
+ input = _transform_input3d(input)
+ _validate_input_dtype(input, accepted_dtypes=[torch.float16, torch.float32, torch.float64])
+ transform = get_affine_matrix3d(
+ params['translations'], params['center'], params['scale'], params['angles'],
+ deg2rad(params['sx']), deg2rad(params['sy']), deg2rad(params['sz'])
+ ).type_as(input)
+ return transform
+
+
def apply_rotation3d(input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:
r"""Rotate a tensor image or a batch of tensor images a random amount of degrees.
Input should be a tensor of shape (C, H, W) or a batch of tensors :math:`(B, C, H, W)`.
@@ -283,4 +359,4 @@ def compute_rotate_tranformation3d(input: torch.Tensor, params: Dict[str, torch.
trans_mat[:, 1] = rotation_mat[:, 1]
trans_mat[:, 2] = rotation_mat[:, 2]
- return trans_mat
\ No newline at end of file
+ return trans_mat
diff --git a/kornia/augmentation/random_generator3d.py b/kornia/augmentation/random_generator3d.py
index 3c4114664..2207b318c 100644
--- a/kornia/augmentation/random_generator3d.py
+++ b/kornia/augmentation/random_generator3d.py
@@ -7,13 +7,14 @@ import torch
from kornia.constants import Resample, BorderType
from .utils import (
_adapted_uniform,
- _check_and_bound
+ _check_and_bound,
+ _rotation_range_reader
)
def random_rotation_generator3d(
batch_size: int,
- degrees: Union[torch.Tensor, float, Tuple[float, float, float],
+ degrees: Union[torch.Tensor, float, Tuple[float, float], Tuple[float, float, float],
Tuple[Tuple[float, float], Tuple[float, float], Tuple[float, float]]],
interpolation: Union[str, int, Resample] = Resample.BILINEAR.name,
same_on_batch: bool = False,
@@ -37,43 +38,159 @@ def random_rotation_generator3d(
Returns:
params Dict[str, torch.Tensor]: parameters to be passed for transformation.
"""
- if not torch.is_tensor(degrees):
- if isinstance(degrees, (float, int)):
- if degrees < 0:
- raise ValueError(f"If Degrees is only one number it must be a positive number. Got{degrees}")
- yaw = torch.tensor([-degrees, degrees]).to(torch.float32)
- pitch = torch.tensor([-degrees, degrees]).to(torch.float32)
- roll = torch.tensor([-degrees, degrees]).to(torch.float32)
-
- elif isinstance(degrees, (tuple)) and isinstance(degrees[0], (float, int)) and len(degrees) == 2:
- yaw = torch.tensor(degrees).to(torch.float32)
- pitch = torch.tensor(degrees).to(torch.float32)
- roll = torch.tensor(degrees).to(torch.float32)
-
- elif isinstance(degrees, (tuple)) and len(degrees) == 3 \
- and isinstance(degrees[0], (tuple)) and isinstance(degrees[1], (tuple)) and isinstance(degrees[2], (tuple)):
- yaw = torch.tensor(degrees[0]).to(torch.float32)
- pitch = torch.tensor(degrees[1]).to(torch.float32)
- roll = torch.tensor(degrees[2]).to(torch.float32)
+ _degrees = _rotation_range_reader(degrees)
- else:
- raise TypeError(f"Degrees should be a float number a sequence or a tensor. Got {type(degrees)}")
- else:
- # https://mypy.readthedocs.io/en/latest/casts.html cast to please mypy gods
- degrees = cast(torch.Tensor, degrees)
- if len(degrees) != 3 and len(degrees[0]) != len(degrees[1]) != len(degrees[2]) != 2:
- raise ValueError(
- f"Degrees must be a 3x2 tensor for the degree range of yaw, pitch, roll. Got {degrees.shape}")
- yaw = degrees[0]
- pitch = degrees[1]
- roll = degrees[2]
-
- yaw = _adapted_uniform((batch_size,), yaw[0], yaw[1], same_on_batch)
- pitch = _adapted_uniform((batch_size,), pitch[0], pitch[1], same_on_batch)
- roll = _adapted_uniform((batch_size,), roll[0], roll[1], same_on_batch)
+ yaw = _adapted_uniform((batch_size,), _degrees[0][0], _degrees[0][1], same_on_batch)
+ pitch = _adapted_uniform((batch_size,), _degrees[1][0], _degrees[1][1], same_on_batch)
+ roll = _adapted_uniform((batch_size,), _degrees[2][0], _degrees[2][1], same_on_batch)
return dict(yaw=yaw,
pitch=pitch,
roll=roll,
interpolation=torch.tensor(Resample.get(interpolation).value),
align_corners=torch.tensor(align_corners))
+
+
+def random_affine_generator3d(
+ batch_size: int,
+ depth: int,
+ height: int,
+ width: int,
+ degrees: Union[torch.Tensor, float, Tuple[float, float], Tuple[float, float, float],
+ Tuple[Tuple[float, float], Tuple[float, float], Tuple[float, float]]],
+ translate: Optional[Tuple[float, float, float]] = None,
+ scale: Optional[Tuple[float, float]] = None,
+ shear: Optional[Union[float, Tuple[float, float]]] = None,
+ resample: Union[str, int, Resample] = Resample.BILINEAR.name,
+ same_on_batch: bool = False,
+ align_corners: bool = False
+) -> Dict[str, torch.Tensor]:
+ r"""Get parameters for ``affine`` for a random affine transform.
+
+ Args:
+ batch_size (int): the tensor batch size.
+ depth (int) : height of the image.
+ height (int) : height of the image.
+ width (int): width of the image.
+ degrees (float or tuple): Range of degrees to select from.
+ If degrees is a number instead of sequence like (min, max), the range of degrees
+ will be (-degrees, +degrees). Set to 0 to deactivate rotations.
+ translate (tuple, 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
+ randomly sampled in the range -img_height * b < dy < img_height * b. Will not translate by default.
+ scale (tuple, optional): scaling factor interval, e.g (a, b), then scale is
+ randomly sampled from the range a <= scale <= b. Will keep original scale by default.
+ shear (sequence or float, optional): Range of degrees to select from.
+ If shear is a number, a shear parallel to the x axis in the range (-shear, +shear)
+ will be apllied. Else if shear is a tuple or list of 2 values a shear parallel to the x axis in the
+ range (shear[0], shear[1]) will be applied. Else if shear is a tuple or list of 4 values,
+ a x-axis shear in (shear[0], shear[1]) and y-axis shear in (shear[2], shear[3]) will be applied.
+ Will not apply shear by default
+ resample (int, str or kornia.Resample): Default: Resample.BILINEAR
+ same_on_batch (bool): apply the same transformation across the batch. Default: False
+ align_corners(bool): interpolation flag. Default: False.See
+ https://pytorch.org/docs/stable/nn.functional.html#torch.nn.functional.interpolate for detail
+
+ Returns:
+ params Dict[str, torch.Tensor]: parameters to be passed for transformation.
+ """
+ degrees_tmp = _rotation_range_reader(degrees)
+
+ # check translation range
+ if translate is not None:
+ assert isinstance(translate, (tuple, list)) and len(translate) == 3, \
+ "translate should be a list or tuple and it must be of length 3."
+ for t in translate:
+ if not (0.0 <= t <= 1.0):
+ raise ValueError("translation values should be between 0 and 1")
+
+ # check scale range
+ if scale is not None:
+ assert isinstance(scale, (tuple, list)) and len(scale) == 2, \
+ "scale should be a list or tuple and it must be of length 2."
+ for s in scale:
+ if s <= 0:
+ raise ValueError("scale values should be positive")
+
+ # check shear range
+ shear_tmp: Optional[Tuple[float, float]]
+ if shear is not None:
+ if isinstance(shear, float):
+ if shear < 0:
+ raise ValueError("If shear is a single number, it must be positive.")
+ shear_tmp = (-shear, shear)
+ else:
+ assert isinstance(shear, (tuple, list)) and len(shear) == 2, \
+ "shear should be a list or tuple and it must be of length 2."
+ shear_tmp = shear
+ else:
+ shear_tmp = shear
+
+ return _get_random_affine_params(
+ batch_size, depth, height, width, degrees_tmp, translate, scale, shear_tmp,
+ resample, same_on_batch, align_corners)
+
+
+def _get_random_affine_params(
+ batch_size: int,
+ depth: int,
+ height: int,
+ width: int,
+ degrees: torch.Tensor,
+ translate: Optional[Tuple[float, float, float]],
+ scales: Optional[Tuple[float, float]],
+ shears: Optional[Tuple[float, float]],
+ resample: Union[str, int, Resample] = Resample.BILINEAR.name,
+ same_on_batch: bool = False,
+ align_corners: bool = False
+) -> Dict[str, torch.Tensor]:
+ r"""Get parameters for ```affine``` transformation random affine transform.
+ The returned matrix is Bx4x4.
+
+ Returns:
+ params Dict[str, torch.Tensor]: parameters to be passed for transformation.
+ """
+ yaw = _adapted_uniform((batch_size,), degrees[0][0], degrees[0][1], same_on_batch)
+ pitch = _adapted_uniform((batch_size,), degrees[1][0], degrees[1][1], same_on_batch)
+ roll = _adapted_uniform((batch_size,), degrees[2][0], degrees[2][1], same_on_batch)
+ angles = torch.cat([yaw, pitch, roll], dim=-1).view((batch_size, -1))
+
+ # compute tensor ranges
+ if scales is not None:
+ scale = _adapted_uniform((batch_size,), scales[0], scales[1], same_on_batch)
+ else:
+ scale = torch.ones(batch_size)
+
+ if translate is not None:
+ max_dx: float = translate[0] * depth
+ max_dy: float = translate[1] * width
+ max_dz: float = translate[2] * height
+ translations = torch.stack([
+ _adapted_uniform((batch_size,), -max_dx, max_dx, same_on_batch),
+ _adapted_uniform((batch_size,), -max_dy, max_dy, same_on_batch),
+ _adapted_uniform((batch_size,), -max_dz, max_dz, same_on_batch)
+ ], dim=-1)
+ else:
+ translations = torch.zeros(batch_size, 3)
+
+ center: torch.Tensor = torch.tensor(
+ [depth, width, height], dtype=torch.float32).view(1, 3) / 2. - 0.5
+ center = center.expand(batch_size, -1)
+
+ if shears is not None:
+ sx = _adapted_uniform((batch_size,), shears[0], shears[1], same_on_batch)
+ sy = _adapted_uniform((batch_size,), shears[0], shears[1], same_on_batch)
+ sz = _adapted_uniform((batch_size,), shears[0], shears[1], same_on_batch)
+ else:
+ sx = sy = sz = torch.tensor([0] * batch_size)
+
+ return dict(translations=translations,
+ center=center,
+ scale=scale,
+ angles=angles,
+ sx=sx,
+ sy=sy,
+ sz=sz,
+ resample=torch.tensor(Resample.get(resample).value),
+ align_corners=torch.tensor(align_corners))
diff --git a/kornia/augmentation/utils.py b/kornia/augmentation/utils.py
index 3e0e45bef..9678287b5 100644
--- a/kornia/augmentation/utils.py
+++ b/kornia/augmentation/utils.py
@@ -1,4 +1,4 @@
-from typing import Tuple, Union, List
+from typing import Tuple, Union, List, cast
import torch
from torch.distributions import Uniform
@@ -162,3 +162,51 @@ def _check_and_bound(factor: Union[torch.Tensor, float, Tuple[float, float], Lis
f"The {name} should be a float number or a tuple with length 2 whose values move between {bounds}.")
return factor_bound
+
+
+def _rotation_range_reader(
+ degrees: Union[torch.Tensor, float, Tuple[float, float], Tuple[float, float, float],
+ Tuple[Tuple[float, float], Tuple[float, float], Tuple[float, float]]]
+) -> torch.Tensor:
+
+ if not torch.is_tensor(degrees):
+ if isinstance(degrees, (float, int)):
+ if degrees < 0:
+ raise ValueError(f"If Degrees is only one number it must be a positive number. Got{degrees}")
+ yaw = torch.tensor([-degrees, degrees]).to(torch.float32)
+ pitch = torch.tensor([-degrees, degrees]).to(torch.float32)
+ roll = torch.tensor([-degrees, degrees]).to(torch.float32)
+
+ elif isinstance(degrees, (tuple)) and len(degrees) == 2 \
+ and isinstance(degrees[0], (float, int)) and isinstance(degrees[1], (float, int)):
+ yaw = torch.tensor(degrees).to(torch.float32)
+ pitch = torch.tensor(degrees).to(torch.float32)
+ roll = torch.tensor(degrees).to(torch.float32)
+
+ elif isinstance(degrees, (tuple)) and len(degrees) == 3 \
+ and isinstance(degrees[0], (tuple)) and isinstance(degrees[1], (tuple)) \
+ and isinstance(degrees[2], (tuple)):
+ yaw = torch.tensor(degrees[0]).to(torch.float32)
+ pitch = torch.tensor(degrees[1]).to(torch.float32)
+ roll = torch.tensor(degrees[2]).to(torch.float32)
+
+ elif isinstance(degrees, (tuple)) and len(degrees) == 3 \
+ and isinstance(degrees[0], (float, int)) and isinstance(degrees[1], (float, int)) \
+ and isinstance(degrees[2], (float, int)):
+ yaw = torch.tensor((-degrees[0], degrees[0])).to(torch.float32)
+ pitch = torch.tensor((-degrees[1], degrees[1])).to(torch.float32)
+ roll = torch.tensor((-degrees[2], degrees[2])).to(torch.float32)
+ else:
+ raise TypeError(f"Degrees should be a float number a sequence or a tensor. Got {degrees}")
+
+ else:
+ # https://mypy.readthedocs.io/en/latest/casts.html cast to please mypy gods
+ degrees = cast(torch.Tensor, degrees)
+ if len(degrees) != 3 and len(degrees[0]) != len(degrees[1]) != len(degrees[2]) != 2:
+ raise ValueError(
+ f"Degrees must be a 3x2 tensor for the degree range of yaw, pitch, roll. Got {degrees.shape}")
+ yaw = degrees[0]
+ pitch = degrees[1]
+ roll = degrees[2]
+
+ return torch.stack([yaw, pitch, roll], dim=0)
diff --git a/kornia/geometry/conversions.py b/kornia/geometry/conversions.py
index 5e0f417e8..4fe36efba 100644
--- a/kornia/geometry/conversions.py
+++ b/kornia/geometry/conversions.py
@@ -137,12 +137,12 @@ def convert_affinematrix_to_homography(A: torch.Tensor) -> torch.Tensor:
def convert_affinematrix_to_homography3d(A: torch.Tensor) -> torch.Tensor:
- r"""Function that converts batch of affine matrices from [Bx3x4] to [Bx3x4].
+ r"""Function that converts batch of affine matrices from [Bx3x4] to [Bx4x4].
Examples::
>>> input = torch.rand(2, 3, 4) # Bx3x4
- >>> output = kornia.convert_affinematrix_to_homography(input) # Bx3x3
+ >>> output = kornia.convert_affinematrix_to_homography(input) # Bx4x4
"""
if not isinstance(A, torch.Tensor):
raise TypeError("Input type is not a torch.Tensor. Got {}".format(
diff --git a/kornia/geometry/transform/affwarp.py b/kornia/geometry/transform/affwarp.py
index 94bbdedb3..8143192e2 100644
--- a/kornia/geometry/transform/affwarp.py
+++ b/kornia/geometry/transform/affwarp.py
@@ -240,13 +240,13 @@ def rotate3d(tensor: torch.Tensor, yaw: torch.Tensor, pitch: torch.Tensor, roll:
if center is not None and not torch.is_tensor(center):
raise TypeError("Input center type is not a torch.Tensor. Got {}"
.format(type(center)))
- if len(tensor.shape) not in (3, 4,):
- raise ValueError("Invalid tensor shape, we expect CxHxW or BxCxHxW. "
+ if len(tensor.shape) not in (4, 5,):
+ raise ValueError("Invalid tensor shape, we expect CxDxHxW or BxCxDxHxW. "
"Got: {}".format(tensor.shape))
# compute the rotation center
if center is None:
- center = _compute_tensor_center(tensor)
+ center = _compute_tensor_center3d(tensor)
# compute the rotation matrix
# TODO: add broadcasting to get_rotation_matrix2d for center
diff --git a/kornia/geometry/transform/imgwarp.py b/kornia/geometry/transform/imgwarp.py
index ecdbff6bb..8d03fedc4 100644
--- a/kornia/geometry/transform/imgwarp.py
+++ b/kornia/geometry/transform/imgwarp.py
@@ -10,7 +10,7 @@ from kornia.geometry.conversions import (
deg2rad, normalize_pixel_coordinates, convert_affinematrix_to_homography, convert_affinematrix_to_homography3d
)
from kornia.geometry.transform.projwarp import (
- warp_projective
+ warp_projective, get_projective_transform
)
from kornia.testing import check_is_tensor
@@ -22,7 +22,8 @@ __all__ = [
"remap",
"invert_affine_transform",
"angle_to_rotation_matrix",
- "get_affine_matrix2d"
+ "get_affine_matrix2d",
+ "get_affine_matrix3d"
]
@@ -466,7 +467,7 @@ def get_affine_matrix2d(translations: torch.Tensor, center: torch.Tensor, scale:
# pad transform to get Bx3x3
transform_h = convert_affinematrix_to_homography(transform)
- if sx is not None:
+ if sx is not None or sy is not None:
x, y = torch.split(center, 1, dim=-1)
x = x.view(-1)
y = y.view(-1)
@@ -480,3 +481,36 @@ def get_affine_matrix2d(translations: torch.Tensor, center: torch.Tensor, scale:
shear_mat = convert_affinematrix_to_homography(shear_mat)
transform_h = transform_h @ shear_mat
return transform_h
+
+
+def get_affine_matrix3d(translations: torch.Tensor, center: torch.Tensor, scale: torch.Tensor, angles: torch.Tensor,
+ sx: Optional[torch.Tensor] = None, sy: Optional[torch.Tensor] = None,
+ sz: Optional[torch.Tensor] = None) -> torch.Tensor:
+ r"""Composes affine matrix Bx4x4 from the components
+ Returns:
+ torch.Tensor: params to be passed to the affine transformation.
+ """
+ # TODO: scale is not implemented here
+ transform: torch.Tensor = get_projective_transform(center, -angles)
+ transform[..., 3] += translations # tx/ty/tz
+ # pad transform to get Bx3x3
+ transform_h = convert_affinematrix_to_homography3d(transform)
+
+ if sx is not None or sy is not None or sz is not None:
+ x, y, z = torch.split(center, 1, dim=-1)
+ x = x.view(-1)
+ y = y.view(-1)
+ z = z.view(-1)
+ sx_tan = torch.tan(sx) # type: ignore
+ sy_tan = torch.tan(sy) # type: ignore
+ sz_tan = torch.tan(sz) # type: ignore
+ zeros = torch.zeros_like(sx) # type: ignore
+ ones = torch.ones_like(sx) # type: ignore
+ shear_mat = torch.stack([
+ ones, -sx_tan, -sx_tan, zeros,
+ -sy_tan, ones, -sy_tan, zeros,
+ -sz_tan, -sz_tan, ones, zeros,
+ ], dim=-1).view(-1, 3, 4)
+ shear_mat = convert_affinematrix_to_homography3d(shear_mat)
+ transform_h = transform_h @ shear_mat
+ return transform_h