Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

move PinholeCamera and PinholeCamerasList to pinhole.py and add tests

edgarribab73aff292ae4
diff --git a/test/test_depth_warper.py b/test/test_depth_warper.py
index c4ae95bde..2ba84a99d 100644
--- a/test/test_depth_warper.py
+++ b/test/test_depth_warper.py
@@ -5,7 +5,6 @@ import torchgeometry as tgm
from torch.autograd import gradcheck
import utils # test utils
-from torchgeometry.core.depth_warper import PinholeCamera
from torchgeometry.core.depth_warper import normalize_pixel_coordinates
@@ -20,9 +19,9 @@ class TestDepthWarper:
tx, ty, tz = 0, 0, 0
# create pinhole cameras
- pinhole_src = PinholeCamera.from_parameters(
+ pinhole_src = tgm.PinholeCamera.from_parameters(
fx, fy, cx, cy, height, width, tx, ty, tz)
- pinhole_dst = PinholeCamera.from_parameters(
+ pinhole_dst = tgm.PinholeCamera.from_parameters(
fx, fy, cx, cy, height, width, tx + 1., ty, tz)
# create warper
@@ -49,9 +48,9 @@ class TestDepthWarper:
tx, ty, tz = 0, 0, 0
# create pinhole cameras
- pinhole_src = PinholeCamera.from_parameters(
+ pinhole_src = tgm.PinholeCamera.from_parameters(
fx, fy, cx, cy, height, width, tx, ty, tz)
- pinhole_dst = PinholeCamera.from_parameters(
+ pinhole_dst = tgm.PinholeCamera.from_parameters(
fx, fy, cx, cy, height, width, tx + 1., ty, tz)
# initialize depth to one
@@ -81,9 +80,9 @@ class TestDepthWarper:
tx, ty, tz = 0, 0, 0
# create pinhole cameras
- pinhole_src = PinholeCamera.from_parameters(
+ pinhole_src = tgm.PinholeCamera.from_parameters(
fx, fy, cx, cy, height, width, tx, ty, tz)
- pinhole_dst = PinholeCamera.from_parameters(
+ pinhole_dst = tgm.PinholeCamera.from_parameters(
fx, fy, cx, cy, height, width, tx + 1., ty + 1., tz)
# initialize depth to one
@@ -105,6 +104,40 @@ 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()
+
+ # 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.compute_projection_matrix(pinhole_src)
+ grid_warped = warper.warp_grid(depth_src)
+
+ # normalize base meshgrid
+ grid = warper.grid[..., :2]
+ grid_norm = normalize_pixel_coordinates(grid, height, width)
+
+ # check offset in x-axis
+ assert utils.check_equal_torch(
+ grid_norm[..., -1, 0], grid_warped[..., -2, 0])
+ # check that y-axis remain the same
+ assert utils.check_equal_torch(
+ grid_norm[..., -1, :, 1], grid_warped[..., -2, :, 1])
+
def _test_depth_warper_offset_tensor(self):
# prepare data
batch_size, channels, height, width = 1, 3, 3, 5
@@ -113,9 +146,9 @@ class TestDepthWarper:
tx, ty, tz = 0, 0, 0
# create pinhole cameras
- pinhole_src = PinholeCamera.from_parameters(
+ pinhole_src = tgm.PinholeCamera.from_parameters(
fx, fy, cx, cy, height, width, tx, ty, tz)
- pinhole_dst = PinholeCamera.from_parameters(
+ pinhole_dst = tgm.PinholeCamera.from_parameters(
fx, fy, cx, cy, height, width, tx + 1., ty + 1., tz)
# initialize depth to one
@@ -150,4 +183,5 @@ class TestDepthWarper:
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()
diff --git a/test/test_pinhole.py b/test/test_pinhole.py
index 2d9211466..72402db72 100644
--- a/test/test_pinhole.py
+++ b/test/test_pinhole.py
@@ -8,6 +8,75 @@ import utils # test utilities
from common import TEST_DEVICES
+class TestPinholeCamera:
+ def _create_intrinsics(self, batch_size, fx, fy, cx, cy):
+ intrinsics = torch.eye(4).expand(batch_size, -1, -1)
+ intrinsics[..., 0, 0] = fx
+ intrinsics[..., 1, 1] = fy
+ intrinsics[..., 0, 2] = cx
+ intrinsics[..., 1, 2] = cy
+ return intrinsics
+
+ def _create_extrinsics(self, batch_size, tx, ty, tz):
+ extrinsics = torch.eye(4).expand(batch_size, -1, -1)
+ extrinsics[..., 0, -1] = tx
+ extrinsics[..., 1, -1] = ty
+ extrinsics[..., 2, -1] = tz
+ return extrinsics
+
+ def test_smoke(self):
+ dummy_intrinsics = torch.eye(4)[None]
+ dummy_extrinsics = torch.eye(4)[None]
+ pinhole = tgm.PinholeCamera(dummy_intrinsics, dummy_extrinsics)
+ assert isinstance(pinhole, tgm.PinholeCamera)
+
+ def test_pinhole_camera_attributes(self):
+ batch_size = 1
+ fx, fy, cx, cy = 1, 2, 3, 4
+ tx, ty, tz = 1, 2, 3
+ intrinsics = self._create_intrinsics(batch_size, fx, fy, cx, cy)
+ extrinsics = self._create_extrinsics(batch_size, tx, ty, tz)
+ pinhole = tgm.PinholeCamera(intrinsics, extrinsics)
+
+ assert pinhole.batch_size == batch_size
+ assert pinhole.fx.item() == fx
+ assert pinhole.fy.item() == fy
+ assert pinhole.cx.item() == cx
+ assert pinhole.cy.item() == cy
+ assert pinhole.tx.item() == tx
+ assert pinhole.ty.item() == ty
+ assert pinhole.tz.item() == tz
+ assert pinhole.rt_matrix.shape == (batch_size, 3, 4)
+ assert pinhole.camera_matrix.shape == (batch_size, 3, 3)
+ assert pinhole.rotation_matrix.shape == (batch_size, 3, 3)
+ assert pinhole.translation_vector.shape == (batch_size, 3, 1)
+
+ def test_pinhole_camera_list_attributes(self):
+ batch_size = 1
+ fx, fy, cx, cy = 1, 2, 3, 4
+ tx, ty, tz = 1, 2, 3
+ intrinsics = self._create_intrinsics(batch_size, fx, fy, cx, cy)
+ extrinsics = self._create_extrinsics(batch_size, tx, ty, tz)
+
+ pinhole_1 = tgm.PinholeCamera(intrinsics, extrinsics)
+ pinhole_2 = pinhole_1.clone()
+ pinholes_list = [pinhole_1, pinhole_2]
+ pinholes = tgm.PinholeCamerasList(pinholes_list)
+
+ assert pinholes.batch_size == batch_size
+ assert torch.allclose(pinholes.fx, torch.ones(1, 2) * fx)
+ assert torch.allclose(pinholes.fy, torch.ones(1, 2) * fy)
+ assert torch.allclose(pinholes.cx, torch.ones(1, 2) * cx)
+ assert torch.allclose(pinholes.cy, torch.ones(1, 2) * cy)
+ assert torch.allclose(pinholes.tx, torch.ones(1, 2) * tx)
+ assert torch.allclose(pinholes.ty, torch.ones(1, 2) * ty)
+ assert torch.allclose(pinholes.tz, torch.ones(1, 2) * tz)
+ assert pinholes.rt_matrix.shape == (batch_size, 2, 3, 4)
+ assert pinholes.camera_matrix.shape == (batch_size, 2, 3, 3)
+ assert pinholes.rotation_matrix.shape == (batch_size, 2, 3, 3)
+ assert pinholes.translation_vector.shape == (batch_size, 2, 3, 1)
+
+
@pytest.mark.parametrize("device_type", TEST_DEVICES)
@pytest.mark.parametrize("batch_size", [1, 2, 5, 6])
def test_scale_pinhole(batch_size, device_type):
diff --git a/torchgeometry/core/depth_warper.py b/torchgeometry/core/depth_warper.py
index 32c1d2294..468b9146c 100644
--- a/torchgeometry/core/depth_warper.py
+++ b/torchgeometry/core/depth_warper.py
@@ -9,6 +9,7 @@ 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
@@ -76,10 +77,10 @@ def pixel2cam(depth: torch.Tensor, intrinsics_inv: torch.Tensor,
"Bx1xHxW. Got {}".format(depth.shape))
if not len(intrinsics_inv.shape) == 3:
raise ValueError("Input intrinsics_inv has to be in the shape of "
- "Bx4x4. Got {}".format(intrincsics_inv.shape))
+ "Bx4x4. Got {}".format(intrinsics_inv.shape))
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(intrincsics_inv.shape))
+ "BxHxWx3. Got {}".format(intrinsics_inv.shape))
cam_coords: torch.Tensor = transform_points(intrinsics_inv, pixel_coords)
return cam_coords * depth.permute(0, 2, 3, 1)
@@ -104,7 +105,7 @@ def cam2pixel(
"""
if not len(cam_coords_src.shape) == 4 and cam_coords_src.shape[3] == 3:
raise ValueError("Input cam_coords_src has to be in the shape of "
- "BxHxWx3. Got {}".format(depth.shape))
+ "BxHxWx3. Got {}".format(cam_coords_src.shape))
if not len(dst_proj_src.shape) == 3 and dst_proj_src.shape[-2:] == (4, 4):
raise ValueError("Input dst_proj_src has to be in the shape of "
"Bx4x4. Got {}".format(dst_proj_src.shape))
@@ -124,34 +125,6 @@ def cam2pixel(
return pixel_coords_dst # BxHxWx2
-class PinholeCamera:
- # TODO: add more documentation
- def __init__(self, intrinsics, extrinsics):
- self.intrinsics = intrinsics
- self.extrinsics = extrinsics
-
- def intrinsics_inverse(self):
- return self.intrinsics.inverse()
-
- # NOTE: just for test. Decide if we keep it.
- @classmethod
- def from_parameters(self, fx, fy, cx, cy, height, width, tx, ty, tz):
- # create the camera matrix
- intrinsics = torch.zeros(1, 4, 4)
- intrinsics[..., 0, 0] += fx
- intrinsics[..., 1, 1] += fy
- intrinsics[..., 0, 2] += cx
- intrinsics[..., 1, 2] += cy
- intrinsics[..., 2, 2] += 1.0
- intrinsics[..., 3, 3] += 1.0
- # create the pose matrix
- extrinsics = torch.eye(4)[None]
- extrinsics[..., 0, -1] += tx
- extrinsics[..., 1, -1] += ty
- extrinsics[..., 2, -1] += tz
- return self(intrinsics, extrinsics)
-
-
class DepthWarper(nn.Module):
"""Warps a patch by inverse depth.
@@ -286,7 +259,7 @@ class DepthWarper(nn.Module):
if len(depth_src.shape) != 4:
raise ValueError("Input depth_src has to be in the shape of"
- "Bx1xHxW. Got {}".format(inv_depth_ref.shape))
+ "Bx1xHxW. Got {}".format(depth_src.shape))
# unpack depth attributes
batch_size, _, height, width = depth_src.shape
diff --git a/torchgeometry/core/pinhole.py b/torchgeometry/core/pinhole.py
index 4e2f93022..2e22026e0 100644
--- a/torchgeometry/core/pinhole.py
+++ b/torchgeometry/core/pinhole.py
@@ -1,3 +1,5 @@
+from typing import Iterable
+
import torch
import torch.nn as nn
@@ -6,6 +8,8 @@ from .transformations import inverse_pose
__all__ = [
+ "PinholeCamera",
+ "PinholeCamerasList",
# functional api
"pinhole_matrix",
"inverse_pinhole_matrix",
@@ -17,6 +21,158 @@ __all__ = [
]
+class PinholeCamera:
+ r"""Class that represents a Pinhole Camera model."""
+
+ def __init__(self, intrinsics: torch.Tensor,
+ extrinsics: torch.Tensor) -> None:
+ if not intrinsics.shape == extrinsics.shape:
+ raise ValueError("intrinsics and extrinsics shapes must match. "
+ "{}".format(intrinsics.shape, extrinsics.shape))
+ # set class attributes
+ self.intrinsics: torch.Tensor = self._check_valid_data(intrinsics,
+ "intrinsics")
+ self.extrinsics: torch.Tensor = self._check_valid_data(extrinsics,
+ "extrinsics")
+
+ def _check_valid_data(
+ self,
+ data: torch.Tensor,
+ data_name: str) -> torch.Tensor:
+ if len(data.shape) not in (3, 4,) and data.shape[-2:] is not (4, 4):
+ raise ValueError("Argument {0} shape must be in the following shape"
+ " Bx4x4 or BxNx4x4. Got {1}".format(data_name,
+ data.shape))
+ return data
+
+ @property
+ def batch_size(self) -> int:
+ self._check_valid_data(self.intrinsics, "intrinsics")
+ return self.intrinsics.shape[0]
+
+ @property
+ def fx(self) -> torch.Tensor:
+ self._check_valid_data(self.intrinsics, "intrinsics")
+ return self.intrinsics[..., 0, 0]
+
+ @property
+ def fy(self) -> torch.Tensor:
+ self._check_valid_data(self.intrinsics, "intrinsics")
+ return self.intrinsics[..., 1, 1]
+
+ @property
+ def cx(self) -> torch.Tensor:
+ self._check_valid_data(self.intrinsics, "intrinsics")
+ return self.intrinsics[..., 0, 2]
+
+ @property
+ def cy(self) -> torch.Tensor:
+ self._check_valid_data(self.intrinsics, "intrinsics")
+ return self.intrinsics[..., 1, 2]
+
+ @property
+ def tx(self) -> torch.Tensor:
+ self._check_valid_data(self.extrinsics, "extrinsics")
+ return self.extrinsics[..., 0, -1]
+
+ @property
+ def ty(self) -> torch.Tensor:
+ self._check_valid_data(self.extrinsics, "extrinsics")
+ return self.extrinsics[..., 1, -1]
+
+ @property
+ def tz(self) -> torch.Tensor:
+ self._check_valid_data(self.extrinsics, "extrinsics")
+ return self.extrinsics[..., 2, -1]
+
+ @property
+ def rt_matrix(self) -> torch.Tensor:
+ self._check_valid_data(self.extrinsics, "extrinsics")
+ return self.extrinsics[..., :3, :4]
+
+ @property
+ def camera_matrix(self) -> torch.Tensor:
+ self._check_valid_data(self.intrinsics, "intrinsics")
+ return self.intrinsics[..., :3, :3]
+
+ @property
+ def rotation_matrix(self) -> torch.Tensor:
+ self._check_valid_data(self.extrinsics, "extrinsics")
+ return self.extrinsics[..., :3, :3]
+
+ @property
+ def translation_vector(self) -> torch.Tensor:
+ self._check_valid_data(self.extrinsics, "extrinsics")
+ return self.extrinsics[..., :3, -1:]
+
+ def clone(self) -> 'PinholeCamera':
+ intrinsics = self.intrinsics.clone()
+ extrinsics = self.extrinsics.clone()
+ return PinholeCamera(intrinsics, extrinsics)
+
+ def intrinsics_inverse(self) -> torch.Tensor:
+ self._check_valid_data(self.intrinsics, "intrinsics")
+ return self.intrinsics.inverse()
+
+ # NOTE: just for test. Decide if we keep it.
+ @classmethod
+ def from_parameters(self, fx, fy, cx, cy, height, width, tx, ty, tz):
+ # create the camera matrix
+ intrinsics = torch.zeros(1, 4, 4)
+ intrinsics[..., 0, 0] += fx
+ intrinsics[..., 1, 1] += fy
+ intrinsics[..., 0, 2] += cx
+ intrinsics[..., 1, 2] += cy
+ intrinsics[..., 2, 2] += 1.0
+ intrinsics[..., 3, 3] += 1.0
+ # create the pose matrix
+ extrinsics = torch.eye(4)[None]
+ extrinsics[..., 0, -1] += tx
+ extrinsics[..., 1, -1] += ty
+ extrinsics[..., 2, -1] += tz
+ return self(intrinsics, extrinsics)
+
+
+class PinholeCamerasList(PinholeCamera):
+ r"""Class that represents a list of pinhole cameras."""
+
+ def __init__(self, pinholes_list: Iterable[PinholeCamera]) -> None:
+ self._initialize_parameters(pinholes_list)
+
+ def _initialize_parameters(
+ self,
+ pinholes: Iterable[PinholeCamera]) -> 'PinholeCamerasList':
+ r"""Initialises the class attributes by iterating over the input list."""
+ if not isinstance(pinholes, (list, tuple,)):
+ raise TypeError("pinhole must of type list or tuple. Got {}"
+ .format(type(pinholes)))
+ intrinsics, extrinsics = [], []
+ for pinhole in pinholes:
+ if not isinstance(pinhole, PinholeCamera):
+ raise TypeError("Argument pinhole must be from type "
+ "PinholeCamera. Got {}".format(type(pinhole)))
+ intrinsics.append(pinhole.intrinsics)
+ extrinsics.append(pinhole.extrinsics)
+ # contatenate and set members. We will assume BxNx4x4
+ self.intrinsics: torch.Tensor = torch.stack(intrinsics, dim=1)
+ self.extrinsics: torch.Tensor = torch.stack(extrinsics, dim=1)
+ return self
+
+ @property
+ def num_cameras(self) -> int:
+ r"""Returns the number of pinholes cameras per batch."""
+ num_cameras: int = -1
+ if self.intrinsics is not None:
+ num_cameras = int(self.intrinsics.shape[1])
+ return num_cameras
+
+ def get_pinhole(self, idx: int) -> PinholeCamera:
+ r"""Returns a PinholeCamera object with parameters such as Bx4x4."""
+ intrinsics: torch.Tensor = self.intrinsics[:, idx]
+ extrinsics: torch.Tensor = self.extrinsics[:, idx]
+ return PinholeCamera(intrinsics, extrinsics)
+
+
def pinhole_matrix(pinholes, eps=1e-6):
r"""Function that returns the pinhole matrix from a pinhole model
diff --git a/torchgeometry/losses/dice.py b/torchgeometry/losses/dice.py
index ebac55d1e..b79042a42 100644
--- a/torchgeometry/losses/dice.py
+++ b/torchgeometry/losses/dice.py
@@ -44,6 +44,7 @@ class DiceLoss(nn.Module):
>>> output = loss(input, target)
>>> output.backward()
"""
+
def __init__(self) -> None:
super(DiceLoss, self).__init__()
self.eps: float = 1e-6