π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
Code cleaned up
Jian Sef3246bf9969
diff --git a/kornia/geometry/conversions.py b/kornia/geometry/conversions.pyindex 640b8ce4e..5e0f417e8 100644--- a/kornia/geometry/conversions.py+++ b/kornia/geometry/conversions.py@@ -11,6 +11,7 @@ __all__ = ["convert_points_from_homogeneous","convert_points_to_homogeneous","convert_affinematrix_to_homography",+ "convert_affinematrix_to_homography3d","angle_axis_to_rotation_matrix","angle_axis_to_quaternion","rotation_matrix_to_angle_axis",diff --git a/kornia/geometry/transform/affwarp.py b/kornia/geometry/transform/affwarp.pyindex b53c4a797..94bbdedb3 100644--- a/kornia/geometry/transform/affwarp.py+++ b/kornia/geometry/transform/affwarp.py@@ -4,7 +4,10 @@ import torchimport torch.nn as nnfrom kornia.geometry.transform.imgwarp import (- warp_affine, warp_affine3d, get_rotation_matrix2d, get_rotation_matrix3d+ warp_affine, get_rotation_matrix2d+)+from kornia.geometry.transform.projwarp import (+ warp_projective, get_projective_transform)__all__ = [@@ -59,8 +62,21 @@ def _compute_rotation_matrix(angle: torch.Tensor,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)+ if len(yaw.shape) == len(pitch.shape) == len(roll.shape) == 0:+ yaw = yaw.unsqueeze(dim=0)+ pitch = pitch.unsqueeze(dim=0)+ roll = roll.unsqueeze(dim=0)++ if len(yaw.shape) == len(pitch.shape) == len(roll.shape) == 1:+ yaw = yaw.unsqueeze(dim=1)+ pitch = pitch.unsqueeze(dim=1)+ roll = roll.unsqueeze(dim=1)++ assert len(yaw.shape) == len(pitch.shape) == len(roll.shape) == 2, \+ f"Expected yaw, pitch, roll to be (B, 1). Got {yaw.shape}, {pitch.shape}, {roll.shape}."++ angles: torch.Tensor = torch.cat([yaw, pitch, roll], dim=1)+ matrix: torch.Tensor = get_projective_transform(center, angles)return matrix@@ -161,8 +177,8 @@ def affine3d(tensor: torch.Tensor, matrix: torch.Tensor, mode: str = 'bilinear',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)+ warped: torch.Tensor = warp_projective(tensor, matrix, (depth, height, width), mode,+ align_corners=align_corners)# return in the original shapeif is_unbatched:diff --git a/kornia/geometry/transform/imgwarp.py b/kornia/geometry/transform/imgwarp.pyindex bcbc6f3ff..ecdbff6bb 100644--- a/kornia/geometry/transform/imgwarp.py+++ b/kornia/geometry/transform/imgwarp.py@@ -3,15 +3,15 @@ from typing import Tuple, Optionalimport torchimport torch.nn.functional as F-from kornia.geometry.conversions import deg2radfrom kornia.geometry.warp import (normalize_homography, homography_warp, normalize_homography3d)--# TODO: move to utils or conversionsfrom kornia.geometry.conversions import (deg2rad, normalize_pixel_coordinates, convert_affinematrix_to_homography, convert_affinematrix_to_homography3d)+from kornia.geometry.transform.projwarp import (+ warp_projective+)from kornia.testing import check_is_tensor__all__ = [@@ -149,68 +149,6 @@ 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.@@ -338,45 +276,6 @@ 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,@@ -465,100 +364,6 @@ 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/transform/projwarp.py b/kornia/geometry/transform/projwarp.pyindex edd4647a9..5c69225e5 100644--- a/kornia/geometry/transform/projwarp.py+++ b/kornia/geometry/transform/projwarp.py@@ -3,12 +3,12 @@ from typing import Tuple, Listimport torchimport kornia as K+from kornia.geometry.conversions import convert_affinematrix_to_homography3d+from kornia.geometry.warp import normalize_homography3d__all__ = ["warp_projective","get_projective_transform",- "normal_transform3d_pixel",- "matrix_to_homogeneous","projection_from_Rt",]@@ -43,10 +43,10 @@ def warp_projective(src: torch.Tensor,size_src: Tuple[int, int, int] = (D, H, W)size_out: Tuple[int, int, int] = dsize- M_4x4 = matrix_to_homogeneous(M) # Bx4x4+ 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_projection_matrix(+ dst_norm_trans_src_norm: torch.Tensor = normalize_homography3d(M_4x4, size_src, size_out) # Bx4x4src_norm_trans_dst_norm = torch.inverse(dst_norm_trans_src_norm)@@ -78,73 +78,6 @@ def projection_from_Rt(rmat: torch.Tensor, tvec: torch.Tensor) -> torch.Tensor:return torch.cat([rmat, tvec], dim=-1) # Bx3x4-def matrix_to_homogeneous(M: torch.Tensor) -> torch.Tensor:- r"""Converts a generic transformation matrix to make it usable for homogeneous coordinates.-- Appends to the last matrix row an extra row filled with zeros with a one to the end.-- Args:- M (torch.Tensor): the transformation matrix with at least two dimensions :math:`(*, M, N)`.-- Returns:- torch.Tensor: the transformation matrix with shape :math:`(*, M, N + 1)`.-- """- M_homo = torch.nn.functional.pad(M, [0, 0, 0, 1], "constant", value=0.)- M_homo[..., -1, -1] += 1.0-- return M_homo---def _normalize_projection_matrix(- dst_pix_trans_src_pix: torch.Tensor,- dsize_src: Tuple[int, int, int],- dsize_dst: Tuple[int, int, int]) -> torch.Tensor:- r"""Computes the transformation matrix to normalize points before applying sampling."""- # source and destination sizes- src_d, src_h, src_w = dsize_src- src_d, dst_h, dst_w = dsize_dst-- # compute the transformation pixel/norm for src/dst- src_norm_trans_src_pix: torch.Tensor = normal_transform3d_pixel(- 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_transform3d_pixel(- src_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---def normal_transform3d_pixel(depth: int, height: int, width: int) -> torch.Tensor:- r"""Compute the normalization matrix from image size in pixels to [-1, 1].-- Args:- depth (int): tensor depht.- height (int): tensor height.- width (int): tensor width.-- Returns:- torch.Tensor: normalized transform with shape :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 / (width - 1.0)- tr_mat[1, 1] = tr_mat[1, 1] * 2.0 / (height - 1.0)- tr_mat[2, 2] = tr_mat[2, 2] * 2.0 / (depth - 1.0)-- return tr_mat[None] # 1x4x4--def get_projective_transform(center: torch.Tensor, angles: torch.Tensor) -> torch.Tensor:r"""Calculates the projection matrix for a 3D rotation.@@ -180,7 +113,7 @@ def get_projective_transform(center: torch.Tensor, angles: torch.Tensor) -> torcproj_mat = projection_from_Rt(rmat, torch.zeros_like(center)[..., None]) # Bx3x4# chain 4x4 transforms- proj_mat = matrix_to_homogeneous(proj_mat) # Bx4x4+ proj_mat = convert_affinematrix_to_homography3d(proj_mat) # Bx4x4proj_mat = (from_origin_mat @ proj_mat @ to_origin_mat)return proj_mat[..., :3, :] # Bx3x4