π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
Initiated RandomRotation3D
Jian S86e7d58ee5ca
diff --git a/kornia/augmentation/augmentation3d.py b/kornia/augmentation/augmentation3d.pyindex 8b0d19adb..0e2edef5b 100644--- a/kornia/augmentation/augmentation3d.py+++ b/kornia/augmentation/augmentation3d.py@@ -8,6 +8,7 @@ from kornia.constants import Resample, BorderTypefrom .augmentation import AugmentationBasefrom . import functional3d as Ffrom . import random_generator as rg+from . import random_generator3d as rg3from .utils import (_infer_batch_shape3d)@@ -186,3 +187,55 @@ class RandomDepthicalFlip3D(AugmentationBase3D):def apply_transform(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:return F.apply_dflip3d(input, params)+++class RandomRotation3D(AugmentationBase3D):++ r"""Rotate a tensor image or a batch of tensor images a random amount of degrees.+ Input should be a tensor of shape (C, D, H, W) or a batch of tensors :math:`(B, C, D, H, W)`.+ If Input is a tuple it is assumed that the first element contains the aforementioned tensors and the second,+ the corresponding transformation matrix that has been applied to them. In this case the module+ will rotate the tensors and concatenate the corresponding transformation matrix to the+ previous one. This is especially useful when using this functionality as part of an ``nn.Sequential`` module.++ 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.+ interpolation (int, str or kornia.Resample): Default: Resample.BILINEAR+ return_transform (bool): if ``True`` return the matrix describing the transformation applied to each+ 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+ """+ def __init__(+ self, degrees: Union[torch.Tensor, float, Tuple[float, float, float],+ Tuple[Tuple[float, float], Tuple[float, float], Tuple[float, float]]],+ interpolation: Union[str, int, Resample] = Resample.BILINEAR.name,+ return_transform: bool = False, same_on_batch: bool = False, align_corners: bool = False+ ) -> None:+ super(RandomRotation3D, self).__init__(return_transform)+ self.degrees = degrees+ self.interpolation: Resample = Resample.get(interpolation)+ self.same_on_batch = same_on_batch+ self.align_corners = align_corners++ def __repr__(self) -> str:+ repr = f"(degrees={self.degrees}, interpolation={self.interpolation.name}, "+ f"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_rotation_generator3d(batch_shape[0], self.degrees, self.interpolation,+ self.same_on_batch, self.align_corners)++ def compute_transformation(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:+ return F.compute_rotate_tranformation3d(input, params)++ def apply_transform(self, input: torch.Tensor, params: Dict[str, torch.Tensor]) -> torch.Tensor:+ return F.apply_rotation3d(input, params)diff --git a/kornia/augmentation/functional3d.py b/kornia/augmentation/functional3d.pyindex f63034622..14faad0cb 100644--- a/kornia/augmentation/functional3d.py+++ b/kornia/augmentation/functional3d.py@@ -4,6 +4,11 @@ import torchfrom . import random_generator as rgfrom .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 import (+ rotate3d+)def random_hflip3d(input: torch.Tensor, p: float = 0.5, return_transform: bool = False@@ -222,3 +227,60 @@ def compute_dflip_transformation3d(input: torch.Tensor, params: Dict[str, torch.trans_mat[to_flip] = flip_mat.type_as(input)return trans_mat+++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)`.++ Args:+ input (torch.Tensor): Tensor to be transformed with shape (H, W), (C, H, W), (B, C, H, W).+ params (Dict[str, torch.Tensor]):+ - params['degrees']: degree to be applied.++ Returns:+ torch.Tensor: The cropped input+ """+ input = _transform_input3d(input)+ _validate_input_dtype(input, accepted_dtypes=[torch.float16, torch.float32, torch.float64])+ yaw: torch.Tensor = params["yaw"].type_as(input)+ pitch: torch.Tensor = params["pitch"].type_as(input)+ roll: torch.Tensor = params["roll"].type_as(input)++ resample_mode: str = Resample(params['interpolation'].item()).name.lower()+ align_corners: bool = cast(bool, params['align_corners'].item())++ transformed: torch.Tensor = rotate3d(input, yaw, pitch, roll, mode=resample_mode, align_corners=align_corners)++ return transformed+++def compute_rotate_tranformation3d(input: torch.Tensor, params: Dict[str, 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['yaw']: degree to be applied.+ - params['pitch']: degree to be applied.+ - params['roll']: degree to be applied.++ 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])+ yaw: torch.Tensor = params["yaw"].type_as(input)+ pitch: torch.Tensor = params["pitch"].type_as(input)+ roll: torch.Tensor = params["roll"].type_as(input)++ center: torch.Tensor = _compute_tensor_center3d(input)+ rotation_mat: torch.Tensor = _compute_rotation_matrix3d(yaw, pitch, roll, center.expand(yaw.shape[0], -1))++ # rotation_mat is B x 3 x 4 and we need a B x 4 x 4 matrix+ trans_mat: torch.Tensor = torch.eye(4, device=input.device, dtype=input.dtype).repeat(input.shape[0], 1, 1)+ trans_mat[:, 0] = rotation_mat[:, 0]+ trans_mat[:, 1] = rotation_mat[:, 1]+ trans_mat[:, 2] = rotation_mat[:, 2]++ return trans_mat\ No newline at end of filediff --git a/kornia/augmentation/random_generator3d.py b/kornia/augmentation/random_generator3d.pynew file mode 100644index 000000000..3c4114664--- /dev/null+++ b/kornia/augmentation/random_generator3d.py@@ -0,0 +1,79 @@+from typing import Tuple, List, Union, Dict, Optional, cast+import random+import math++import torch++from kornia.constants import Resample, BorderType+from .utils import (+ _adapted_uniform,+ _check_and_bound+)+++def random_rotation_generator3d(+ batch_size: int,+ degrees: Union[torch.Tensor, 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,+ align_corners: bool = False+) -> Dict[str, torch.Tensor]:+ r"""Get parameters for ``rotate`` for a random rotate transform.++ Args:+ batch_size (int): the tensor batch size.+ 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).+ interpolation (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.++ 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)++ 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)++ return dict(yaw=yaw,+ pitch=pitch,+ roll=roll,+ interpolation=torch.tensor(Resample.get(interpolation).value),+ align_corners=torch.tensor(align_corners))diff --git a/kornia/geometry/conversions.py b/kornia/geometry/conversions.pyindex f3115041e..640b8ce4e 100644--- a/kornia/geometry/conversions.py+++ b/kornia/geometry/conversions.py@@ -135,6 +135,25 @@ def convert_affinematrix_to_homography(A: torch.Tensor) -> torch.Tensor:return H+def convert_affinematrix_to_homography3d(A: torch.Tensor) -> torch.Tensor:+ r"""Function that converts batch of affine matrices from [Bx3x4] to [Bx3x4].++ Examples::++ >>> input = torch.rand(2, 3, 4) # Bx3x4+ >>> output = kornia.convert_affinematrix_to_homography(input) # Bx3x3+ """+ if not isinstance(A, torch.Tensor):+ raise TypeError("Input type is not a torch.Tensor. Got {}".format(+ type(A)))+ if not (len(A.shape) == 3 and A.shape[-2:] == (3, 4)):+ raise ValueError("Input matrix must be a Bx3x4 tensor. Got {}"+ .format(A.shape))+ H: torch.Tensor = torch.nn.functional.pad(A, [0, 0, 0, 1], "constant", value=0.)+ H[..., -1, -1] += 1.0+ return H++def angle_axis_to_rotation_matrix(angle_axis: torch.Tensor) -> torch.Tensor:r"""Convert 3d vector of axis-angle rotation to 3x3 rotation matrixdiff --git a/kornia/geometry/transform/affwarp.py b/kornia/geometry/transform/affwarp.pyindex 4103d94d2..b53c4a797 100644--- a/kornia/geometry/transform/affwarp.py+++ b/kornia/geometry/transform/affwarp.py@@ -4,13 +4,14 @@ import torchimport torch.nn as nnfrom kornia.geometry.transform.imgwarp import (- warp_affine, get_rotation_matrix2d,+ warp_affine, warp_affine3d, get_rotation_matrix2d, get_rotation_matrix3d)__all__ = ["affine","scale","rotate",+ "rotate3d","translate","shear","resize",@@ -35,6 +36,18 @@ def _compute_tensor_center(tensor: torch.Tensor) -> torch.Tensor:return center+def _compute_tensor_center3d(tensor: torch.Tensor) -> torch.Tensor:+ """Computes the center of tensor plane."""+ depth, height, width = tensor.shape[-3:]+ center_x: float = float(depth - 1) / 2+ center_y: float = float(height - 1) / 2+ center_z: float = float(width - 1) / 2+ center: torch.Tensor = torch.tensor(+ [center_x, center_y, center_z],+ device=tensor.device, dtype=tensor.dtype)+ return center++def _compute_rotation_matrix(angle: torch.Tensor,center: torch.Tensor) -> torch.Tensor:"""Computes a pure affine rotation matrix."""@@ -43,6 +56,14 @@ def _compute_rotation_matrix(angle: torch.Tensor,return matrix+def _compute_rotation_matrix3d(yaw: torch.Tensor, pitch: torch.Tensor, roll: torch.Tensor,+ center: torch.Tensor) -> torch.Tensor:+ """Computes a pure affine rotation matrix."""+ scale: torch.Tensor = torch.ones_like(yaw)+ matrix: torch.Tensor = get_rotation_matrix3d(center, yaw, pitch, roll, scale)+ return matrix++def _compute_translation_matrix(translation: torch.Tensor) -> torch.Tensor:"""Computes affine matrix for translation."""matrix: torch.Tensor = torch.eye(@@ -113,6 +134,43 @@ def affine(tensor: torch.Tensor, matrix: torch.Tensor, mode: str = 'bilinear',return warped+def affine3d(tensor: torch.Tensor, matrix: torch.Tensor, mode: str = 'bilinear',+ align_corners: bool = False) -> torch.Tensor:+ r"""Apply an affine transformation to the 3d volume.++ Args:+ tensor (torch.Tensor): The image tensor to be warped.+ matrix (torch.Tensor): The 3x4 affine transformation matrix.+ mode (str): 'bilinear' | 'nearest'+ align_corners(bool): interpolation flag. Default: False. See+ https://pytorch.org/docs/stable/nn.functional.html#torch.nn.functional.interpolate for detail++ Returns:+ torch.Tensor: The warped image.+ """+ # warping needs data in the shape of BCDHW+ is_unbatched: bool = tensor.ndimension() == 4+ if is_unbatched:+ tensor = torch.unsqueeze(tensor, dim=0)++ # we enforce broadcasting since by default grid_sample it does not+ # give support for that+ matrix = matrix.expand(tensor.shape[0], -1, -1)++ # warp the input tensor+ depth: int = tensor.shape[-3]+ height: int = tensor.shape[-2]+ width: int = tensor.shape[-1]+ warped: torch.Tensor = warp_affine3d(tensor, matrix, (depth, height, width), mode,+ align_corners=align_corners)++ # return in the original shape+ if is_unbatched:+ warped = torch.squeeze(warped, dim=0)++ return warped++# based on:# https://github.com/anibali/tvl/blob/master/src/tvl/transforms.py#L185@@ -129,7 +187,7 @@ def rotate(tensor: torch.Tensor, angle: torch.Tensor,if not torch.is_tensor(angle):raise TypeError("Input angle type is not a torch.Tensor. Got {}".format(type(angle)))- if center is not None and not torch.is_tensor(angle):+ 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,):@@ -150,6 +208,42 @@ def rotate(tensor: torch.Tensor, angle: torch.Tensor,return affine(tensor, rotation_matrix[..., :2, :3], mode, align_corners)+def rotate3d(tensor: torch.Tensor, yaw: torch.Tensor, pitch: torch.Tensor, roll: torch.Tensor,+ center: Union[None, torch.Tensor] = None, mode: str = 'bilinear',+ align_corners: bool = False) -> torch.Tensor:+ r"""Rotate the image anti-clockwise about the centre.++ See :class:`~kornia.Rotate` for details.+ """+ if not torch.is_tensor(tensor):+ raise TypeError("Input tensor type is not a torch.Tensor. Got {}"+ .format(type(tensor)))+ if not torch.is_tensor(yaw):+ raise TypeError("Input angle type is not a torch.Tensor. Got {}"+ .format(type(yaw)))+ 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. "+ "Got: {}".format(tensor.shape))++ # compute the rotation center+ if center is None:+ center = _compute_tensor_center(tensor)++ # compute the rotation matrix+ # TODO: add broadcasting to get_rotation_matrix2d for center+ yaw = yaw.expand(tensor.shape[0])+ pitch = yaw.expand(tensor.shape[0])+ roll = yaw.expand(tensor.shape[0])+ center = center.expand(tensor.shape[0], -1)+ rotation_matrix: torch.Tensor = _compute_rotation_matrix3d(yaw, pitch, roll, center)++ # warp using the affine transform+ return affine3d(tensor, rotation_matrix[..., :3, :4], mode, align_corners)++def translate(tensor: torch.Tensor, translation: torch.Tensor,align_corners: bool = False) -> torch.Tensor:r"""Translate the tensor in pixel units.diff --git a/kornia/geometry/transform/imgwarp.py b/kornia/geometry/transform/imgwarp.pyindex c27b5e8e1..bcbc6f3ff 100644--- a/kornia/geometry/transform/imgwarp.py+++ b/kornia/geometry/transform/imgwarp.py@@ -5,12 +5,12 @@ import torch.nn.functional as Ffrom kornia.geometry.conversions import deg2radfrom kornia.geometry.warp import (- normalize_homography, homography_warp+ normalize_homography, homography_warp, normalize_homography3d)# TODO: move to utils or conversionsfrom kornia.geometry.conversions import (- deg2rad, normalize_pixel_coordinates, convert_affinematrix_to_homography+ deg2rad, normalize_pixel_coordinates, convert_affinematrix_to_homography, convert_affinematrix_to_homography3d)from kornia.testing import check_is_tensor@@ -149,6 +149,68 @@ def warp_affine(src: torch.Tensor, M: torch.Tensor,padding_mode=padding_mode)+def warp_affine3d(src: torch.Tensor, M: torch.Tensor,+ dsize: Tuple[int, int, int], flags: str = 'bilinear',+ padding_mode: str = 'zeros',+ align_corners: bool = False) -> torch.Tensor:+ r"""Applies an affine transformation to a tensor.++ The function warp_affine transforms the source tensor using+ the specified matrix:++ .. math::+ \text{dst}(x, y) = \text{src} \left( M_{11} x + M_{12} y + M_{13} ,+ M_{21} x + M_{22} y + M_{23} \right )++ Args:+ src (torch.Tensor): input tensor of shape :math:`(B, C, D, H, W)`.+ M (torch.Tensor): affine transformation of shape :math:`(B, 3, 4)`.+ dsize (Tuple[int, int, int]): size of the output image (depth, height, width).+ mode (str): interpolation mode to calculate output values+ 'bilinear' | 'nearest'. Default: 'bilinear'.+ padding_mode (str): padding mode for outside grid values+ 'zeros' | 'border' | 'reflection'. Default: 'zeros'.+ align_corners (bool): mode for grid_generation. Default: False. See+ https://pytorch.org/docs/stable/nn.functional.html#torch.nn.functional.interpolate for details++ Returns:+ torch.Tensor: the warped tensor.++ Shape:+ - Output: :math:`(B, C, D, H, W)`+ """+ if not torch.is_tensor(src):+ raise TypeError("Input src type is not a torch.Tensor. Got {}"+ .format(type(src)))++ if not torch.is_tensor(M):+ raise TypeError("Input M type is not a torch.Tensor. Got {}"+ .format(type(M)))++ if not len(src.shape) == 5:+ raise ValueError("Input src must be a BxCxDxHxW tensor. Got {}"+ .format(src.shape))++ if not (len(M.shape) == 3 or M.shape[-2:] == (3, 4)):+ raise ValueError("Input M must be a Bx3x4 tensor. Got {}"+ .format(M.shape))+ B, C, D, H, W = src.size()+ dsize_src = (D, H, W)+ out_size = dsize+ # we generate a 3x3 transformation matrix from 2x3 affine+ M_3x3: torch.Tensor = convert_affinematrix_to_homography3d(M)+ dst_norm_trans_src_norm: torch.Tensor = normalize_homography3d(+ M_3x3, dsize_src, out_size)+ src_norm_trans_dst_norm = torch.inverse(dst_norm_trans_src_norm)+ grid = F.affine_grid(src_norm_trans_dst_norm[:, :3, :], # type: ignore+ [B, C, out_size[0], out_size[1], out_size[2]],+ align_corners=align_corners)+ return F.grid_sample(src, grid, # type: ignore+ align_corners=align_corners,+ mode=flags,+ padding_mode=padding_mode)++def get_perspective_transform(src, dst):r"""Calculates a perspective transform from four pairs of the correspondingpoints.@@ -276,6 +338,45 @@ def angle_to_rotation_matrix(angle: torch.Tensor) -> torch.Tensor:return torch.stack([cos_a, sin_a, -sin_a, cos_a], dim=-1).view(*angle.shape, 2, 2)+def angle_to_rotation_matrix3d(yaw: torch.Tensor, pitch: torch.Tensor, roll: torch.Tensor) -> torch.Tensor:+ r"""Create a rotation matrix out of angles in degrees.+ Args:+ yaw: (torch.Tensor): tensor of angles in degrees, top to bottom axis.+ pitch: (torch.Tensor): tensor of angles in degrees, left to right axis.+ roll: (torch.Tensor): tensor of angles in degrees, tail to nose axis.++ Returns:+ torch.Tensor: tensor of *x3x3 rotation matrices.++ Shape:+ - Input: :math:`(*)`, :math:`(*)`, :math:`(*)`+ - Output: :math:`(*, 3, 3)`++ Example:+ >>> input = torch.rand(1, 3) # Nx3+ >>> output = kornia.angle_to_rotation_matrix(input) # Nx3x2x2+ """+ assert yaw.shape == pitch.shape == roll.shape, \+ f"yaw, pitch, roll must be the size shape. Got {yaw.shape}, {pitch.shape} and {roll.shape}."+ yaw_rad = deg2rad(yaw)+ cos_a: torch.Tensor = torch.cos(yaw_rad)+ sin_a: torch.Tensor = torch.sin(yaw_rad)++ pitch_rad = deg2rad(pitch)+ cos_b: torch.Tensor = torch.cos(pitch_rad)+ sin_b: torch.Tensor = torch.sin(pitch_rad)++ roll_rad = deg2rad(roll)+ cos_c: torch.Tensor = torch.cos(roll_rad)+ sin_c: torch.Tensor = torch.sin(roll_rad)++ return torch.stack([+ cos_a * cos_b, cos_a * sin_b * sin_c - sin_a * cos_c, cos_a * sin_b * cos_c + sin_a * sin_c,+ sin_a * cos_b, sin_a * sin_b * sin_c + cos_a * cos_c, sin_a * sin_b * cos_c - cos_a * sin_c,+ - sin_b , cos_b * sin_c , cos_b * cos_c+ ], dim=-1).view(*yaw.shape, 3, 3)++def get_rotation_matrix2d(center: torch.Tensor,angle: torch.Tensor,@@ -364,6 +465,100 @@ def get_rotation_matrix2d(return M+def get_rotation_matrix3d(+ center: torch.Tensor,+ yaw: torch.Tensor,+ pitch: torch.Tensor,+ roll: torch.Tensor,+ scale: torch.Tensor) -> torch.Tensor:+ r"""Calculates an affine matrix of 3D rotation.++ The function calculates the following matrix:++ .. math::+ \begin{bmatrix}+ cos(\text{yaw})cos(\text{pitch})+ & cos(\text{yaw})sin(\text{pitch})sin(\text{roll}) - sin(\text{yaw})cos(\text{roll})+ & cos(\text{yaw})sin(\text{pitch})cos(\text{roll}) + sin(\text{yaw})cos(\text{roll}) & 0 \\+ sin(\text{yaw})cos(\text{pitch})+ & sin(\text{yaw})sin(\text{pitch})sin(\text{roll}) + cos(\text{yaw})cos(\text{roll})+ & sin(\text{yaw})sin(\text{pitch})cos(\text{roll}) - cos(\text{yaw})sin(\text{roll}) & 0 \\+ - sin(\text{yaw})+ & cos(\text{pitch})sin(\text{roll})+ & cos(\text{pitch})cos(\text{roll}) & 0+ \end{bmatrix}++ The transformation maps the rotation center to itself+ If this is not the target, adjust the shift.++ Args:+ center (Tensor): center of the rotation in the source image.+ yaw (Tensor): rotation angle in degrees. Positive values mean+ counter-clockwise rotation (the coordinate origin is assumed to+ be the top-left corner).+ pitch (Tensor): rotation angle in degrees. Positive values mean+ counter-clockwise rotation (the coordinate origin is assumed to+ be the top-left corner).+ roll (Tensor): rotation angle in degrees. Positive values mean+ counter-clockwise rotation (the coordinate origin is assumed to+ be the top-left corner).+ scale (Tensor): isotropic scale factor.++ Returns:+ Tensor: the affine matrix of 2D rotation.++ Shape:+ - Input: :math:`(B, 3)`, :math:`(B)` and :math:`(B)`+ - Output: :math:`(B, 3, 4)`++ Example:+ >>> center = torch.zeros(1, 3)+ >>> scale = torch.ones(1)+ >>> angle = 45. * torch.ones(1)+ >>> M = kornia.get_rotation_matrix3d(center, angle, scale)+ tensor([[[ 0.7071, 0.7071, 0.0000],+ [-0.7071, 0.7071, 0.0000]]])+ """+ # TODO: translation to rotation center+ # TODO: axis-wise scaling?+ if not torch.is_tensor(center):+ raise TypeError("Input center type is not a torch.Tensor. Got {}"+ .format(type(center)))+ if not torch.is_tensor(yaw) or not torch.is_tensor(pitch) or not torch.is_tensor(roll):+ raise TypeError("Input yaw, pitch, roll type is not a torch.Tensor. Got yaw {}, pitch {}, roll {}"+ .format(type(yaw), type(pitch), type(roll)))+ if not torch.is_tensor(scale):+ raise TypeError("Input scale type is not a torch.Tensor. Got {}"+ .format(type(scale)))+ if not (len(center.shape) == 2 and center.shape[1] == 3):+ raise ValueError("Input center must be a Bx3 tensor. Got {}"+ .format(center.shape))+ if not len(yaw.shape) == 1 or not len(pitch.shape) == 1 or not len(roll.shape) == 1:+ raise ValueError("Input yaw, pitch, roll must be a B tensor. Got yaw {}, pitch {}, roll {}"+ .format(yaw.shape, pitch.shape, roll.shape))+ if not len(scale.shape) == 1:+ raise ValueError("Input scale must be a B tensor. Got {}"+ .format(scale.shape))+ if not (center.shape[0] == yaw.shape[0] == pitch.shape[0] == roll.shape[0] == scale.shape[0]):+ raise ValueError("Inputs must have same batch size dimension. Got center {}, yaw {}, pitch {}, roll {}"+ "and scale {}".format(center.shape, yaw.shape, pitch.shape, roll.shape, scale.shape))+ # convert angle and apply scale+ scaled_rotation: torch.Tensor = angle_to_rotation_matrix3d(yaw, pitch, roll) * scale.view(-1, 1, 1)++ # unpack the center to x, y, z coordinates+ x: torch.Tensor = center[..., 0]+ y: torch.Tensor = center[..., 1]+ z: torch.Tensor = center[..., 2]++ # create output tensor+ batch_size: int = center.shape[0]+ one = torch.tensor(1.).to(center.device)+ M: torch.Tensor = torch.zeros(+ batch_size, 3, 4, device=center.device, dtype=center.dtype)+ M[..., 0:3, 0:3] = scaled_rotation+ return M++def remap(tensor: torch.Tensor, map_x: torch.Tensor,map_y: torch.Tensor,align_corners: bool = False) -> torch.Tensor:diff --git a/kornia/geometry/warp/homography_warper.py b/kornia/geometry/warp/homography_warper.pyindex a1a0729bc..9e5f6cf07 100644--- a/kornia/geometry/warp/homography_warper.py+++ b/kornia/geometry/warp/homography_warper.py@@ -14,6 +14,7 @@ __all__ = ["homography_warp","warp_grid","normalize_homography",+ "normalize_homography3d","normal_transform_pixel",]@@ -225,6 +226,33 @@ def normal_transform_pixel(height: int, width: int) -> torch.Tensor:return tr_mat+def normal_transform_pixel3d(depth:int, height: int, width: int) -> torch.Tensor:+ r"""Compute the normalization matrix from image size in pixels to [-1, 1].++ Args:+ depth (int): image depth.+ height (int): image height.+ width (int): image width.++ Returns:+ Tensor: normalized transform.++ Shape:+ Output: :math:`(1, 4, 4)`+ """+ tr_mat = torch.tensor([[1.0, 0.0, 0.0, -1.0],+ [0.0, 1.0, 0.0, -1.0],+ [0.0, 0.0, 1.0, -1.0],+ [0.0, 0.0, 0.0, 1.0]]) # 4x4++ tr_mat[0, 0] = tr_mat[0, 0] * 2.0 / (depth - 1.0)+ tr_mat[1, 1] = tr_mat[1, 1] * 2.0 / (height - 1.0)+ tr_mat[2, 2] = tr_mat[1, 1] * 2.0 / (width - 1.0)++ tr_mat = tr_mat.unsqueeze(0) # 1x4x4+ return tr_mat++def normalize_homography(dst_pix_trans_src_pix: torch.Tensor,dsize_src: Tuple[int, int], dsize_dst: Tuple[int, int]) -> torch.Tensor:r"""Normalize a given homography in pixels to [-1, 1].@@ -260,3 +288,41 @@ def normalize_homography(dst_pix_trans_src_pix: torch.Tensor,dst_norm_trans_dst_pix @ (dst_pix_trans_src_pix @ src_pix_trans_src_norm))return dst_norm_trans_src_norm+++def normalize_homography3d(dst_pix_trans_src_pix: torch.Tensor,+ dsize_src: Tuple[int, int, int], dsize_dst: Tuple[int, int, int]) -> torch.Tensor:+ r"""Normalize a given homography in pixels to [-1, 1].++ Args:+ dst_pix_trans_src_pix (torch.Tensor): homography/ies from source to destiantion to be+ normalized. :math:`(B, 4, 4)`+ dsize_src (tuple): size of the source image (depth, height, width).+ dsize_src (tuple): size of the destination image (depth, height, width).++ Returns:+ Tensor: the normalized homography.++ Shape:+ Output: :math:`(B, 4, 4)`+ """+ check_is_tensor(dst_pix_trans_src_pix)++ if not (len(dst_pix_trans_src_pix.shape) == 3 or dst_pix_trans_src_pix.shape[-2:] == (4, 4)):+ raise ValueError("Input dst_pix_trans_src_pix must be a Bx3x3 tensor. Got {}"+ .format(dst_pix_trans_src_pix.shape))++ # source and destination sizes+ src_d, src_h, src_w = dsize_src+ dst_d, dst_h, dst_w = dsize_dst+ # compute the transformation pixel/norm for src/dst+ src_norm_trans_src_pix: torch.Tensor = normal_transform_pixel3d(+ src_d, src_h, src_w).to(dst_pix_trans_src_pix)+ src_pix_trans_src_norm = torch.inverse(src_norm_trans_src_pix)+ dst_norm_trans_dst_pix: torch.Tensor = normal_transform_pixel3d(+ dst_d, dst_h, dst_w).to(dst_pix_trans_src_pix)+ # compute chain transformations+ dst_norm_trans_src_norm: torch.Tensor = (+ dst_norm_trans_dst_pix @ (dst_pix_trans_src_pix @ src_pix_trans_src_norm)+ )+ return dst_norm_trans_src_norm