Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

add pinhole model docs

edgarribacfe665f15085
diff --git a/docs/source/data/pinhole_model.png b/docs/source/data/pinhole_model.png
new file mode 100644
index 000000000..45350574c
Binary files /dev/null and b/docs/source/data/pinhole_model.png differ
diff --git a/docs/source/pinhole.rst b/docs/source/pinhole.rst
index 0dbc7f222..4761c222f 100644
--- a/docs/source/pinhole.rst
+++ b/docs/source/pinhole.rst
@@ -1,8 +1,55 @@
-Pinhole
---------
+Pinhole Camera
+--------------
.. currentmodule:: torchgeometry
+In this module we have all the functions and data structures used to describe the projection of a 3D scene space onto a 2D image plane.
+
+In computer vision, we can map between the 3D world and a 2D image using *projective geometry*. The module refers to the simplest camera model, the **Pinhole Camera**, which is the most basic model for general projective cameras located into the finite cameras group.
+
+The Pinhole Camera model is shown in the figure below:
+
+.. image:: data/pinhole_model.png
+
+In this model, a scene view is formed by projecting 3D points into the image plane using a perspective transformation.
+
+.. math::
+ s \; m' = K [R|t] M'
+
+or
+
+.. math::
+ s \begin{bmatrix} u \\ v \\ 1\end{bmatrix} =
+ \begin{bmatrix}
+ f_x & 0 & u_0 \\
+ 0 & f_y & v_0 \\
+ 0 & 0 & 1
+ \end{bmatrix}
+ \begin{bmatrix}
+ r_{11} & r_{12} & r_{13} & t_1 \\
+ r_{21} & r_{22} & r_{23} & t_2 \\
+ r_{31} & r_{32} & r_{33} & t_3
+ \end{bmatrix}
+ \begin{bmatrix}
+ X \\
+ Y \\
+ Z \\
+ 1
+ \end{bmatrix}
+
+where:
+ * :math:`M'` is a 3D point in space with coordinates :math:`[X,Y,Z]^T` expressed in a Euclidean coordinate system.
+ * :math:`m'` is the projection of the 3D point :math:`M'` into the *image plane* with coordinates :math:`[u,v]^T` expressed in pixel units.
+ * :math:`K` is the *camera calibration matrix*, also refered as the instrinsics parameters matrix.
+ * :math:`C` is the *principal point offset* with coordinates :math:`[u_0, v_0]^T` at the origin in the image plane.
+ * :math:`fx, fy` are the focal lengths expressed in pixel units.
+
+The camera rotation and translation are expressed in terms of Euclidean coordinate frame, known as the *world coordinates system*. This terms are usually expressed by the joint rotation-translation matrix :math:`[R|t]`, or also called as the extrinsics parameters matrix. It is used to describe the camera pose around a static scene and translates the coordinates of a 3D point :math:`(X,Y,Z)` to a coordinate sytstem respect to the camera.
+
+.. autoclass:: PinholeCamera
+ :members:
+.. autoclass:: PinholeCamerasList
+
.. note::
The pinhole model is represented in a single vector as follows:
diff --git a/mypy_files.txt b/mypy_files.txt
index bcde574dc..c194743bb 100644
--- a/mypy_files.txt
+++ b/mypy_files.txt
@@ -1,4 +1,6 @@
torchgeometry/core/homography_warper.py
+torchgeometry/core/depth_warper.py
+torchgeometry/core/pinhole.py
torchgeometry/image/gaussian.py
torchgeometry/losses/ssim.py
torchgeometry/losses/dice.py
diff --git a/test/test_pinhole.py b/test/test_pinhole.py
index 72402db72..3b34a47b7 100644
--- a/test/test_pinhole.py
+++ b/test/test_pinhole.py
@@ -25,18 +25,25 @@ class TestPinholeCamera:
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)
+ intrinsics = torch.eye(4)[None]
+ extrinsics = torch.eye(4)[None]
+ height = torch.ones(1)
+ width = torch.ones(1)
+ pinhole = tgm.PinholeCamera(intrinsics, extrinsics, height, width)
assert isinstance(pinhole, tgm.PinholeCamera)
def test_pinhole_camera_attributes(self):
batch_size = 1
- fx, fy, cx, cy = 1, 2, 3, 4
+ height, width = 4, 6
+ fx, fy, cx, cy = 1, 2, width / 2, height / 2
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)
+ height = torch.ones(batch_size) * height
+ width = torch.ones(batch_size) * width
+
+ pinhole = tgm.PinholeCamera(intrinsics, extrinsics, height, width)
assert pinhole.batch_size == batch_size
assert pinhole.fx.item() == fx
@@ -46,6 +53,36 @@ class TestPinholeCamera:
assert pinhole.tx.item() == tx
assert pinhole.ty.item() == ty
assert pinhole.tz.item() == tz
+ assert pinhole.height.item() == height
+ assert pinhole.width.item() == width
+ 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_attributes_batch2(self):
+ batch_size = 2
+ height, width = 4, 6
+ fx, fy, cx, cy = 1, 2, width / 2, height / 2
+ 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)
+ height = torch.ones(batch_size) * height
+ width = torch.ones(batch_size) * width
+
+ pinhole = tgm.PinholeCamera(intrinsics, extrinsics, height, width)
+
+ assert pinhole.batch_size == batch_size
+ assert pinhole.fx.shape[0] == batch_size
+ assert pinhole.fy.shape[0] == batch_size
+ assert pinhole.cx.shape[0] == batch_size
+ assert pinhole.cy.shape[0] == batch_size
+ assert pinhole.tx.shape[0] == batch_size
+ assert pinhole.ty.shape[0] == batch_size
+ assert pinhole.tz.shape[0] == batch_size
+ assert pinhole.height.shape[0] == batch_size
+ assert pinhole.width.shape[0] == batch_size
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)
@@ -53,12 +90,16 @@ class TestPinholeCamera:
def test_pinhole_camera_list_attributes(self):
batch_size = 1
- fx, fy, cx, cy = 1, 2, 3, 4
+ height, width = 4, 6
+ fx, fy, cx, cy = 1, 2, width / 2, height / 2
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)
+ height = torch.ones(batch_size) * height
+ width = torch.ones(batch_size) * width
- pinhole_1 = tgm.PinholeCamera(intrinsics, extrinsics)
+ pinhole_1 = tgm.PinholeCamera(intrinsics, extrinsics, height, width)
pinhole_2 = pinhole_1.clone()
pinholes_list = [pinhole_1, pinhole_2]
pinholes = tgm.PinholeCamerasList(pinholes_list)
diff --git a/torchgeometry/core/depth_warper.py b/torchgeometry/core/depth_warper.py
index 468b9146c..596793d5d 100644
--- a/torchgeometry/core/depth_warper.py
+++ b/torchgeometry/core/depth_warper.py
@@ -134,7 +134,8 @@ class DepthWarper(nn.Module):
I_{ref} = \\omega(I_{i}, H_{ref}^{i}, \\xi_{ref})
Args:
- pinholes (torch.Tensor): The pinhole models for ith frame with shape `[Nx12]`.
+ 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.
@@ -171,14 +172,7 @@ class DepthWarper(nn.Module):
height, width, normalized_coordinates=False) # 1xHxWx2
return convert_points_to_homogeneous(grid) # append ones to last dim
- # TODO(edgar): refactor this and potentially and potentially accept the
- # pinholes models as Nx2x4x4, where first will be the pinhole_matrix in the
- # 4x4 shape, and second the Rt matrix in the 4x4 shape. For this, we need
- # to update inverse_pinhole, scale_pinhole, etc. But seems the more generic
- # thing to do. Additionally, I wouldn't force the output shape(self.height/width)
- # to be the pinhole camera content. Instead I would stick to the values from
- # the class signature which I would force to the user to introduce (now is
- # optional and could be None).
+ # TODO(edgar): remove
def compute_homographies(self, pinhole, scale=None):
if scale is None:
batch_size = pinhole.shape[0]
@@ -217,7 +211,6 @@ class DepthWarper(nn.Module):
def _compute_projection(self, x, y, invd):
point = torch.FloatTensor([[[x], [y], [1.0], [invd]]])
- #flow = torch.matmul(self._i_Hs_ref, point.to(self._i_Hs_ref.device))
flow = torch.matmul(
self._dst_proj_src, point.to(self._dst_proj_src.device))
z = 1. / flow[:, 2]
diff --git a/torchgeometry/core/pinhole.py b/torchgeometry/core/pinhole.py
index 2e22026e0..8ce6d5a00 100644
--- a/torchgeometry/core/pinhole.py
+++ b/torchgeometry/core/pinhole.py
@@ -22,96 +22,206 @@ __all__ = [
class PinholeCamera:
- r"""Class that represents a Pinhole Camera model."""
+ r"""Class that represents a Pinhole Camera model.
+
+ Args:
+ intrinsics (torch.Tensor): tensor with shape :math:`(B, 4, 4)`
+ containing the full 4x4 camera calibration matrix.
+ extrinsics (torch.Tensor): tensor with shape :math:`(B, 4, 4)`
+ containing the full 4x4 rotation-translation matrix.
+ height (torch.Tensor): tensor with shape :math:`(B)` containing the
+ image height.
+ widht (torch.Tensor): tensor with shape :math:`(B)` containing the image
+ width.
+
+ .. note::
+ We assume that class attributes are batched in order to take advantage
+ of PyTorch parallelism.
+ """
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))
+ extrinsics: torch.Tensor,
+ height: torch.Tensor,
+ width: torch.Tensor) -> None:
+ # verify batch size and shapes
+ self._check_valid([intrinsics, extrinsics, height, width])
+ self._check_valid_params(intrinsics, "intrinsics")
+ self._check_valid_params(extrinsics, "extrinsics")
+ self._check_valid_shape(height, "height")
+ self._check_valid_shape(width, "width")
# 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,
+ self.height: torch.Tensor = height
+ self.width: torch.Tensor = width
+ self._intrinsics: torch.Tensor = intrinsics
+ self._extrinsics: torch.Tensor = extrinsics
+
+ @staticmethod
+ def _check_valid(data_iter: Iterable[torch.Tensor]) -> bool:
+ if not all(data.shape[0] for data in data_iter):
+ raise ValueError("Arguments shapes must match")
+ return True
+
+ @staticmethod
+ def _check_valid_params(
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
+ return True
+
+ @staticmethod
+ def _check_valid_shape(
+ data: torch.Tensor,
+ data_name: str) -> torch.Tensor:
+ if not len(data.shape) == 1:
+ raise ValueError("Argument {0} shape must be in the following shape"
+ " B. Got {1}".format(data_name, data.shape))
+ return True
+
+ @property
+ def intrinsics(self) -> torch.Tensor:
+ r"""The full 4x4 intrinsics matrix.
+
+ Returns:
+ torch.Tensor: tensor of shape :math:`(B, 4, 4)`
+ """
+ assert self._check_valid_params(self._intrinsics, "intrinsics")
+ return self._intrinsics
+
+ @property
+ def extrinsics(self) -> torch.Tensor:
+ r"""The full 4x4 extrinsics matrix.
+
+ Returns:
+ torch.Tensor: tensor of shape :math:`(B, 4, 4)`
+ """
+ assert self._check_valid_params(self._extrinsics, "extrinsics")
+ return self._extrinsics
@property
def batch_size(self) -> int:
- self._check_valid_data(self.intrinsics, "intrinsics")
+ r"""Returns the batch size of the storage.
+
+ Returns:
+ int: batch size value
+ """
return self.intrinsics.shape[0]
@property
def fx(self) -> torch.Tensor:
- self._check_valid_data(self.intrinsics, "intrinsics")
+ r"""Returns the focal lenght in the x-direction.
+
+ Returns:
+ torch.Tensor: tensor of shape :math:`(B)`
+ """
return self.intrinsics[..., 0, 0]
@property
def fy(self) -> torch.Tensor:
- self._check_valid_data(self.intrinsics, "intrinsics")
+ r"""Returns the focal lenght in the y-direction.
+
+ Returns:
+ torch.Tensor: tensor of shape :math:`(B)`
+ """
return self.intrinsics[..., 1, 1]
@property
def cx(self) -> torch.Tensor:
- self._check_valid_data(self.intrinsics, "intrinsics")
+ r"""Returns the x-coordinate of the principal point.
+
+ Returns:
+ torch.Tensor: tensor of shape :math:`(B)`
+ """
return self.intrinsics[..., 0, 2]
@property
def cy(self) -> torch.Tensor:
- self._check_valid_data(self.intrinsics, "intrinsics")
+ r"""Returns the y-coordinate of the principal point.
+
+ Returns:
+ torch.Tensor: tensor of shape :math:`(B)`
+ """
return self.intrinsics[..., 1, 2]
@property
def tx(self) -> torch.Tensor:
- self._check_valid_data(self.extrinsics, "extrinsics")
+ r"""Returns the x-coordinate of the translation vector.
+
+ Returns:
+ torch.Tensor: tensor of shape :math:`(B)`
+ """
return self.extrinsics[..., 0, -1]
@property
def ty(self) -> torch.Tensor:
- self._check_valid_data(self.extrinsics, "extrinsics")
+ r"""Returns the y-coordinate of the translation vector.
+
+ Returns:
+ torch.Tensor: tensor of shape :math:`(B)`
+ """
return self.extrinsics[..., 1, -1]
@property
def tz(self) -> torch.Tensor:
- self._check_valid_data(self.extrinsics, "extrinsics")
+ r"""Returns the z-coordinate of the translation vector.
+
+ Returns:
+ torch.Tensor: tensor of shape :math:`(B)`
+ """
return self.extrinsics[..., 2, -1]
@property
def rt_matrix(self) -> torch.Tensor:
- self._check_valid_data(self.extrinsics, "extrinsics")
+ r"""Returns the 3x4 rotation-translation matrix.
+
+ Returns:
+ torch.Tensor: tensor of shape :math:`(B, 3, 4)`
+ """
return self.extrinsics[..., :3, :4]
@property
def camera_matrix(self) -> torch.Tensor:
- self._check_valid_data(self.intrinsics, "intrinsics")
+ r"""Returns the 3x3 camera matrix containing the intrinsics.
+
+ Returns:
+ torch.Tensor: tensor of shape :math:`(B, 3, 3)`
+ """
return self.intrinsics[..., :3, :3]
@property
def rotation_matrix(self) -> torch.Tensor:
- self._check_valid_data(self.extrinsics, "extrinsics")
+ r"""Returns the 3x3 rotation matrix from the extrinsics.
+
+ Returns:
+ torch.Tensor: tensor of shape :math:`(B, 3, 3)`
+ """
return self.extrinsics[..., :3, :3]
@property
def translation_vector(self) -> torch.Tensor:
- self._check_valid_data(self.extrinsics, "extrinsics")
+ r"""Returns the translation vector from the extrinsics.
+
+ Returns:
+ torch.Tensor: tensor of shape :math:`(B, 3, 1)`
+ """
return self.extrinsics[..., :3, -1:]
def clone(self) -> 'PinholeCamera':
- intrinsics = self.intrinsics.clone()
- extrinsics = self.extrinsics.clone()
- return PinholeCamera(intrinsics, extrinsics)
+ r"""Returns a deep copy of the current object instance."""
+ height: torch.Tensor = self.height
+ width: torch.Tensor = self.width
+ intrinsics: torch.Tensor = self.intrinsics.clone()
+ extrinsics: torch.Tensor = self.extrinsics.clone()
+ return PinholeCamera(intrinsics, extrinsics, height, width)
def intrinsics_inverse(self) -> torch.Tensor:
- self._check_valid_data(self.intrinsics, "intrinsics")
+ r"""Returns the inverse of the 4x4 instrisics matrix.
+
+ Returns:
+ torch.Tensor: tensor of shape :math:`(B, 4, 4)`
+ """
return self.intrinsics.inverse()
# NOTE: just for test. Decide if we keep it.
@@ -130,11 +240,30 @@ class PinholeCamera:
extrinsics[..., 0, -1] += tx
extrinsics[..., 1, -1] += ty
extrinsics[..., 2, -1] += tz
- return self(intrinsics, extrinsics)
+ # create image hegith and width
+ height_tmp = torch.zeros(1)
+ height_tmp[..., 0] += height
+ width_tmp = torch.zeros(1)
+ width_tmp[..., 0] += width
+ return self(intrinsics, extrinsics, height_tmp, width_tmp)
class PinholeCamerasList(PinholeCamera):
- r"""Class that represents a list of pinhole cameras."""
+ r"""Class that represents a list of pinhole cameras.
+
+ The class inherits from :class:`~torchgeometry.PinholeCamera` meaning that
+ it will keep the same class properties but with an extra dimension.
+
+ .. note::
+ The underlying data tensor will be stacked in the first dimension.
+ That's it, given a list of two camera instances, the intrinsics tensor
+ will have a shape :math:`(B, N, 4, 4)` where :math:`B` is the batch
+ size and :math:`N` is the numbers of cameras (in this case two).
+
+ Args:
+ pinholes_list (Iterable[PinholeCamera]): a python tuple or list
+ containg a set of `PinholeCamera` instances.
+ """
def __init__(self, pinholes_list: Iterable[PinholeCamera]) -> None:
self._initialize_parameters(pinholes_list)
@@ -142,7 +271,7 @@ class PinholeCamerasList(PinholeCamera):
def _initialize_parameters(
self,
pinholes: Iterable[PinholeCamera]) -> 'PinholeCamerasList':
- r"""Initialises the class attributes by iterating over the input list."""
+ r"""Initialises the class attributes given a cameras list."""
if not isinstance(pinholes, (list, tuple,)):
raise TypeError("pinhole must of type list or tuple. Got {}"
.format(type(pinholes)))
@@ -154,8 +283,8 @@ class PinholeCamerasList(PinholeCamera):
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)
+ self._intrinsics: torch.Tensor = torch.stack(intrinsics, dim=1)
+ self._extrinsics: torch.Tensor = torch.stack(extrinsics, dim=1)
return self
@property
@@ -168,9 +297,11 @@ class PinholeCamerasList(PinholeCamera):
def get_pinhole(self, idx: int) -> PinholeCamera:
r"""Returns a PinholeCamera object with parameters such as Bx4x4."""
+ height: torch.Tensor = self.height[..., idx]
+ width: torch.Tensor = self.width[..., idx]
intrinsics: torch.Tensor = self.intrinsics[:, idx]
extrinsics: torch.Tensor = self.extrinsics[:, idx]
- return PinholeCamera(intrinsics, extrinsics)
+ return PinholeCamera(intrinsics, extrinsics, height, width)
def pinhole_matrix(pinholes, eps=1e-6):