Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

refactor depth_warper tests

edgarriba6ca1c6819e07
diff --git a/test/test_depth_warper.py b/test/test_depth_warper.py
index 2ba84a99d..3143e7717 100644
--- a/test/test_depth_warper.py
+++ b/test/test_depth_warper.py
@@ -11,21 +11,28 @@ from torchgeometry.core.depth_warper import normalize_pixel_coordinates
class TestDepthWarper:
eps = 1e-6
- def _test_compute_projection_matrix(self):
+ def _create_pinhole_pair(self, batch_size):
# prepare data
- batch_size, height, width = 1, 3, 5
fx, fy = 1., 1.
+ height, width = 3, 5
cx, cy = width / 2, height / 2
tx, ty, tz = 0, 0, 0
# create pinhole cameras
pinhole_src = tgm.PinholeCamera.from_parameters(
- fx, fy, cx, cy, height, width, tx, ty, tz)
+ fx, fy, cx, cy, height, width, tx, ty, tz, batch_size)
pinhole_dst = tgm.PinholeCamera.from_parameters(
- fx, fy, cx, cy, height, width, tx + 1., ty, tz)
+ fx, fy, cx, cy, height, width, tx, ty, tz, batch_size)
+ return pinhole_src, pinhole_dst
+
+ @pytest.mark.parametrize("batch_size", (1, 2,))
+ def test_compute_projection_matrix_one_cam(self, batch_size):
+ height, width = 3, 5 # output shape
+ pinhole_src, pinhole_dst = self._create_pinhole_pair(batch_size)
+ pinhole_dst.tx += 1. # apply offset to tx
# create warper
- warper = tgm.DepthWarper(None, height, width, pinhole_dst)
+ warper = tgm.DepthWarper([pinhole_dst, ], height, width)
assert warper._dst_proj_src is None
# initialize projection matrices
@@ -34,32 +41,51 @@ class TestDepthWarper:
# retreive computed projection matrix and compare to expected
dst_proj_src = warper._dst_proj_src
- dst_proj_src_expected = torch.eye(4)[None] # Bx4x4
- dst_proj_src_expected[..., 0, -2] += cx
- dst_proj_src_expected[..., 1, -2] += cy
+ dst_proj_src_expected = torch.eye(
+ 4)[None].repeat(batch_size, 1, 1) # Bx4x4
+ dst_proj_src_expected[..., 0, -2] += pinhole_src.cx
+ dst_proj_src_expected[..., 1, -2] += pinhole_src.cy
dst_proj_src_expected[..., 0, -1] += 1. # offset to x-axis
assert utils.check_equal_torch(dst_proj_src, dst_proj_src_expected)
- def _test_warp_grid_offset_x1_depth1(self):
- # prepare data
- batch_size, height, width = 1, 3, 5
- fx, fy = 1., 1.
- cx, cy = width / 2, height / 2
- tx, ty, tz = 0, 0, 0
+ @pytest.mark.parametrize("batch_size", (1, 2,))
+ def test_compute_projection_matrix_two_cams(self, batch_size):
+ height, width = 3, 5 # output shape
+ pinhole_src, pinhole_dst = self._create_pinhole_pair(batch_size)
+ pinhole_dst.tx += 1. # apply offset to tx
- # create pinhole cameras
- pinhole_src = tgm.PinholeCamera.from_parameters(
- fx, fy, cx, cy, height, width, tx, ty, tz)
- pinhole_dst = tgm.PinholeCamera.from_parameters(
- fx, fy, cx, cy, height, width, tx + 1., ty, tz)
+ # create warper
+ warper = tgm.DepthWarper([pinhole_dst, pinhole_src], height, width)
+ assert warper._dst_proj_src is None
+
+ # initialize projection matrices
+ warper.compute_projection_matrix(pinhole_src)
+ assert warper._dst_proj_src is not None
+
+ # retreive computed projection matrix and compare to expected
+ dst_proj_src = warper._dst_proj_src
+ dst_proj_src_expected = torch.eye(
+ 4)[None, None].repeat(1, 2, 1, 1) # BxNx4x4
+ dst_proj_src_expected[..., 0, -2] += pinhole_src.cx
+ dst_proj_src_expected[..., 1, -2] += pinhole_src.cy
+ dst_proj_src_expected[..., 0, 0, -1] += 1. # offset to x-axis
+ assert utils.check_equal_torch(dst_proj_src, dst_proj_src_expected)
+
+ @pytest.mark.parametrize("batch_size", (1, 2,))
+ def test_warp_grid_offset_x1_depth1_one_cam(self, batch_size):
+ height, width = 3, 5 # output shape
+ pinhole_src, pinhole_dst = self._create_pinhole_pair(batch_size)
+ pinhole_dst.tx += 1. # apply offset to tx
# initialize depth to one
depth_src = torch.ones(batch_size, 1, height, width)
# create warper, initialize projection matrices and warp grid
- warper = tgm.DepthWarper(None, height, width, pinhole_dst)
+ warper = tgm.DepthWarper([pinhole_dst, ], height, width)
warper.compute_projection_matrix(pinhole_src)
+
grid_warped = warper.warp_grid(depth_src)
+ assert grid_warped.shape == (batch_size, height, width, 2)
# normalize base meshgrid
grid = warper.grid[..., :2]
@@ -72,26 +98,22 @@ class TestDepthWarper:
assert utils.check_equal_torch(
grid_norm[..., -1, 1], grid_warped[..., -1, 1])
- def _test_warp_grid_offset_x1y1_depth1(self):
- # prepare data
- batch_size, height, width = 1, 3, 5
- fx, fy = 1., 1.
- cx, cy = width / 2, height / 2
- tx, ty, tz = 0, 0, 0
-
- # create pinhole cameras
- pinhole_src = tgm.PinholeCamera.from_parameters(
- fx, fy, cx, cy, height, width, tx, ty, tz)
- pinhole_dst = tgm.PinholeCamera.from_parameters(
- fx, fy, cx, cy, height, width, tx + 1., ty + 1., tz)
+ @pytest.mark.parametrize("batch_size", (1, 2,))
+ def test_warp_grid_offset_x1y1_depth1(self, batch_size):
+ height, width = 3, 5 # output shape
+ pinhole_src, pinhole_dst = self._create_pinhole_pair(batch_size)
+ pinhole_dst.tx += 1. # apply offset to tx
+ pinhole_dst.ty += 1. # apply offset to ty
# initialize depth to one
depth_src = torch.ones(batch_size, 1, height, width)
# create warper, initialize projection matrices and warp grid
- warper = tgm.DepthWarper(None, height, width, pinhole_dst)
+ warper = tgm.DepthWarper([pinhole_dst, ], height, width)
warper.compute_projection_matrix(pinhole_src)
+
grid_warped = warper.warp_grid(depth_src)
+ assert grid_warped.shape == (batch_size, height, width, 2)
# normalize base meshgrid
grid = warper.grid[..., :2]
@@ -104,63 +126,54 @@ class TestDepthWarper:
assert utils.check_equal_torch(
grid_norm[..., -1, :, 1], grid_warped[..., -2, :, 1])
- def _test_warp_grid_offset_x1y1_depth1_batch2(self):
- # prepare data
- batch_size, height, width = 1, 3, 5
- fx, fy = 1., 1.
- cx, cy = width / 2, height / 2
- tx, ty, tz = 0, 0, 0
-
- # create pinhole cameras
- pinhole_src = tgm.PinholeCamera.from_parameters(
- fx, fy, cx, cy, height, width, tx, ty, tz)
- pinhole_dst = tgm.PinholeCamera.from_parameters(
- fx, fy, cx, cy, height, width, tx + 1., ty + 1., tz)
- import pdb
- pdb.set_trace()
+ @pytest.mark.parametrize("batch_size", (1, 2,))
+ def test_warp_grid_offset_x1y1_depth1_two_cams(self, batch_size):
+ height, width = 3, 5 # output shape
+ pinhole_src, pinhole_dst = self._create_pinhole_pair(batch_size)
+ pinhole_dst.tx += 1. # apply offset to tx
+ pinhole_dst.ty += 1. # apply offset to ty
+ num_cams = 2
# initialize depth to one
depth_src = torch.ones(batch_size, 1, height, width)
# create warper, initialize projection matrices and warp grid
- warper = tgm.DepthWarper(None, height, width, pinhole_dst)
+ warper = tgm.DepthWarper([pinhole_dst, pinhole_src], height, width)
warper.compute_projection_matrix(pinhole_src)
+
grid_warped = warper.warp_grid(depth_src)
+ assert grid_warped.shape == (batch_size * num_cams, height, width, 2)
# normalize base meshgrid
grid = warper.grid[..., :2]
grid_norm = normalize_pixel_coordinates(grid, height, width)
- # check offset in x-axis
+ # check offset in x-axis in the first camera
assert utils.check_equal_torch(
- grid_norm[..., -1, 0], grid_warped[..., -2, 0])
- # check that y-axis remain the same
+ grid_norm[0:1, ..., -1, 0], grid_warped[0:1, ..., -2, 0])
+ # check offset in y-axis in the first camera
assert utils.check_equal_torch(
- grid_norm[..., -1, :, 1], grid_warped[..., -2, :, 1])
+ grid_norm[0:1, ..., -1, :, 1], grid_warped[0:1, ..., -2, :, 1])
+ # check that second camera grid is the same
+ assert utils.check_equal_torch(grid_norm, grid_warped[1:2])
- def _test_depth_warper_offset_tensor(self):
- # prepare data
- batch_size, channels, height, width = 1, 3, 3, 5
- fx, fy = 1., 1.
- cx, cy = width / 2, height / 2
- tx, ty, tz = 0, 0, 0
-
- # create pinhole cameras
- pinhole_src = tgm.PinholeCamera.from_parameters(
- fx, fy, cx, cy, height, width, tx, ty, tz)
- pinhole_dst = tgm.PinholeCamera.from_parameters(
- fx, fy, cx, cy, height, width, tx + 1., ty + 1., tz)
+ @pytest.mark.parametrize("batch_size", (1, 2,))
+ def test_warp_tensor_offset_x1y1(self, batch_size):
+ channels, height, width = 3, 3, 5 # output shape
+ pinhole_src, pinhole_dst = self._create_pinhole_pair(batch_size)
+ pinhole_dst.tx += 1. # apply offset to tx
+ pinhole_dst.ty += 1. # apply offset to ty
# initialize depth to one
depth_src = torch.ones(batch_size, 1, height, width)
# create warper, initialize projection matrices and warp grid
- warper = tgm.DepthWarper(None, height, width, pinhole_dst)
+ warper = tgm.DepthWarper([pinhole_dst, ], height, width)
warper.compute_projection_matrix(pinhole_src)
# create patch to warp
patch_dst = torch.arange(float(height * width)).view(
- batch_size, 1, height, width).expand(batch_size, channels, -1, -1)
+ 1, 1, height, width).expand(batch_size, channels, -1, -1)
# warpd source patch by depth
patch_src = warper(depth_src, patch_dst)
@@ -169,19 +182,82 @@ class TestDepthWarper:
assert utils.check_equal_torch(
patch_dst[..., 1:, 1:], patch_src[..., :2, :4])
+ @pytest.mark.parametrize("batch_size", (1,))
+ def test_warp_tensor_offset_x1y1_two_cams(self, batch_size):
+ # prepare data
+ num_cameras = 2
+ channels, height, width = 3, 3, 5 # output shape
+ pinhole_src, pinhole_dst = self._create_pinhole_pair(batch_size)
+ pinhole_dst.tx += 1. # apply offset to tx
+ pinhole_dst.ty += 1. # apply offset to ty
+
+ # initialize depth to one
+ depth_src = torch.ones(batch_size, 1, height, width)
+
+ # create warper, initialize projection matrices and warp grid
+ warper = tgm.DepthWarper([pinhole_dst, pinhole_src], height, width)
+ warper.compute_projection_matrix(pinhole_src)
+
+ # create patch to warp
+ patch_dst = torch.arange(float(height * width))[None, None, None]
+ patch_dst = patch_dst.repeat(batch_size, num_cameras, channels, 1, 1)
+ patch_dst[:, 1] *= 2
+ patch_dst = patch_dst.view(-1, channels, height, width)
+
+ # warpd source patch by depth
+ patch_src = warper(depth_src, patch_dst)
+
+ # compare patches
+ assert utils.check_equal_torch(
+ patch_dst[:1, ..., 1:, 1:], patch_src[:1, ..., :2, :4])
+ assert utils.check_equal_torch(patch_dst[1:], patch_src[1:])
+
+ @pytest.mark.parametrize("batch_size", (1, 2,))
+ def test_compute_projection(self, batch_size):
+ height, width = 3, 5 # output shape
+ pinhole_src, pinhole_dst = self._create_pinhole_pair(batch_size)
+
+ # create warper, initialize projection matrices and warp grid
+ warper = tgm.DepthWarper([pinhole_dst, ], height, width)
+ warper.compute_projection_matrix(pinhole_src)
+
# test compute_projection
- # TODO: this might need a better test
xy_projected = warper._compute_projection(0.0, 0.0, 1.0)
- assert xy_projected.shape == (1, 2)
+ assert xy_projected.shape == (batch_size, 2)
+
+ @pytest.mark.parametrize("batch_size", (1, 2,))
+ def test_compute_subpixel_step(self, batch_size):
+ height, width = 3, 5 # output shape
+ pinhole_src, pinhole_dst = self._create_pinhole_pair(batch_size)
+
+ # create warper, initialize projection matrices and warp grid
+ warper = tgm.DepthWarper([pinhole_dst, ], height, width)
+ warper.compute_projection_matrix(pinhole_src)
# test compute_subpixel_step
- # TODO: this might need a better test
subpixel_step = warper.compute_subpixel_step()
assert pytest.approx(subpixel_step.item(), 0.3536)
- def test_run_all(self):
- self._test_compute_projection_matrix()
- self._test_warp_grid_offset_x1_depth1()
- self._test_warp_grid_offset_x1y1_depth1()
- # self._test_warp_grid_offset_x1y1_depth1_batch2()
- self._test_depth_warper_offset_tensor()
+ @pytest.mark.parametrize("batch_size", (1, 2))
+ def test_gradcheck(self, batch_size):
+ # prepare data
+ channels, height, width = 3, 3, 5 # output shape
+ pinhole_src, pinhole_dst = self._create_pinhole_pair(batch_size)
+
+ # initialize depth to one
+ depth_src = torch.ones(batch_size, 1, height, width)
+ depth_src = utils.tensor_to_gradcheck_var(depth_src) # to var
+
+ # create patch to warp
+ img_dst = torch.ones(batch_size, channels, height, width)
+ img_dst = utils.tensor_to_gradcheck_var(img_dst) # to var
+
+ # evaluate function gradient
+ assert gradcheck(tgm.depth_warp,
+ ([pinhole_dst,], pinhole_src, depth_src, img_dst, height, width,),
+ raise_exception=True)
+
+
+ # TODO(edgar): we should include a test showing some kind of occlusion
+ # def test_warp_with_occlusion(self):
+ # pass
diff --git a/test/test_pinhole.py b/test/test_pinhole.py
index c60cd6b63..5d90d7a5e 100644
--- a/test/test_pinhole.py
+++ b/test/test_pinhole.py
@@ -168,63 +168,65 @@ class TestPinholeCamera:
pinhole_scale = pinhole.scale(scale_factor)
assert utils.check_equal_torch(pinhole_scale.intrinsics[..., 0, 0],
- pinhole.intrinsics[..., 0, 0] * scale_val) # fx
+ pinhole.intrinsics[..., 0, 0] * scale_val) # fx
assert utils.check_equal_torch(pinhole_scale.intrinsics[..., 1, 1],
- pinhole.intrinsics[..., 1, 1] * scale_val) # fy
+ pinhole.intrinsics[..., 1, 1] * scale_val) # fy
assert utils.check_equal_torch(pinhole_scale.intrinsics[..., 0, 2],
- pinhole.intrinsics[..., 0, 2] * scale_val) # cx
+ pinhole.intrinsics[..., 0, 2] * scale_val) # cx
assert utils.check_equal_torch(pinhole_scale.intrinsics[..., 1, 2],
- pinhole.intrinsics[..., 1, 2] * scale_val) # cy
- assert utils.check_equal_torch(pinhole_scale.height,
- pinhole.height * scale_val) # image_height
- assert utils.check_equal_torch(pinhole_scale.width,
- pinhole.width * scale_val) # image_width
+ pinhole.intrinsics[..., 1, 2] * scale_val) # cy
+ assert utils.check_equal_torch(
+ pinhole_scale.height,
+ pinhole.height * scale_val)
+ assert utils.check_equal_torch(
+ pinhole_scale.width,
+ pinhole.width * scale_val)
def test_pinhole_camera_scale_inplace(self):
- batch_size = 2
- height, width = 4, 6
- fx, fy, cx, cy = 1, 2, width / 2, height / 2
- tx, ty, tz = 1, 2, 3
- scale_val = 2.0
-
- intrinsics = self._create_intrinsics(batch_size, fx, fy, cx, cy)
- extrinsics = self._create_extrinsics(batch_size, tx, ty, tz)
- height = torch.ones(batch_size) * height
- width = torch.ones(batch_size) * width
- scale_factor = torch.ones(batch_size) * scale_val
-
- pinhole = tgm.PinholeCamera(intrinsics, extrinsics, height, width)
- pinhole_scale = pinhole.clone()
+ batch_size=2
+ height, width=4, 6
+ fx, fy, cx, cy=1, 2, width / 2, height / 2
+ tx, ty, tz=1, 2, 3
+ scale_val=2.0
+
+ intrinsics=self._create_intrinsics(batch_size, fx, fy, cx, cy)
+ extrinsics=self._create_extrinsics(batch_size, tx, ty, tz)
+ height=torch.ones(batch_size) * height
+ width=torch.ones(batch_size) * width
+ scale_factor=torch.ones(batch_size) * scale_val
+
+ pinhole=tgm.PinholeCamera(intrinsics, extrinsics, height, width)
+ pinhole_scale=pinhole.clone()
pinhole_scale.scale_(scale_factor)
assert utils.check_equal_torch(pinhole_scale.intrinsics[..., 0, 0],
- pinhole.intrinsics[..., 0, 0] * scale_val) # fx
+ pinhole.intrinsics[..., 0, 0] * scale_val) # fx
assert utils.check_equal_torch(pinhole_scale.intrinsics[..., 1, 1],
- pinhole.intrinsics[..., 1, 1] * scale_val) # fy
+ pinhole.intrinsics[..., 1, 1] * scale_val) # fy
assert utils.check_equal_torch(pinhole_scale.intrinsics[..., 0, 2],
- pinhole.intrinsics[..., 0, 2] * scale_val) # cx
+ pinhole.intrinsics[..., 0, 2] * scale_val) # cx
assert utils.check_equal_torch(pinhole_scale.intrinsics[..., 1, 2],
- pinhole.intrinsics[..., 1, 2] * scale_val) # cy
- assert utils.check_equal_torch(pinhole_scale.height,
- pinhole.height * scale_val) # image_height
- assert utils.check_equal_torch(pinhole_scale.width,
- pinhole.width * scale_val) # image_width
+ pinhole.intrinsics[..., 1, 2] * scale_val) # cy
+ assert utils.check_equal_torch(
+ pinhole_scale.height, pinhole.height * scale_val)
+ assert utils.check_equal_torch(
+ pinhole_scale.width, pinhole.width * scale_val)
@pytest.mark.parametrize("device_type", TEST_DEVICES)
@pytest.mark.parametrize("batch_size", [1, 2, 5, 6])
def test_scale_pinhole(batch_size, device_type):
# generate input data
- device = torch.device(device_type)
- pinholes = torch.rand(batch_size, 12).to(device)
- scales = torch.rand(batch_size).to(device)
+ device=torch.device(device_type)
+ pinholes=torch.rand(batch_size, 12).to(device)
+ scales=torch.rand(batch_size).to(device)
- pinholes_scale = tgm.scale_pinhole(pinholes, scales)
+ pinholes_scale=tgm.scale_pinhole(pinholes, scales)
assert utils.check_equal_torch(
pinholes_scale[..., :6] / scales.unsqueeze(-1), pinholes[..., :6])
# evaluate function gradient
- pinholes = utils.tensor_to_gradcheck_var(pinholes) # to var
- scales = utils.tensor_to_gradcheck_var(scales) # to var
+ pinholes=utils.tensor_to_gradcheck_var(pinholes) # to var
+ scales=utils.tensor_to_gradcheck_var(scales) # to var
assert gradcheck(tgm.scale_pinhole, (pinholes, scales,),
raise_exception=True)
@@ -233,21 +235,21 @@ def test_scale_pinhole(batch_size, device_type):
@pytest.mark.parametrize("batch_size", [1, 2, 5, 6])
def test_pinhole_matrix(batch_size, device_type):
# generate input data
- image_height, image_width = 32., 32.
- cx, cy = image_width / 2, image_height / 2
- fx, fy = 1., 1.
- rx, ry, rz = 0., 0., 0.
- tx, ty, tz = 0., 0., 0.
- offset_x = 10. # we will apply a 10units offset to `i` camera
- eps = 1e-6
-
- pinhole = utils.create_pinhole(
+ image_height, image_width=32., 32.
+ cx, cy=image_width / 2, image_height / 2
+ fx, fy=1., 1.
+ rx, ry, rz=0., 0., 0.
+ tx, ty, tz=0., 0., 0.
+ offset_x=10. # we will apply a 10units offset to `i` camera
+ eps=1e-6
+
+ pinhole=utils.create_pinhole(
fx, fy, cx, cy, image_height, image_width, rx, ry, rx, tx, ty, tz)
- pinhole = pinhole.repeat(batch_size, 1).to(torch.device(device_type))
+ pinhole=pinhole.repeat(batch_size, 1).to(torch.device(device_type))
- pinhole_matrix = tgm.pinhole_matrix(pinhole)
+ pinhole_matrix=tgm.pinhole_matrix(pinhole)
- ones = torch.ones(batch_size)
+ ones=torch.ones(batch_size)
assert bool((pinhole_matrix[:, 0, 0] == fx * ones).all())
assert bool((pinhole_matrix[:, 1, 1] == fy * ones).all())
assert bool((pinhole_matrix[:, 0, 2] == cx * ones).all())
@@ -257,7 +259,7 @@ def test_pinhole_matrix(batch_size, device_type):
assert tgm.PinholeMatrix()(pinhole).shape == (batch_size, 4, 4)
# evaluate function gradient
- pinhole = utils.tensor_to_gradcheck_var(pinhole) # to var
+ pinhole=utils.tensor_to_gradcheck_var(pinhole) # to var
assert gradcheck(tgm.pinhole_matrix, (pinhole,),
raise_exception=True)
@@ -266,21 +268,21 @@ def test_pinhole_matrix(batch_size, device_type):
@pytest.mark.parametrize("batch_size", [1, 2, 5, 6])
def test_inverse_pinhole_matrix(batch_size, device_type):
# generate input data
- image_height, image_width = 32., 32.
- cx, cy = image_width / 2, image_height / 2
- fx, fy = 1., 1.
- rx, ry, rz = 0., 0., 0.
- tx, ty, tz = 0., 0., 0.
- offset_x = 10. # we will apply a 10units offset to `i` camera
- eps = 1e-6
-
- pinhole = utils.create_pinhole(
+ image_height, image_width=32., 32.
+ cx, cy=image_width / 2, image_height / 2
+ fx, fy=1., 1.
+ rx, ry, rz=0., 0., 0.
+ tx, ty, tz=0., 0., 0.
+ offset_x=10. # we will apply a 10units offset to `i` camera
+ eps=1e-6
+
+ pinhole=utils.create_pinhole(
fx, fy, cx, cy, image_height, image_width, rx, ry, rx, tx, ty, tz)
- pinhole = pinhole.repeat(batch_size, 1).to(torch.device(device_type))
+ pinhole=pinhole.repeat(batch_size, 1).to(torch.device(device_type))
- pinhole_matrix = tgm.inverse_pinhole_matrix(pinhole)
+ pinhole_matrix=tgm.inverse_pinhole_matrix(pinhole)
- ones = torch.ones(batch_size)
+ ones=torch.ones(batch_size)
assert utils.check_equal_torch(pinhole_matrix[:, 0, 0], (1. / fx) * ones)
assert utils.check_equal_torch(pinhole_matrix[:, 1, 1], (1. / fy) * ones)
assert utils.check_equal_torch(
@@ -292,7 +294,7 @@ def test_inverse_pinhole_matrix(batch_size, device_type):
assert tgm.InversePinholeMatrix()(pinhole).shape == (batch_size, 4, 4)
# evaluate function gradient
- pinhole = utils.tensor_to_gradcheck_var(pinhole) # to var
+ pinhole=utils.tensor_to_gradcheck_var(pinhole) # to var
assert gradcheck(tgm.pinhole_matrix, (pinhole,),
raise_exception=True)
@@ -301,20 +303,20 @@ def test_inverse_pinhole_matrix(batch_size, device_type):
@pytest.mark.parametrize("batch_size", [1, 2, 5, 6])
def test_homography_i_H_ref(batch_size, device_type):
# generate input data
- device = torch.device(device_type)
- image_height, image_width = 32., 32.
- cx, cy = image_width / 2, image_height / 2
- fx, fy = 1., 1.
- rx, ry, rz = 0., 0., 0.
- tx, ty, tz = 0., 0., 0.
- offset_x = 10. # we will apply a 10units offset to `i` camera
- eps = 1e-6
-
- pinhole_ref = utils.create_pinhole(
+ device=torch.device(device_type)
+ image_height, image_width=32., 32.
+ cx, cy=image_width / 2, image_height / 2
+ fx, fy=1., 1.
+ rx, ry, rz=0., 0., 0.
+ tx, ty, tz=0., 0., 0.
+ offset_x=10. # we will apply a 10units offset to `i` camera
+ eps=1e-6
+
+ pinhole_ref=utils.create_pinhole(
fx, fy, cx, cy, image_height, image_width, rx, ry, rx, tx, ty, tz)
- pinhole_ref = pinhole_ref.repeat(batch_size, 1).to(device)
+ pinhole_ref=pinhole_ref.repeat(batch_size, 1).to(device)
- pinhole_i = utils.create_pinhole(
+ pinhole_i=utils.create_pinhole(
fx,
fy,
cx,
@@ -327,14 +329,14 @@ def test_homography_i_H_ref(batch_size, device_type):
tx + offset_x,
ty,
tz)
- pinhole_i = pinhole_i.repeat(batch_size, 1).to(device)
+ pinhole_i=pinhole_i.repeat(batch_size, 1).to(device)
# compute homography from ref to i
- i_H_ref = tgm.homography_i_H_ref(pinhole_i, pinhole_ref) + eps
- i_H_ref_inv = torch.inverse(i_H_ref)
+ i_H_ref=tgm.homography_i_H_ref(pinhole_i, pinhole_ref) + eps
+ i_H_ref_inv=torch.inverse(i_H_ref)
# compute homography from i to ref
- ref_H_i = tgm.homography_i_H_ref(pinhole_ref, pinhole_i) + eps
+ ref_H_i=tgm.homography_i_H_ref(pinhole_ref, pinhole_i) + eps
assert utils.check_equal_torch(i_H_ref_inv, ref_H_i)
# evaluate function gradient
diff --git a/torchgeometry/core/depth_warper.py b/torchgeometry/core/depth_warper.py
index 596793d5d..036ef4a75 100644
--- a/torchgeometry/core/depth_warper.py
+++ b/torchgeometry/core/depth_warper.py
@@ -1,16 +1,14 @@
-from typing import Optional
+from typing import Optional, Iterable, Union
import torch
import torch.nn as nn
import torch.nn.functional as F
from torchgeometry.utils import create_meshgrid
+from torchgeometry.core.transformations import relative_pose
from torchgeometry.core.conversions import transform_points
from torchgeometry.core.conversions import convert_points_to_homogeneous
-from torchgeometry.core.transformations import relative_pose
-# NOTE: remove later
-from torchgeometry.core.pinhole import PinholeCamera
-from torchgeometry.core.pinhole import scale_pinhole, homography_i_H_ref
+from torchgeometry.core.pinhole import PinholeCamera, PinholeCamerasList
__all__ = [
@@ -81,7 +79,8 @@ def pixel2cam(depth: torch.Tensor, intrinsics_inv: torch.Tensor,
if not len(pixel_coords.shape) == 4 and pixel_coords.shape[3] == 3:
raise ValueError("Input pixel_coords has to be in the shape of "
"BxHxWx3. Got {}".format(intrinsics_inv.shape))
- cam_coords: torch.Tensor = transform_points(intrinsics_inv, pixel_coords)
+ cam_coords: torch.Tensor = transform_points(
+ intrinsics_inv[:, None], pixel_coords)
return cam_coords * depth.permute(0, 2, 3, 1)
@@ -111,7 +110,8 @@ def cam2pixel(
"Bx4x4. Got {}".format(dst_proj_src.shape))
b, h, w, _ = cam_coords_src.shape
# apply projection matrix to points
- point_coords: torch.Tensor = transform_points(dst_proj_src, cam_coords_src)
+ point_coords: torch.Tensor = transform_points(
+ dst_proj_src[:, None], cam_coords_src)
x_coord: torch.Tensor = point_coords[..., 0]
y_coord: torch.Tensor = point_coords[..., 1]
z_coord: torch.Tensor = point_coords[..., 2]
@@ -122,49 +122,38 @@ def cam2pixel(
# stack and return the coordinates, that's the actual flow
pixel_coords_dst: torch.Tensor = torch.stack([u_coord, v_coord], dim=-1)
- return pixel_coords_dst # BxHxWx2
+ return pixel_coords_dst # (B*N)xHxWx2
class DepthWarper(nn.Module):
- """Warps a patch by inverse depth.
+ """Warps a patch by depth.
.. math::
- H_{ref}^{i} = K_{i} * T_{ref}^{i} * K_{ref}^{-1}
+ H_{src}^{dst} = K_{dst} * T_{src}^{dst} * K_{src}^{-1}
- I_{ref} = \\omega(I_{i}, H_{ref}^{i}, \\xi_{ref})
+ I_{src} = \\omega(I_{dst}, H_{src}^{dst}, D_{src})
Args:
- pinholes (torch.Tensor): The pinhole models for ith frame with
- shape `[Nx12]`.
- width (int): The width of the image to warp. Optional.
- height (int): The height of the image to warp. Optional.
+ pinholes_dst (Iterable[PinholeCamera]): The pinhole models for the
+ destination frame.
+ height (int): The height of the image to warp.
+ width (int): The width of the image to warp.
"""
def __init__(self,
- pinholes: torch.Tensor,
- height: int,
- width: int,
- pinhole_dst):
+ pinholes_dst: Iterable[PinholeCamera],
+ height: int, width: int):
super(DepthWarper, self).__init__()
self.width: int = width
self.height: int = height
self.eps = 1e-6
- # old parameters
- self._pinholes = pinholes
- self._i_Hs_ref = None # to be filled later
- self._pinhole_ref = None # to be filled later
+ self._pinhole_dst: PinholeCamerasList = PinholeCamerasList(pinholes_dst)
+ self._pinhole_src: Union[None, PinholeCamera] = None
+ self._dst_proj_src: Union[None, torch.Tensor] = None
- # new refactor parameters
self.grid: torch.Tensor = self._create_meshgrid(height, width)
- self._pinhole_src = None # to be filled later
- self._dst_proj_src = None # to be filled later
-
- if not isinstance(pinhole_dst, PinholeCamera):
- raise TypeError("Argument pinhole_dst expected to be of class "
- "PinholeCamera. Got {}".format(type(pinhole_dst)))
- self._pinhole_dst = pinhole_dst
@staticmethod
def _create_meshgrid(height: int, width: int) -> torch.Tensor:
@@ -173,7 +162,7 @@ class DepthWarper(nn.Module):
return convert_points_to_homogeneous(grid) # append ones to last dim
# TODO(edgar): remove
- def compute_homographies(self, pinhole, scale=None):
+ '''def compute_homographies(self, pinhole, scale=None):
if scale is None:
batch_size = pinhole.shape[0]
scale = torch.ones(
@@ -188,31 +177,42 @@ class DepthWarper(nn.Module):
self._pinhole_ref = pinhole_ref
# scale pinholes_i and compute homographies
pinhole_i = scale_pinhole(self._pinholes, scale)
- self._i_Hs_ref = homography_i_H_ref(pinhole_i, pinhole_ref)
+ self._i_Hs_ref = homography_i_H_ref(pinhole_i, pinhole_ref)'''
- def compute_projection_matrix(self, pinhole_src):
- # TODO: add documentation
+ def compute_projection_matrix(self, pinhole_src: PinholeCamera):
if not isinstance(pinhole_src, PinholeCamera):
raise TypeError("Argument pinhole_src expected to be of class "
- "PinholeCamera. Got {}".format(type(pinhole_dst)))
+ "PinholeCamera. Got {}".format(type(pinhole_src)))
# compute the relative pose between the non reference and the reference
# camera frames.
- dst_trans_src = relative_pose(
- pinhole_src.extrinsics, self._pinhole_dst.extrinsics)
+ batch_size: int = pinhole_src.batch_size
+ num_cameras: int = self._pinhole_dst.num_cameras
+
+ extrinsics_src: torch.Tensor = pinhole_src.extrinsics[:, None].expand(
+ -1, num_cameras, -1, -1) # BxNx4x4
+ extrinsics_src = extrinsics_src.contiguous().view(-1, 4, 4) # (B*N)x4x4
+ extrinsics_dst: torch.Tensor = self._pinhole_dst.extrinsics.view(
+ -1, 4, 4) # (B*N)x4x4
+ dst_trans_src: torch.Tensor = relative_pose(
+ extrinsics_src, extrinsics_dst)
# compute the projection matrix between the non reference cameras and
# the reference.
- self._dst_proj_src = torch.matmul(
- self._pinhole_dst.intrinsics, dst_trans_src)
+ intrinsics_dst: torch.Tensor = self._pinhole_dst.intrinsics.view(
+ -1, 4, 4)
+ dst_proj_src: torch.Tensor = torch.matmul(
+ intrinsics_dst, dst_trans_src)
# update class member
self._pinhole_src = pinhole_src
+ self._dst_proj_src = dst_proj_src.view(
+ pinhole_src.batch_size, -1, 4, 4)
return self
def _compute_projection(self, x, y, invd):
point = torch.FloatTensor([[[x], [y], [1.0], [invd]]])
flow = torch.matmul(
- self._dst_proj_src, point.to(self._dst_proj_src.device))
+ self._dst_proj_src[:, 0], point.to(self._dst_proj_src.device))
z = 1. / flow[:, 2]
x = (flow[:, 0] * z)
y = (flow[:, 1] * z)
@@ -251,7 +251,7 @@ class DepthWarper(nn.Module):
raise ValueError("Please, call compute_projection_matrix.")
if len(depth_src.shape) != 4:
- raise ValueError("Input depth_src has to be in the shape of"
+ raise ValueError("Input depth_src has to be in the shape of "
"Bx1xHxW. Got {}".format(depth_src.shape))
# unpack depth attributes
@@ -261,162 +261,86 @@ class DepthWarper(nn.Module):
# expand the base coordinate grid according to the input batch size
pixel_coords: torch.Tensor = self.grid.to(device).to(dtype).expand(
- batch_size, -1, -1, -1)
+ batch_size, -1, -1, -1) # BxHxWx3
# reproject the pixel coordinates to the camera frame
cam_coords_src: torch.Tensor = pixel2cam(
depth_src,
- self._pinhole_src.intrinsics_inverse(),
+ self._pinhole_src.intrinsics_inverse().to(dtype),
pixel_coords) # BxHxWx3
+ # create views from tensors to match with cam2pixel expected shapes
+ cam_coords_src = cam_coords_src[:, None].expand(
+ -1, self._pinhole_dst.num_cameras, -1, -1, -1) # BxNxHxWx3
+ cam_coords_src = cam_coords_src.contiguous().view(
+ -1, height, width, 3) # (B*N)xHxWx3
+ dst_proj_src: torch.Tensor = self._dst_proj_src.view(-1, 4, 4)
+
# reproject the camera coordinates to the pixel
pixel_coords_src: torch.Tensor = cam2pixel(
- cam_coords_src, self._dst_proj_src) # BxHxWx2
+ cam_coords_src, dst_proj_src.to(dtype)) # (B*N)xHxWx2
# normalize between -1 and 1 the coordinates
pixel_coords_src_norm: torch.Tensor = normalize_pixel_coordinates(
pixel_coords_src, self.height, self.width)
return pixel_coords_src_norm
- def warp_grid_old(
+ def forward(
self,
- inv_depth_ref: torch.Tensor,
- roi=None) -> torch.Tensor:
- """Computes a grid for warping a given the inverse depth from
- a reference pinhole camera.
-
- The function `compute_homographies` has to be called beforehand in
- order to have precomputed the relative transformations encoding the
- relative pose and the intrinsics between the reference and a non
- reference camera.
- """
- # TODO: add type and value checkings
- if self._i_Hs_ref is None:
- raise ValueError("Please, call compute_homographies.")
-
- if len(inv_depth_ref.shape) != 4:
- raise ValueError("Input inv_depth_ref has to be in the shape of"
- "Bx1xHxW. Got {}".format(inv_depth_ref.shape))
-
- # NOTE: exclude this by now. We will figure out later if we want to
- # support this feature again.
- '''if roi is None:
- roi = (0, int(self.height), 0, int(self.width))
- start_row, end_row, start_col, end_col = roi
- assert start_row < end_row
- assert start_col < end_col
- height, width = end_row - start_row, end_col - start_col
- area = width * height
-
- # take sub region
- inv_depth_ref = inv_depth_ref[..., start_row:end_row,
- start_col:end_col].contiguous()'''
-
- batch_size, _, height, width = inv_depth_ref.shape
- device: torch.device = inv_depth_ref.device
- dtype: torch.dtype = inv_depth_ref.dtype
-
- # expand the base according to the number of the input batch size
- # and concatenate it with the inverse depth [x, y, inv_depth]'
- import pdb
- pdb.set_trace()
- grid: torch.Tensor = self.grid.to(device).to(dtype).expand(
- batch_size, -1, -1, -1)
- grid = torch.cat([grid, inv_depth_ref.permute(0, 2, 3, 1)], dim=-1)
- grid = grid.view(batch_size, 1, 1, height, width, 3) # Nx1x1xHxWx3
-
- # reshape the transforms to match with the grid shape: Nx1x1x4x4
- i_trans_ref: torch.Tensor = torch.unsqueeze(
- torch.unsqueeze(self._i_Hs_ref, dim=1), dim=1).to(device)
-
- # transform the actual grid
- flow: torch.Tensor = transform_points(i_trans_ref, grid).view(
- batch_size, height, width, 3)
-
- # recover the the coordinates
- z: torch.Tensor = 1. / (flow[..., 2] + self.eps) # NxHxW
- x: torch.Tensor = flow[..., 0] * z
- y: torch.Tensor = flow[..., 1] * z
-
- # in case we are using normalized coordinates in the range of [-1, 1]
- # we have to move the coordinates to the grid center.
- x_norm: torch.Tensor = x
- y_norm: torch.Tensor = y
-
- if self.normalized_coordinates:
- factor_x: float = 2. / (self.width - 1.)
- factor_y: float = 2. / (self.height - 1.)
- x_norm = factor_x * x - 1.
- y_norm = factor_y * y - 1.
-
- # stack and return the values
- return torch.stack([x_norm, y_norm], dim=-1) # NxHxWx2
-
- def 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.
+ depth_src: torch.Tensor,
+ patch_dst: torch.Tensor) -> torch.Tensor:
+ """Warps a tensor from destination frame to reference given the depth
+ in the reference frame.
Args:
- inv_depth_ref (Tensor): The inverse depth in the reference frame.
- patch_i (Tensor): The patch in the it frame.
+ depth_src (torch.Tensor): The depth in the reference frame. The
+ tensor must have a shape :math:`(B, 1, H, W)`.
+ patch_dst (torch.Tensor): The patch in the destination frame. The
+ tensor must have a shape :math:`(B, C, H, W)`.
Return:
- Tensor: The warped data from ith frame to reference.
+ torch.Tensor: The warped patch from destination frame to reference.
Shape:
- - Input: :math:`(N, 1, H, W)` and :math:`(N, C, H, W)`
- - Output: :math:`(N, C, H, W)`
+ - Output: :math:`(N, C, H, W)` where C = number of channels.
Example:
- >>> # image in ith frame
- >>> img_i = torch.rand(1, 3, 32, 32) # NxCxHxW
- >>> # pinholes models for camera i and reference
- >>> pinholes_i = torch.Tensor([1, 12]) # Nx12
- >>> pinhole_ref = torch.Tensor([1, 12]), # Nx12
- >>> # create the depth warper and compute the homographies
- >>> warper = tgm.DepthWarper(pinholes_i)
- >>> warper.compute_homographies(pinhole_ref)
- >>> # 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
+ >>> # pinholes camera models
+ >>> pinhole_dst = tgm.PinholeCamera(...)
+ >>> pinhole_src = tgm.PinholeCamera(...)
+ >>> # create the depth warper, compute the projection matrix
+ >>> warper = tgm.DepthWarper([pinhole_dst, ], height, width)
+ >>> warper.compute_projection_matrix(pinhole_src)
+ >>> # warp the destionation frame to reference by depth
+ >>> depth_src = torch.ones(1, 1, 32, 32) # Nx1xHxW
+ >>> image_dst = torch.rand(1, 3, 32, 32) # NxCxHxW
+ >>> image_src = warper(depth_src, image_dst) # NxCxHxW
"""
- # TODO: add type and value checkings
- return torch.nn.functional.grid_sample(
- patch_i, self.warp_grid(inv_depth_ref))
+ return F.grid_sample(patch_dst, self.warp_grid(depth_src))
# functional api
-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]`.
- inv_depth_ref (Tensor): The inverse depth in the reference frame.
- patch_i (Tensor): The patch data in the ith frame.
+def depth_warp(pinholes_dst: Iterable[PinholeCamera],
+ pinhole_src: PinholeCamera,
+ depth_src: torch.Tensor,
+ patch_dst: torch.Tensor,
+ height: int, width: int):
+ r"""Function that warps a tensor from destination frame to reference
+ given the depth in the reference frame.
- Return:
- Tensor: The warped data from ith frame to reference.
+ See :class:`~torchgeometry.DepthWarper` for details.
Example:
- >>> # image in ith frame
- >>> img_i = torch.rand(1, 3, 32, 32) # NxCxHxW
- >>> # pinholes models for camera i and reference
- >>> pinholes_i = torch.Tensor([1, 12]) # Nx12
- >>> 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
+ >>> # pinholes camera models
+ >>> pinhole_dst = tgm.PinholeCamera(...)
+ >>> pinhole_src = tgm.PinholeCamera(...)
+ >>> # warp the destionation frame to reference by depth
+ >>> depth_src = torch.ones(1, 1, 32, 32) # Nx1xHxW
+ >>> image_dst = torch.rand(1, 3, 32, 32) # NxCxHxW
+ >>> image_src = tgm.depth_warp([pinhole_dst, ], pinhole_src,
+ >>> depth_src, image_dst, height, width) # NxCxHxW
"""
- warper = DepthWarper(pinholes_i, width=width, height=height)
- warper.compute_homographies(pinhole_ref)
- return warper(inv_depth_ref, patch_i)
+ warper = DepthWarper(pinholes_dst, height, width)
+ warper.compute_projection_matrix(pinhole_src)
+ return warper(depth_src, patch_dst)
diff --git a/torchgeometry/core/pinhole.py b/torchgeometry/core/pinhole.py
index 24b4a6fd3..82fab305e 100644
--- a/torchgeometry/core/pinhole.py
+++ b/torchgeometry/core/pinhole.py
@@ -155,6 +155,14 @@ class PinholeCamera:
"""
return self.extrinsics[..., 0, -1]
+ @tx.setter
+ def tx(self, value) -> 'PinholeCamera':
+ r"""Set the x-coordinate of the translation vector with the given
+ value.
+ """
+ self.extrinsics[..., 0, -1] = value
+ return self
+
@property
def ty(self) -> torch.Tensor:
r"""Returns the y-coordinate of the translation vector.
@@ -164,6 +172,14 @@ class PinholeCamera:
"""
return self.extrinsics[..., 1, -1]
+ @ty.setter
+ def ty(self, value) -> 'PinholeCamera':
+ r"""Set the y-coordinate of the translation vector with the given
+ value.
+ """
+ self.extrinsics[..., 1, -1] = value
+ return self
+
@property
def tz(self) -> torch.Tensor:
r"""Returns the z-coordinate of the translation vector.
@@ -173,6 +189,14 @@ class PinholeCamera:
"""
return self.extrinsics[..., 2, -1]
+ @tz.setter
+ def tz(self, value) -> 'PinholeCamera':
+ r"""Set the y-coordinate of the translation vector with the given
+ value.
+ """
+ self.extrinsics[..., 2, -1] = value
+ return self
+
@property
def rt_matrix(self) -> torch.Tensor:
r"""Returns the 3x4 rotation-translation matrix.
@@ -270,9 +294,20 @@ class PinholeCamera:
# NOTE: just for test. Decide if we keep it.
@classmethod
- def from_parameters(self, fx, fy, cx, cy, height, width, tx, ty, tz):
+ def from_parameters(
+ self,
+ fx,
+ fy,
+ cx,
+ cy,
+ height,
+ width,
+ tx,
+ ty,
+ tz,
+ batch_size=1):
# create the camera matrix
- intrinsics = torch.zeros(1, 4, 4)
+ intrinsics = torch.zeros(batch_size, 4, 4)
intrinsics[..., 0, 0] += fx
intrinsics[..., 1, 1] += fy
intrinsics[..., 0, 2] += cx
@@ -280,14 +315,14 @@ class PinholeCamera:
intrinsics[..., 2, 2] += 1.0
intrinsics[..., 3, 3] += 1.0
# create the pose matrix
- extrinsics = torch.eye(4)[None]
+ extrinsics = torch.eye(4).repeat(batch_size, 1, 1)
extrinsics[..., 0, -1] += tx
extrinsics[..., 1, -1] += ty
extrinsics[..., 2, -1] += tz
# create image hegith and width
- height_tmp = torch.zeros(1)
+ height_tmp = torch.zeros(batch_size)
height_tmp[..., 0] += height
- width_tmp = torch.zeros(1)
+ width_tmp = torch.zeros(batch_size)
width_tmp[..., 0] += width
return self(intrinsics, extrinsics, height_tmp, width_tmp)
diff --git a/torchgeometry/core/transformations.py b/torchgeometry/core/transformations.py
index 0b0b05d25..887b89414 100644
--- a/torchgeometry/core/transformations.py
+++ b/torchgeometry/core/transformations.py
@@ -95,9 +95,6 @@ def relative_pose(pose_1: torch.Tensor, pose_2: torch.Tensor,
if not (len(pose_1.shape) == 3 and pose_1.shape[-2:] == (4, 4)):
raise ValueError("Input must be a of the shape Nx4x4."
" Got {}".format(pose_1.shape, pose_2.shape))
- if not pose_1.shape == pose_2.shape:
- raise ValueError("Input pose_1 and pose_2 must be a of the same shape."
- " Got {}".format(pose_1.shape, pose_2.shape))
# unpack input data
r_mat_1 = pose_1[..., :3, :3] # Nx3x3
r_mat_2 = pose_2[..., :3, :3] # Nx3x3
@@ -110,7 +107,9 @@ def relative_pose(pose_1: torch.Tensor, pose_2: torch.Tensor,
t_vec_21 = torch.matmul(r_mat_1_trans, t_vec_2 - t_vec_1)
# pack output data
- pose_21 = torch.zeros_like(pose_1)
+ batch_size = r_mat_21.shape[0]
+ pose_21 = torch.zeros(batch_size, 4, 4,
+ device=r_mat_21.device, dtype=r_mat_21.dtype)
pose_21[..., :3, :3] = r_mat_21
pose_21[..., :3, -1:] = t_vec_21
pose_21[..., -1, -1] += 1.0