π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix linter test
edgarriba5e16efee1f47
diff --git a/torchgeometry/conversions.py b/torchgeometry/conversions.pyindex cd79ba538..dbeed3949 100644--- a/torchgeometry/conversions.py+++ b/torchgeometry/conversions.py@@ -119,7 +119,7 @@ def convert_points_to_homogeneous(points):def transform_points(dst_pose_src, points_src):"""Applies batch of transformations to batch of sets of points.- Args:+ Args:dst_pose_src (Tensor): tensor for transformations of size (B, D+1, D+1).points_src (Tensor): tensor of points of size (B, N, D).@@ -152,11 +152,12 @@ def angle_axis_to_rotation_matrix_numpy(angle_axis):Convert 3d vector of axis-angle rotation to 4x4 rotation matrixArgs:- angle_axis (numpy.ndarray): array of 3d vector of axis-angle rotations of size (1, 3).-+ angle_axis (numpy.ndarray): array of 3d vector of axis-angle rotations+ of size (1, 3).+Returns:numpy.ndarray: array of 4x4 rotation matrices of size (4, 4).-+"""# stolen from ceres/rotation.hk_one = 1.0@@ -201,8 +202,9 @@ def angle_axis_to_rotation_matrix_torch(angle_axis, eps=1e-6):Convert 3d vector of axis-angle rotation to 4x4 rotation matrixArgs:- angle_axis (Tensor): tensor of 3d vector of axis-angle rotations of size (N, 3).-+ angle_axis (Tensor): tensor of 3d vector of axis-angle rotations+ of size (N, 3).+Returns:Tensor: tensor of 4x4 rotation matrices of size (N, 4, 4).@@ -280,7 +282,7 @@ def rtvec_to_pose(rtvec):"""Convert axis-angle rotation and translation vector to 4x4 pose matrix- Args:+ Args:rtvec (Tensor): Rodrigues vector transformations of size (N, 6).Returns:@@ -297,7 +299,8 @@ def rotation_matrix_to_quaternion(rotation_matrix):if isinstance(rotation_matrix, np.ndarray):return rotation_matrix_to_quaternion_numpy(rotation_matrix)elif isinstance(rotation_matrix, torch.Tensor):- if not (len(rotation_matrix.shape) == 3 and rotation_matrix.shape[1] == 4):+ if not (len(rotation_matrix.shape) == 3 and # noqa+ rotation_matrix.shape[1] == 4):raise ValueError("Input must be a three dimensional torch.Tensor.")return rotation_matrix_to_quaternion_torch(rotation_matrix)else:@@ -312,7 +315,7 @@ def quaternion_to_angle_axis(quaternion):elif isinstance(quaternion, torch.Tensor):if not (len(quaternion.shape) == 2 and quaternion.shape[1] == 4):raise ValueError("Input must be a two dimensional torch.Tensor.")- return quaternion_to_angle_axis_torch(quaternion)+ return quaternion_to_angle_axis_torch(quaternion)else:raise NotImplementedError('Not suported type {}'.format(@@ -330,7 +333,7 @@ def rotation_matrix_to_angle_axis(rotation_matrix):Tensor: Rodrigues vector transformation of size (1, 6).'''- #todo add check that matrix is a valid rotation matrix+ # todo add check that matrix is a valid rotation matrixquaternion = rotation_matrix_to_quaternion(rotation_matrix)return quaternion_to_angle_axis(quaternion)@@ -374,8 +377,8 @@ def rotation_matrix_to_quaternion_numpy(rotation_matrix):j = (i + 1) % 3k = (j + 1) % 3- t = np.sqrt(rotation_matrix[i, i] - rotation_matrix[j, j] -- rotation_matrix[k, k] + 1.0)+ t = np.sqrt(rotation_matrix[i, i] - rotation_matrix[j, j] - # noqa+ rotation_matrix[k, k] + 1.0)quaternion[i + 1] = 0.5 * tt = 0.5 / tquaternion[0] = (rotation_matrix[k, j] - rotation_matrix[j, k]) * t@@ -389,13 +392,13 @@ def quaternion_to_angle_axis_numpy(quaternion):'''Convert quaternion vector to angle axis of rotationAdapted from ceres C++ library: ceres-solver/include/ceres/rotation.h-+Args:quaternion (Tensor): quaternion rotation vector of length 4Returns:Tensor: axis-angle rotation of size (1, 3).-+'''assert quaternion.shape[-1] == 4, 'Input must be a vector of length 4'normalizer = 1 / np.linalg.norm(quaternion)@@ -410,7 +413,7 @@ def quaternion_to_angle_axis_numpy(quaternion):sin_theta = np.sqrt(sin_squared)cos_theta = quaternion[0] * normalizertheta = np.arctan2(-sin_theta, -cos_theta) if cos_theta < 0.0\- else np.arctan2(sin_theta, cos_theta)+ else np.arctan2(sin_theta, cos_theta)two_theta = 2 * thetak = two_theta / sin_thetaangle_axis[0] = q1 * k@@ -434,33 +437,32 @@ def rotation_matrix_to_quaternion_torch(rotation_matrix, eps=1e-6):mask_d2 = rmat_t[:, 2, 2] < eps- mask_d0_d1 = rmat_t[:, 0, 0] > rmat_t[:,1, 1]- mask_d0_nd1 = rmat_t[:, 0, 0] < -rmat_t[:,1, 1]-+ mask_d0_d1 = rmat_t[:, 0, 0] > rmat_t[:, 1, 1]+ mask_d0_nd1 = rmat_t[:, 0, 0] < -rmat_t[:, 1, 1]- t0 = 1 + rmat_t[:,0, 0] - rmat_t[:,1, 1] - rmat_t[:,2, 2]- q0 = torch.stack([rmat_t[:,1, 2] - rmat_t[:, 2, 1],- t0, rmat_t[:, 0, 1] + rmat_t[:, 1, 0],- rmat_t[:, 2, 0] + rmat_t[:,0, 2]], -1)- t0_rep = t0.repeat(4,1).t()+ t0 = 1 + rmat_t[:, 0, 0] - rmat_t[:, 1, 1] - rmat_t[:, 2, 2]+ q0 = torch.stack([rmat_t[:, 1, 2] - rmat_t[:, 2, 1],+ t0, rmat_t[:, 0, 1] + rmat_t[:, 1, 0],+ rmat_t[:, 2, 0] + rmat_t[:, 0, 2]], -1)+ t0_rep = t0.repeat(4, 1).t()t1 = 1 - rmat_t[:, 0, 0] + rmat_t[:, 1, 1] - rmat_t[:, 2, 2]- q1 = torch.stack([rmat_t[:, 2,0] - rmat_t[:,0, 2],- rmat_t[:, 0, 1] + rmat_t[:, 1, 0],- t1, rmat_t[:, 1, 2] + rmat_t[:, 2, 1]], -1)- t1_rep = t1.repeat(4,1).t()+ q1 = torch.stack([rmat_t[:, 2, 0] - rmat_t[:, 0, 2],+ rmat_t[:, 0, 1] + rmat_t[:, 1, 0],+ t1, rmat_t[:, 1, 2] + rmat_t[:, 2, 1]], -1)+ t1_rep = t1.repeat(4, 1).t()t2 = 1 - rmat_t[:, 0, 0] - rmat_t[:, 1, 1] + rmat_t[:, 2, 2]q2 = torch.stack([rmat_t[:, 0, 1] - rmat_t[:, 1, 0],- rmat_t[:, 2, 0] + rmat_t[:, 0, 2],- rmat_t[:, 1, 2] + rmat_t[:, 2, 1], t2], -1)- t2_rep = t2.repeat(4,1).t()+ rmat_t[:, 2, 0] + rmat_t[:, 0, 2],+ rmat_t[:, 1, 2] + rmat_t[:, 2, 1], t2], -1)+ t2_rep = t2.repeat(4, 1).t()t3 = 1 + rmat_t[:, 0, 0] + rmat_t[:, 1, 1] + rmat_t[:, 2, 2]- q3 = torch.stack([t3, rmat_t[:, 1, 2] - rmat_t[:, 2, 1],+ q3 = torch.stack([t3, rmat_t[:, 1, 2] - rmat_t[:, 2, 1],rmat_t[:, 2, 0] - rmat_t[:, 0, 2],rmat_t[:, 0, 1] - rmat_t[:, 1, 0]], -1)- t3_rep = t3.repeat(4,1).t()+ t3_rep = t3.repeat(4, 1).t()mask_c0 = mask_d2 * mask_d0_d1mask_c1 = mask_d2 * (1 - mask_d0_d1)@@ -472,7 +474,8 @@ def rotation_matrix_to_quaternion_torch(rotation_matrix, eps=1e-6):mask_c3 = mask_c3.view(-1, 1).type_as(q3)q = q0 * mask_c0 + q1 * mask_c1 + q2 * mask_c2 + q3 * mask_c3- q /= torch.sqrt(t0_rep * mask_c0 + t1_rep * mask_c1 + t2_rep * mask_c2 + t3_rep * mask_c3)+ q /= torch.sqrt(t0_rep * mask_c0 + t1_rep * mask_c1 + # noqa+ t2_rep * mask_c2 + t3_rep * mask_c3)q *= 0.5return q@@ -492,19 +495,21 @@ def quaternion_to_angle_axis_torch(quaternion, eps=1e-6):sin_squared = q1 * q1 + q2 * q2 + q3 * q3mask = (sin_squared > eps).to(sin_squared.device)- mask_pos = (mask == True).type_as(sin_squared)- mask_neg = (mask == False).type_as(sin_squared)+ mask_pos = (mask).type_as(sin_squared)+ mask_neg = (mask == False).type_as(sin_squared) # noqabatch_size = quaternion.size(0)- angle_axis = torch.zeros(batch_size, 3, dtype=quaternion.dtype).to(quaternion.device)+ angle_axis = torch.zeros(+ batch_size, 3, dtype=quaternion.dtype).to(+ quaternion.device)sin_theta = torch.sqrt(sin_squared)cos_theta = quaternion[:, 0] * normalizermask_theta = (cos_theta < eps).view(1, -1)- mask_theta_neg = (mask_theta == True).type_as(cos_theta)- mask_theta_pos = (mask_theta == False).type_as(cos_theta)+ mask_theta_neg = (mask_theta).type_as(cos_theta)+ mask_theta_pos = (mask_theta == False).type_as(cos_theta) # noqatheta = torch.atan2(-sin_theta, -cos_theta) * mask_theta_neg \- + torch.atan2(sin_theta, cos_theta) * mask_theta_pos+ + torch.atan2(sin_theta, cos_theta) * mask_theta_postwo_theta = 2 * thetak_pos = two_theta / sin_thetadiff --git a/torchgeometry/depth_warper.py b/torchgeometry/depth_warper.pyindex c56753207..54624d925 100644--- a/torchgeometry/depth_warper.py+++ b/torchgeometry/depth_warper.py@@ -25,6 +25,7 @@ class DepthWarper(nn.Module):height (int): The height of the image to warp. Optional."""+def __init__(self, pinholes, width=None, height=None):super(DepthWarper, self).__init__()# TODO: add type and value checkings@@ -126,7 +127,8 @@ accurate sampling of the depth cost volume, per camera.return flows.permute(0, 2, 3, 1) # NxHxWx2def forward(self, inv_depth_ref, patch_i):- """Warps an image or tensor from ith frame to reference given the inverse depth in the reference frame.+ """Warps an image or tensor from ith frame to reference given the+ inverse depth in the reference frame.Args:inv_depth_ref (Tensor): The inverse depth in the reference frame.@@ -148,27 +150,30 @@ accurate sampling of the depth cost volume, per camera.>>> # create the depth warper and compute the homographies>>> warper = tgm.DepthWarper(pinholes_i)>>> warper.compute_homographies(pinhole_ref)- >>> # warper the ith frame to reference by inverse depth in the reference+ >>> # warp the ith frame to reference by inverse depth>>> inv_depth_ref = torch.ones(1, 1, 32, 32) # Nx1xHxW>>> img_ref = warper(inv_depth_ref, img_i) # NxCxHxW"""# TODO: add type and value checkings- return torch.nn.functional.grid_sample(patch_i, self.warp(inv_depth_ref))+ return torch.nn.functional.grid_sample(+ patch_i, self.warp(inv_depth_ref))# functional api-def depth_warp(pinholes_i, pinhole_ref, inv_depth_ref, patch_i, \- width=None, height=None):+def depth_warp(pinholes_i, pinhole_ref, inv_depth_ref, patch_i,+ width=None, height=None):""".. note::Functional API for :class:`torgeometry.DepthWarper`-+Warps a patch by inverse depth.Args:- pinholes_i (Tensor): The pinhole models for ith frame with shape `[Nx12]`.- pinholes_ref (Tensor): The pinhole models for the reference frame with shape `[1x12]`.+ pinholes_i (Tensor): The pinhole models for ith frame with+ shape `[Nx12]`.+ pinholes_ref (Tensor): The pinhole models for the reference frame+ with shape `[1x12]`.inv_depth_ref (Tensor): The inverse depth in the reference frame.patch_i (Tensor): The patch data in the ith frame.@@ -183,7 +188,8 @@ def depth_warp(pinholes_i, pinhole_ref, inv_depth_ref, patch_i, \>>> pinhole_ref = torch.Tensor([1, 12]), # Nx12>>> # warp the ith frame to reference by inverse depth in the reference>>> inv_depth_ref = torch.ones(1, 1, 32, 32) # Nx1xHxW- >>> img_ref = tgm.depth_warp(pinholes_i, pinhole_ref, inv_depth_ref, img_i) # NxCxHxW+ >>> img_ref = tgm.depth_warp( \+ >>> pinholes_i, pinhole_ref, inv_depth_ref, img_i) # NxCxHxW"""warper = DepthWarper(pinholes_i, width=width, height=height)warper.compute_homographies(pinhole_ref)diff --git a/torchgeometry/homography_warper.py b/torchgeometry/homography_warper.pyindex dab15398a..7f3dfeb66 100644--- a/torchgeometry/homography_warper.py+++ b/torchgeometry/homography_warper.py@@ -42,6 +42,7 @@ class HomographyWarper(nn.Module):points (Tensor): Tensor[3, N] of homogeneous points in normalized imagespace [-1, 1] to sample. Optional parameter."""+def __init__(self, height, width, points=None):super(HomographyWarper, self).__init__()if points is not None:@@ -107,9 +108,11 @@ class HomographyWarper(nn.Module):Args:patch (Tensor): The image or tensor to warp. Should be from source.- dst_homo_src (Tensor): The homography or stack of homographies from source to destination.- padding_mode (string): Either 'zeros' to replace out of bounds with zeros- or 'border' to choose the closest border data.+ dst_homo_src (Tensor): The homography or stack of homographies+ from source to destination.+ padding_mode (string): Either 'zeros' to replace out of bounds with+ zeros or 'border' to choose the closest+ border data.Return:Tensor: Patch sampled at locations from source to destination.@@ -133,6 +136,7 @@ class HomographyWarper(nn.Module):# functional api+def homography_warp(patch, dst_H_src, dsize, points=None,padding_mode='zeros'):"""@@ -142,12 +146,14 @@ def homography_warp(patch, dst_H_src, dsize, points=None,Args:patch (Tensor): The image or tensor to warp. Should be from source.- dst_homo_src (Tensor): The homography or stack of homographies from source to destination.+ dst_homo_src (Tensor): The homography or stack of homographies from+ source to destination.dsize (tuple): The height and width of the image to warp.points (Tensor): Tensor[3, N] of homogeneous points in normalized imagespace [-1, 1] to sample. Optional parameter.- padding_mode (string): Either 'zeros' to replace out of bounds with zeros- or 'border' to choose the closest border data.+ padding_mode (string): Either 'zeros' to replace out of bounds with+ zeros or 'border' to choose the closest border+ data.Return:Tensor: Patch sampled at locations from source to destination.diff --git a/torchgeometry/pinhole.py b/torchgeometry/pinhole.pyindex 08279f0da..6f948a7a5 100644--- a/torchgeometry/pinhole.py+++ b/torchgeometry/pinhole.py@@ -54,7 +54,8 @@ def pinhole_matrix(pinholes):"""Converts vector pinhole representation to 4x4 TensorArgs:- pinholes (Tensor): tensor of form [fx fy cx cy h w rx ry rz tx ty tz] of size (N, 12).+ pinholes (Tensor): tensor of form [fx fy cx cy h w rx ry rz tx ty tz]+ of size (N, 12).Returns:Tensor: tensor of pinhole matrices of size (N, 4, 4).@@ -78,7 +79,8 @@ def inverse_pinhole_matrix(pinhole, eps=1e-6):"""Invert a set of pinholesArgs:- pinholes (Tensor): tensor of form [fx fy cx cy h w rx ry rz tx ty tz] of size (N, 12).+ pinholes (Tensor): tensor of form [fx fy cx cy h w rx ry rz tx ty tz]+ of size (N, 12).Returns:Tensor: tensor of inverted pinhole matrices of size (N, 4, 4).@@ -102,11 +104,13 @@ def scale_pinhole(pinholes, scale):"""Scales the pinhole matrix for each pinhole model.Args:- pinholes (Tensor): tensor of form [fx fy cx cy h w rx ry rz tx ty tz] of size (N, 12).+ pinholes (Tensor): tensor of form [fx fy cx cy h w rx ry rz tx ty tz]+ of size (N, 12).scale (Tensor): tensor of scales of form [N, 1]Returns:- Tensor: tensor of scaled pinholes of form [fx fy cx cy h w rx ry rz tx ty tz] of size (N, 12).+ Tensor: tensor of scaled pinholes of form+ [fx fy cx cy h w rx ry rz tx ty tz] of size (N, 12)."""assert len(pinholes.shape) == 2 and pinholes.shape[1] == 12, pinholes.shape@@ -120,7 +124,8 @@ def get_optical_pose_base(pinholes):"""Get extrinsic transformation matrices for pinholesArgs:- pinholes (Tensor): tensor of form [fx fy cx cy h w rx ry rz tx ty tz] of size (N, 12).+ pinholes (Tensor): tensor of form [fx fy cx cy h w rx ry rz tx ty tz]+ of size (N, 12).Returns:Tensor: tensor of extrinsic transformation matrices of size (N, 4, 4).@@ -135,13 +140,16 @@ def homography_i_H_ref(pinhole_i, pinhole_ref):"""Homography from pinhole_ref to pinhole_i- Args:- pinhole_i (Tensor): tensor of form [fx fy cx cy h w rx ry rz tx ty tz] of size (N, 12).- pinhole_ref (Tensor): tensor of form [fx fy cx cy h w rx ry rz tx ty tz] of size (N, 12).+ Args:+ pinhole_i (Tensor): tensor of form [fx fy cx cy h w rx ry rz tx ty tz]+ of size (N, 12).+ pinhole_ref (Tensor): tensor of form [fx fy cx cy h w rx ry rz tx ty tz]+ of size (N, 12).Returns:- Tensor: tensors that convert depth points (u, v, d) from pinhole_ref to pinhole_i (N, 4, 4).-+ Tensor: tensors that convert depth points (u, v, d) from pinhole_ref to+ pinhole_i (N, 4, 4).+"""assert len(pinhole_i.shape) == 2 and pinhole_i.shape[1] == 12, pinhole.shapediff --git a/torchgeometry/utils.py b/torchgeometry/utils.pyindex 16d8632de..a82eaf843 100644--- a/torchgeometry/utils.py+++ b/torchgeometry/utils.py@@ -1,7 +1,6 @@import cv2import numpy as npimport torch-import numpy as npimport torchgeometry as tgmimport torch.nn as nn@@ -45,7 +44,7 @@ class Inverse(nn.Module):def image_to_tensor(image):"""Converts a numpy image to a torch.Tensor image.- Args:+ Args:image (numpy.ndarray): image of the form (H, W, C).Returns:@@ -64,7 +63,8 @@ def image_to_tensor(image):def tensor_to_image(tensor):- """Converts a torch.Tensor image to a numpy image. In case the tensor is in the GPU, it will be copied back to CPU.+ """Converts a torch.Tensor image to a numpy image. In case the tensor is in+ the GPU, it will be copied back to CPU.Args:tensor (Tensor): image of the form (C, H, W).@@ -109,6 +109,7 @@ def draw_rectangle(image, dst_homo_src):]]).to(dst_homo_src.device)# transform pointspts_dst = tgm.transform_points(tgm.inverse(dst_homo_src), pts_src)+def compute_factor(size):return 1.0 * size / 2