Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

refactor and add layers api

edgarribad1d9d3e7c770
diff --git a/test/test_depth_warper.py b/test/test_depth_warper.py
index 1a23c793e..d2def0480 100644
--- a/test/test_depth_warper.py
+++ b/test/test_depth_warper.py
@@ -19,11 +19,11 @@ class Tester(unittest.TestCase):
tx, ty, tz = 0., 0., 0.
offset = 1. # we will apply a 1unit offset to `i` camera
- pinhole_src = utils.create_pinhole(
+ pinhole_ref = utils.create_pinhole(
fx, fy, cx, cy, height, width, rx, ry, rx, tx, ty, tz)
- pinhole_src = pinhole_src.expand(batch_size, -1)
+ pinhole_ref = pinhole_ref.expand(batch_size, -1)
- pinhole_dst = utils.create_pinhole(
+ pinhole_i = utils.create_pinhole(
fx,
fy,
cx,
@@ -36,29 +36,35 @@ class Tester(unittest.TestCase):
tx + offset,
ty + offset,
tz)
- pinhole_dst = pinhole_dst.expand(batch_size, -1)
+ pinhole_i = pinhole_i.expand(batch_size, -1)
# create checkerboard
board = utils.create_checkerboard(height, width, 4)
- patch_src = torch.from_numpy(board).view(
+ patch_i = torch.from_numpy(board).view(
1, 1, height, width).expand(batch_size, 1, height, width)
# instantiate warper and compute relative homographies
- warper = tgm.DepthWarper(pinhole_src, height, width)
+ warper = tgm.DepthWarper(pinhole_i, height, width)
warper.compute_homographies(
- pinhole_dst, scale=torch.ones(
+ pinhole_ref, scale=torch.ones(
batch_size, 1))
# generate synthetic inverse depth
- inv_depth_src = torch.ones(batch_size, 1, height, width)
+ inv_depth_ref = torch.ones(batch_size, 1, height, width)
# warpd source patch by depth
- patch_dst = warper(inv_depth_src, patch_src)
+ patch_ref = warper(inv_depth_ref, patch_i)
# compute error
res = utils.check_equal_torch(
- patch_src[..., :-int(offset), :-int(offset)],
- patch_dst[..., int(offset):, int(offset):])
+ patch_ref[..., :-int(offset), :-int(offset)],
+ patch_i[..., int(offset):, int(offset):])
+ self.assertTrue(res)
+
+ # test functional
+ patch_ref_functional = tgm.depth_warp(pinhole_i, pinhole_ref,
+ inv_depth_ref, patch_i)
+ res = utils.check_equal_torch(patch_ref, patch_ref_functional)
self.assertTrue(res)
diff --git a/test/test_functional.py b/test/test_functional.py
index 7034dca36..7dc7ef5b8 100644
--- a/test/test_functional.py
+++ b/test/test_functional.py
@@ -18,6 +18,10 @@ class Tester(unittest.TestCase):
points_h = tgm.convert_points_to_homogeneous(points)
self.assertTrue((points_h[..., -1] == torch.ones(1, 2, 1)).all())
+ # functional
+ self.assertTrue(
+ torch.allclose(points_h, tgm.ConvertPointsToHomogeneous()(points)))
+
def test_convert_points_to_homogeneous_gradcheck(self):
# generate input data
batch_size = 2
@@ -41,6 +45,10 @@ class Tester(unittest.TestCase):
error = utils.compute_mse(points_h[..., :2], points)
self.assertAlmostEqual(error.item(), 0.0, places=4)
+ # functional
+ self.assertTrue(torch.allclose(
+ points, tgm.ConvertPointsFromHomogeneous()(points_h)))
+
def test_convert_points_from_homogeneous_gradcheck(self):
# generate input data
batch_size = 2
@@ -65,6 +73,10 @@ class Tester(unittest.TestCase):
error = utils.compute_mse(res, eye)
self.assertAlmostEqual(error.item(), 0.0, places=4)
+ # functional
+ self.assertTrue(
+ torch.allclose(homographies_inv, tgm.Inverse()(homographies)))
+
def test_inverse_gradcheck(self):
# generate input data
batch_size = 2
@@ -96,6 +108,10 @@ class Tester(unittest.TestCase):
error = utils.compute_mse(points_src, points_dst_to_src)
self.assertAlmostEqual(error.item(), 0.0, places=4)
+ # functional
+ self.assertTrue(torch.allclose(points_dst,
+ tgm.TransformPoints()(dst_homo_src, points_src)))
+
def test_transform_points_gradcheck(self):
# generate input data
batch_size = 2
@@ -127,6 +143,9 @@ class Tester(unittest.TestCase):
error = utils.compute_mse(x_rad, x_deg_to_rad)
self.assertAlmostEqual(error.item(), 0.0, places=4)
+ # functional
+ self.assertTrue(torch.allclose(x_deg, tgm.RadToDeg()(x_rad)))
+
def test_rad2deg_gradcheck(self):
# generate input data
x_rad = tgm.pi * torch.rand(2, 3, 4)
@@ -148,6 +167,9 @@ class Tester(unittest.TestCase):
error = utils.compute_mse(x_deg, x_rad_to_deg)
self.assertAlmostEqual(error.item(), 0.0, places=4)
+ # functional
+ self.assertTrue(torch.allclose(x_rad, tgm.DegToRad()(x_deg)))
+
def test_deg2rad_gradcheck(self):
# generate input data
x_deg = 180. * torch.rand(2, 3, 4)
diff --git a/test/test_homography_warper.py b/test/test_homography_warper.py
index 3ecb6a4d6..f6f1a9968 100644
--- a/test/test_homography_warper.py
+++ b/test/test_homography_warper.py
@@ -46,6 +46,13 @@ class Tester(unittest.TestCase):
threshold = 0.05
self.assertTrue(error.item() < threshold)
+ # check functional api
+ patch_dst_to_src_functional = tgm.homography_warp(
+ patch_dst, tgm.inverse(dst_homo_src_i), (height, width))
+ res = utils.check_equal_torch(patch_dst_to_src,
+ patch_dst_to_src_functional)
+ self.assertTrue(res)
+
def test_homography_warper_gradcheck(self):
# generate input data
batch_size = 1
@@ -71,6 +78,10 @@ class Tester(unittest.TestCase):
raise_exception=True)
self.assertTrue(res)
+ # evaluate function gradient
+ res = gradcheck(tgm.homography_warp, (patch_src, dst_homo_src,
+ (height, width)), raise_exception=True)
+ self.assertTrue(res)
if __name__ == '__main__':
unittest.main()
diff --git a/torchgeometry/__init__.py b/torchgeometry/__init__.py
index 75738df9b..3f6bfd871 100644
--- a/torchgeometry/__init__.py
+++ b/torchgeometry/__init__.py
@@ -1,8 +1,8 @@
-from .functional import *
+from .homography_warper import HomographyWarper, homography_warp
+from .depth_warper import DepthWarper, depth_warp
+from .pinhole import *
from .conversions import *
from .utils import *
-from .homography_warper import HomographyWarper
-from .depth_warper import DepthWarper
__version__ = '0.1.0' # the current version of the lib
diff --git a/torchgeometry/conversions.py b/torchgeometry/conversions.py
index f795574d0..110070c64 100644
--- a/torchgeometry/conversions.py
+++ b/torchgeometry/conversions.py
@@ -1,15 +1,152 @@
import torch
+import torch.nn as nn
import numpy as np
__all__ = [
+ # functional api
+ "pi",
+ "rad2deg",
+ "deg2rad",
+ "convert_points_from_homogeneous",
+ "convert_points_to_homogeneous",
+ "transform_points",
"angle_axis_to_rotation_matrix",
"rotation_matrix_to_angle_axis",
"rotation_matrix_to_quaternion",
"quaternion_to_angle_axis",
"rtvec_to_pose",
+ # layer api
+ "RadToDeg",
+ "DegToRad",
+ "ConvertPointsFromHomogeneous",
+ "ConvertPointsToHomogeneous",
+ "TransformPoints",
+ "AngleAxisToRotationMatrix",
+ "RotationMatrixToAngleAxis",
+ "RotationMatrixToQuaternion",
+ "QuaternionToAngleAxis",
+ "RtvecToPose",
]
+"""Constant with number pi
+"""
+pi = torch.Tensor([3.141592653589793])
+
+
+def rad2deg(tensor):
+ """Converts angles from radians to degrees.
+
+ Args:
+ tensor (Tensor): Tensor to be converted of unspecified shape.
+
+ Returns:
+ Tensor: Converted tensor with same shape as input.
+
+ Example:
+ >>> input = tgm.pi * torch.rand(1, 3, 3)
+ >>> output = tgm.rad2deg(input)
+ """
+ if not torch.is_tensor(tensor):
+ raise TypeError("Input type is not a torch.Tensor. Got {}"
+ .format(type(tensor)))
+
+ return 180. * tensor / pi.to(tensor.device).type(tensor.dtype)
+
+
+def deg2rad(tensor):
+ """Converts angles from degrees to radians.
+
+ Args:
+ tensor (Tensor): Tensor to be converted of unspecified shape.
+
+ Returns:
+ Tensor: Converted tensor with same shape as input.
+
+ Example:
+ >>> input = 360. * torch.rand(1, 3, 3)
+ >>> output = tgm.deg2rad(input)
+ """
+ if not torch.is_tensor(tensor):
+ raise TypeError("Input type is not a torch.Tensor. Got {}"
+ .format(type(tensor)))
+
+ return tensor * pi.to(tensor.device).type(tensor.dtype) / 180.
+
+
+def convert_points_from_homogeneous(points, eps=1e-6):
+ """Converts points from homogeneous to Euclidean space.
+
+ Args:
+ points (Tensor): tensor of N-dimensional points of size (B, D, N).
+
+ Returns:
+ Tensor: tensor of N-1-dimensional points of size (B, D, N-1).
+ """
+ if not torch.is_tensor(points):
+ raise TypeError("Input type is not a torch.Tensor. Got {}".format(
+ type(points)))
+
+ if not len(points.shape) == 3:
+ raise ValueError(
+ "Input size must be a three dimensional tensor. Got {}".format(
+ points.shape))
+
+ return points[..., :-1] / (points[..., -1:] + eps)
+
+
+def convert_points_to_homogeneous(points):
+ """Converts points from Euclidean to homogeneous space.
+
+ Args:
+ points (Tensor): tensor of N-dimensional points of size (B, D, N).
+
+ Returns:
+ Tensor: tensor of N+1-dimensional points of size (B, D, N+1).
+ """
+ if not torch.is_tensor(points):
+ raise TypeError("Input type is not a torch.Tensor. Got {}".format(
+ type(points)))
+
+ if not len(points.shape) == 3:
+ raise ValueError(
+ "Input size must be a three dimensional tensor. Got {}".format(
+ points.shape))
+
+ return torch.cat([points, torch.ones_like(points)[..., :1]], dim=-1)
+
+
+def transform_points(dst_pose_src, points_src):
+ """Applies batch of transformations to batch of sets of points.
+
+ 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).
+
+ Returns:
+ Tensor: tensor of N-dimensional points of size (B, D, N).
+
+ """
+ if not torch.is_tensor(dst_pose_src) or not torch.is_tensor(points_src):
+ raise TypeError("Input type is not a torch.Tensor")
+ if not dst_pose_src.device == points_src.device:
+ raise TypeError("Tensor must be in the same device")
+ if not len(dst_pose_src.shape) == 3 or not len(points_src.shape) == 3:
+ raise ValueError("Input size must be a three dimensional tensor")
+ if not dst_pose_src.shape[0] == points_src.shape[0]:
+ raise ValueError("Input batch size must be the same for both tensors")
+ if not dst_pose_src.shape[2] == (points_src.shape[2] + 1):
+ raise ValueError("Input dimensions must differe by one unit")
+ # to homogeneous
+ points_src_h = convert_points_to_homogeneous(points_src) # BxNxD+1
+ # transform coordinates
+ points_dst_h = torch.matmul(dst_pose_src, points_src_h.transpose(1, 2))
+ points_dst_h = points_dst_h.permute(0, 2, 1) # BxNxD+1
+ # to euclidean
+ points_dst = convert_points_from_homogeneous(points_dst_h) # BxNxD
+ return points_dst
+
+
def angle_axis_to_rotation_matrix_numpy(angle_axis):
"""
Convert 3d vector of axis-angle rotation to 4x4 rotation matrix
@@ -382,3 +519,87 @@ def quaternion_to_angle_axis_torch(quaternion, eps=1e-6):
# TODO: add below funtionalities
# - rotation_matrix_to_angle_axis
# - pose_to_rtvec
+
+
+# layer api
+
+
+class RadToDeg(nn.Module):
+ def __init__(self):
+ super(RadToDeg, self).__init__()
+
+ def forward(self, input):
+ return rad2deg(input)
+
+
+class DegToRad(nn.Module):
+ def __init__(self):
+ super(DegToRad, self).__init__()
+
+ def forward(self, input):
+ return deg2rad(input)
+
+
+class ConvertPointsFromHomogeneous(nn.Module):
+ def __init__(self):
+ super(ConvertPointsFromHomogeneous, self).__init__()
+
+ def forward(self, input):
+ return convert_points_from_homogeneous(input)
+
+
+class ConvertPointsToHomogeneous(nn.Module):
+ def __init__(self):
+ super(ConvertPointsToHomogeneous, self).__init__()
+
+ def forward(self, input):
+ return convert_points_to_homogeneous(input)
+
+
+class TransformPoints(nn.Module):
+ def __init__(self):
+ super(TransformPoints, self).__init__()
+
+ def forward(self, dst_homo_src, points_src):
+ return transform_points(dst_homo_src, points_src)
+
+
+class AngleAxisToRotationMatrix(nn.Module):
+ def __init__(self):
+ super(AngleAxisToRotationMatrix, self).__init__()
+
+ def forward(self, input):
+ return angle_axis_to_rotation_matrix(input)
+
+
+class RotationMatrixToAngleAxis(nn.Module):
+ def __init__(self):
+ super(RotationMatrixToAngleAxis, self).__init__()
+
+ def forward(self, input):
+ return rotation_matrix_to_angle_axis(input)
+
+
+class RotationMatrixToQuaternion(nn.Module):
+ def __init__(self):
+ super(RotationMatrixToQuaterion, self).__init__()
+
+ def forward(self, input):
+ return rotation_matrix_to_quaterion(input)
+
+
+class QuaternionToAngleAxis(nn.Module):
+ def __init__(self):
+ super(QuaternionToAngleAxis, self).__init__()
+
+ def forward(self, input):
+ return quaterion_to_angle_axis(input)
+
+
+class RtvecToPose(nn.Module):
+ def __init__(self):
+ super(RtvecToPose, self).__init__()
+
+ def forward(self, input):
+ return rtvec_to_pose(input)
+>>>>>>> refactor and add layers api
diff --git a/torchgeometry/depth_warper.py b/torchgeometry/depth_warper.py
index ccc120066..28e3c9968 100644
--- a/torchgeometry/depth_warper.py
+++ b/torchgeometry/depth_warper.py
@@ -2,7 +2,13 @@ import torch
import torch.nn as nn
from torch.autograd import Variable
-from .functional import scale_pinhole, homography_i_H_ref
+from .pinhole import scale_pinhole, homography_i_H_ref
+
+
+__all__ = [
+ "depth_warp",
+ "DepthWarper",
+]
class DepthWarper(nn.Module):
@@ -112,3 +118,14 @@ accurate sampling of the depth cost volume, per camera.
def forward(self, inv_depth_ref, data):
# TODO: add type and value checkings
return torch.nn.functional.grid_sample(data, self.warp(inv_depth_ref))
+
+
+# functional api
+
+def depth_warp(pinholes_i, pinhole_ref, inv_depth_ref, patch_i, \
+ width=None, height=None):
+ """Functional API for :class:`torgeometry.DepthWarper`.
+ """
+ warper = DepthWarper(pinholes_i, width=width, height=height)
+ warper.compute_homographies(pinhole_ref)
+ return warper(inv_depth_ref, patch_i)
diff --git a/torchgeometry/homography_warper.py b/torchgeometry/homography_warper.py
index 9907e1482..e6b7bfcb2 100644
--- a/torchgeometry/homography_warper.py
+++ b/torchgeometry/homography_warper.py
@@ -2,7 +2,13 @@ import torch
import torch.nn as nn
import torch.nn.functional as F
-from .functional import transform_points
+from .conversions import transform_points
+
+
+__all__ = [
+ "HomographyWarper",
+ "homography_warp",
+]
def create_meshgrid(height, width, normalized_coordinates=True):
@@ -21,6 +27,8 @@ def create_meshgrid(height, width, normalized_coordinates=True):
return torch.stack(torch.meshgrid([ys, xs])).view(1, 2, -1)[:, (1, 0), :]
+# layer api
+
class HomographyWarper(nn.Module):
'''
Warps patches by homographies.
@@ -109,3 +117,13 @@ height, width '''
.format(patch.device, dst_H_src.device))
return F.grid_sample(patch, self.warp_grid(dst_H_src), 'bilinear',
padding_mode=padding_mode)
+
+# functional api
+
+def homography_warp(patch, dst_H_src, dsize, points=None,
+ padding_mode='zeros'):
+ """Functional API for :class:`torgeometry.HomographyWarper`.
+ """
+ height, width = dsize
+ warper = HomographyWarper(height, width, points)
+ return warper(patch, dst_H_src, padding_mode)
diff --git a/torchgeometry/pinhole.py b/torchgeometry/pinhole.py
new file mode 100644
index 000000000..4c94fda5e
--- /dev/null
+++ b/torchgeometry/pinhole.py
@@ -0,0 +1,197 @@
+import torch
+import torch.nn as nn
+
+from .conversions import rtvec_to_pose
+
+
+__all__ = [
+ # functional api
+ "inverse_pose",
+ "pinhole_matrix",
+ "inverse_pinhole_matrix",
+ "scale_pinhole",
+ "homography_i_H_ref",
+ # layer api
+ "InversePose",
+ "PinholeMatrix",
+ "InversePinholeMatrix",
+ "ScalePinhole",
+ "Homography_i_H_ref",
+]
+
+
+def inverse_pose(pose):
+ """Inverts a 4x4 pose.
+
+ Args:
+ points (Tensor): tensor of either size (4, 4) or (B, 4, 4).
+
+ Returns:
+ Tensor: tensor with same size as input.
+ """
+ if not torch.is_tensor(pose):
+ raise TypeError("Input type is not a torch.Tensor. Got {}".format(
+ type(pose)))
+ if not pose.shape[-2:] == (4, 4):
+ raise ValueError("Input size must be a 4x4 tensor. Got {}"
+ .format(pose.shape))
+ pose_shape = pose.shape
+ if len(pose_shape) == 2:
+ pose = torch.unsqueeze(pose, dim=0)
+
+ pose_inv = pose.clone()
+ pose_inv[..., :3, 0:3] = torch.transpose(pose[..., :3, :3], 1, 2)
+ pose_inv[..., :3, 3:4] = torch.matmul(-1.0 * pose_inv[..., :3, :3],
+ pose[..., :3, 3:4])
+
+ if len(pose_shape) == 2:
+ pose_inv = torch.squeeze(pose_inv, dim=0)
+
+ return pose_inv
+
+
+def pinhole_matrix(pinholes):
+ """Converts vector pinhole representation to 4x4 Tensor
+
+ Args:
+ 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).
+
+ """
+ assert len(pinholes.shape) == 2 and pinholes.shape[1] == 12, pinholes.shape
+ # unpack pinhole values
+ fx, fy, cx, cy = torch.chunk(pinholes[..., :4], 4, dim=1) # Nx1
+ # create output container
+ k = torch.eye(4, device=pinholes.device, dtype=pinholes.dtype)
+ k = k.view(1, 4, 4).repeat(pinholes.shape[0], 1, 1) # Nx4x4
+ # fill output with pinhole values
+ k[..., 0, 0] = fx
+ k[..., 0, 2] = cx
+ k[..., 1, 1] = fy
+ k[..., 1, 2] = cy
+ return k
+
+
+def inv_pinhole_matrix(pinhole, eps=1e-6):
+ """Invert a set of pinholes
+
+ Args:
+ 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).
+
+ """
+ assert len(pinhole.shape) == 2 and pinhole.shape[1] == 12, pinhole.shape
+ # unpack pinhole values
+ fx, fy, cx, cy = torch.chunk(pinhole[..., :4], 4, dim=1) # Nx1
+ # create output container
+ k = torch.eye(4, device=pinhole.device, dtype=pinhole.dtype)
+ k = k.view(1, 4, 4).repeat(pinhole.shape[0], 1, 1) # Nx4x4
+ # fill output with inverse values
+ k[..., 0, 0] = 1. / (fx + eps)
+ k[..., 1, 1] = 1. / (fy + eps)
+ k[..., 0, 2] = -1. * cx / (fx + eps)
+ k[..., 1, 2] = -1. * cy / (fy + eps)
+ return k
+
+
+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).
+ 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).
+
+ """
+ assert len(pinholes.shape) == 2 and pinholes.shape[1] == 12, pinholes.shape
+ assert len(scale.shape) == 2 and scale.shape[1] == 1, scale.shape
+ pinholes_scaled = pinholes.clone()
+ pinholes_scaled[..., :6] = pinholes[..., :6] * scale
+ return pinholes_scaled
+
+
+def get_optical_pose_base(pinholes):
+ """Get extrinsic transformation matrices for pinholes
+
+ Args:
+ 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).
+
+ """
+ assert len(pinholes.shape) == 2 and pinholes.shape[1] == 12, pinholes.shape
+ optical_pose_parent = pinholes[..., 6:]
+ return rtvec_to_pose(optical_pose_parent)
+
+
+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).
+
+ Returns:
+ 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.shape
+ assert pinhole_i.shape == pinhole_ref.shape, pinhole_ref.shape
+ i_pose_base = get_optical_pose_base(pinhole_i)
+ ref_pose_base = get_optical_pose_base(pinhole_ref)
+ i_pose_ref = torch.matmul(i_pose_base, inverse_pose(ref_pose_base))
+ return torch.matmul(
+ pinhole_matrix(pinhole_i),
+ torch.matmul(i_pose_ref, inverse_pinhole_matrix(pinhole_ref)))
+
+
+# layer api
+
+
+class InversePose(nn.Module):
+ def __init__(self):
+ super(InversePose, self).__init__()
+
+ def forward(self, input):
+ return inverse_pose(input)
+
+
+class PinholeMatrix(nn.Module):
+ def __init__(self):
+ super(PinholeMatrix, self).__init__()
+
+ def forward(self, input):
+ return pinhole_matrix(input)
+
+
+class InversePinholeMatrix(nn.Module):
+ def __init__(self):
+ super(InversePinholeMatrix, self).__init__()
+
+ def forward(self, input):
+ return inverse_pinhole_matrix(input)
+
+
+class ScalePinhole(nn.Module):
+ def __init__(self):
+ super(ScalePinhole, self).__init__()
+
+ def forward(self, input, scale):
+ return scale_pinhole(input, scale)
+
+
+class Homography_i_H_ref(nn.Module):
+ def __init__(self):
+ super(Homography_i_H_ref, self).__init__()
+
+ def forward(self, pinhole_i, pinhole_ref):
+ return homography_i_H_ref(pinhole_i, pinhole_ref)
diff --git a/torchgeometry/utils.py b/torchgeometry/utils.py
index a0b5bd9d5..3aa21c56b 100644
--- a/torchgeometry/utils.py
+++ b/torchgeometry/utils.py
@@ -3,15 +3,39 @@ import numpy as np
import torch
import numpy as np
import torchgeometry as tgm
+import torch.nn as nn
+
__all__ = [
"tensor_to_image",
"image_to_tensor",
"draw_rectangle",
"create_pinhole"
+ "inverse",
+ "Inverse",
]
+def inverse(homography):
+ # TODO: add documentation
+ # NOTE: we expect in the future to have a native Pytorch function
+ """Batched version of torch.inverse(...)
+ """
+ if not len(homography.shape) == 3:
+ raise ValueError("Input size must be a three dimensional tensor. Got {}"
+ .format(homography.shape))
+ # iterate, compute inverse and stack tensors
+ return torch.stack([torch.inverse(homo) for homo in homography])
+
+
+class Inverse(nn.Module):
+ def __init__(self):
+ super(Inverse, self).__init__()
+
+ def forward(self, input):
+ return inverse(input)
+
+
def image_to_tensor(image):
"""Converts a numpy image to a torch.Tensor image.