Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix small issues in the documentation

edgarribaf12892d74fbd
diff --git a/docs/source/pinhole.rst b/docs/source/pinhole.rst
index 4c6958b77..7a95700cd 100644
--- a/docs/source/pinhole.rst
+++ b/docs/source/pinhole.rst
@@ -3,15 +3,15 @@ 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 this module we have all the functions and data structures needed 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.
+In computer vision, we can map between the 3D world and a 2D image using *projective geometry*. The module implements the simplest camera model, the **Pinhole Camera**, which is the most basic model for general projective cameras from the finite cameras group.
-The Pinhole Camera model is shown in the figure below:
+The Pinhole Camera model is shown in the following figure:
.. 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.
+Using this model, a scene view can be formed by projecting 3D points into the image plane using a perspective transformation.
.. math::
s \; m' = K [R|t] M'
@@ -39,34 +39,26 @@ or
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:`m'` is the projection of the 3D point :math:`M'` onto 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.
+The camera rotation and translation are expressed in terms of Euclidean coordinate frame, also 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:
-
- .. math::
- pinhole = (f_x, f_y, c_x, c_y, height, width, r_x, r_y, r_z, t_x, t_y, t_z)
-
- where:
- :math:`(r_x, r_y, r_z)` is the rotation vector in angle-axis convention.
-
- :math:`(t_x, t_y, t_z)` is the translation vector.
+.. autofunction:: cam2pixel
+.. autofunction:: pixel2cam
+.. autofunction:: normalize_pixel_coordinates
+.. TODO(edgar): deprecate in v0.2
+.. autofunction:: homography_i_H_ref
.. autofunction:: pinhole_matrix
.. autofunction:: inverse_pinhole_matrix
.. autofunction:: scale_pinhole
-.. autofunction:: homography_i_H_ref
-.. autofunction:: cam2pixel
-.. autofunction:: pixel2cam
.. autoclass:: PinholeMatrix
.. autoclass:: InversePinholeMatrix
diff --git a/docs/source/utils.rst b/docs/source/utils.rst
index 0a8de5644..4de93b3fe 100644
--- a/docs/source/utils.rst
+++ b/docs/source/utils.rst
@@ -6,5 +6,3 @@ torchgeometry.utils
.. autofunction:: tensor_to_image
.. autofunction:: image_to_tensor
.. autofunction:: create_meshgrid
-.. autofunction:: normalize_pixel_coordinates
-
diff --git a/test/test_pinhole.py b/test/test_pinhole.py
index 2db637487..3f7934e64 100644
--- a/test/test_pinhole.py
+++ b/test/test_pinhole.py
@@ -95,7 +95,6 @@ class TestPinholeCamera:
assert pinhole.ty.item() == 0.
assert pinhole.tz.item() == 0.
-
def test_pinhole_camera_attributes_batch2(self):
batch_size = 2
height, width = 4, 6
diff --git a/torchgeometry/core/depth_warper.py b/torchgeometry/core/depth_warper.py
index 265b61c02..cb3e67f8a 100644
--- a/torchgeometry/core/depth_warper.py
+++ b/torchgeometry/core/depth_warper.py
@@ -7,8 +7,9 @@ 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.pinhole import PinholeCamera, PinholeCamerasList
+from torchgeometry.core.pinhole import normalize_pixel_coordinates
from torchgeometry.core.pinhole import cam2pixel, pixel2cam
-from torchgeometry.utils import create_meshgrid, normalize_pixel_coordinates
+from torchgeometry.utils import create_meshgrid
__all__ = [
@@ -21,26 +22,35 @@ class DepthWarper(nn.Module):
"""Warps a patch by depth.
.. math::
- H_{src}^{dst} = K_{dst} * T_{src}^{dst} * K_{src}^{-1}
+ P_{src}^{\{dst\}} = K_{dst} * T_{src}^{\{dst\}}
- I_{src} = \\omega(I_{dst}, H_{src}^{dst}, D_{src})
+ I_{src} = \\omega(I_{dst}, P_{src}^{\{dst\}}, D_{src})
Args:
- pinholes_dst (Iterable[PinholeCamera]): The pinhole models for the
+ 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.
-
+ height (int): the height of the image to warp.
+ width (int): the width of the image to warp.
+ mode (Optional[str]): interpolation mode to calculate output values
+ 'bilinear' | 'nearest'. Default: 'bilinear'.
+ padding_mode (Optional[str]): padding mode for outside grid values
+ 'zeros' | 'border' | 'reflection'. Default: 'zeros'.
"""
def __init__(self,
pinholes_dst: Iterable[PinholeCamera],
- height: int, width: int):
+ height: int, width: int,
+ mode: Optional[str] = 'bilinear',
+ padding_mode: Optional[str] = 'zeros'):
super(DepthWarper, self).__init__()
+ # constructor members
self.width: int = width
self.height: int = height
+ self.mode: Optional[str] = mode
+ self.padding_mode: Optional[str] = padding_mode
self.eps = 1e-6
+ # state members
self._pinhole_dst: PinholeCamerasList = PinholeCamerasList(pinholes_dst)
self._pinhole_src: Union[None, PinholeCamera] = None
self._dst_proj_src: Union[None, torch.Tensor] = None
@@ -53,7 +63,10 @@ class DepthWarper(nn.Module):
height, width, normalized_coordinates=False) # 1xHxWx2
return convert_points_to_homogeneous(grid) # append ones to last dim
- def compute_projection_matrix(self, pinhole_src: PinholeCamera):
+ def compute_projection_matrix(
+ self, pinhole_src: PinholeCamera) -> 'DepthWarper':
+ r"""Computes the projection matrix from the source to destinaion frame.
+ """
if not isinstance(pinhole_src, PinholeCamera):
raise TypeError("Argument pinhole_src expected to be of class "
"PinholeCamera. Got {}".format(type(pinhole_src)))
@@ -77,7 +90,7 @@ class DepthWarper(nn.Module):
dst_proj_src: torch.Tensor = torch.matmul(
intrinsics_dst, dst_trans_src)
- # update class member
+ # update class members
self._pinhole_src = pinhole_src
self._dst_proj_src = dst_proj_src.view(
pinhole_src.batch_size, -1, 4, 4)
@@ -92,7 +105,7 @@ class DepthWarper(nn.Module):
y = (flow[:, 1] * z)
return torch.cat([x, y], 1)
- def compute_subpixel_step(self):
+ def compute_subpixel_step(self) -> torch.Tensor:
"""This computes the required inverse depth step to achieve sub pixel
accurate sampling of the depth cost volume, per camera.
@@ -110,7 +123,6 @@ class DepthWarper(nn.Module):
# half pixel sampling, we're interested in the min for all cameras
return torch.min(0.5 / dxdd)
- # compute grids
def warp_grid(self, depth_src: torch.Tensor) -> torch.Tensor:
"""Computes a grid for warping a given the depth from the reference
pinhole camera.
@@ -167,13 +179,13 @@ class DepthWarper(nn.Module):
in the reference frame.
Args:
- depth_src (torch.Tensor): The depth in the reference frame. The
+ 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
+ patch_dst (torch.Tensor): the patch in the destination frame. The
tensor must have a shape :math:`(B, C, H, W)`.
Return:
- torch.Tensor: The warped patch from destination frame to reference.
+ torch.Tensor: the warped patch from destination frame to reference.
Shape:
- Output: :math:`(N, C, H, W)` where C = number of channels.
@@ -190,7 +202,8 @@ class DepthWarper(nn.Module):
>>> image_dst = torch.rand(1, 3, 32, 32) # NxCxHxW
>>> image_src = warper(depth_src, image_dst) # NxCxHxW
"""
- return F.grid_sample(patch_dst, self.warp_grid(depth_src))
+ return F.grid_sample(patch_dst, self.warp_grid(depth_src),
+ mode=self.mode, padding_mode=self.padding_mode)
# functional api
diff --git a/torchgeometry/core/pinhole.py b/torchgeometry/core/pinhole.py
index 07864d8c8..2937a0734 100644
--- a/torchgeometry/core/pinhole.py
+++ b/torchgeometry/core/pinhole.py
@@ -18,6 +18,7 @@ __all__ = [
"homography_i_H_ref",
"pixel2cam",
"cam2pixel",
+ "normalize_pixel_coordinates",
# layer api
"PinholeMatrix",
"InversePinholeMatrix",
@@ -38,8 +39,8 @@ class PinholeCamera:
width.
.. note::
- We assume that class attributes are batched in order to take advantage
- of PyTorch parallelism.
+ We assume that the class attributes are in batch form in order to take
+ advantage of PyTorch parallelism to boost computing performce.
"""
def __init__(self, intrinsics: torch.Tensor,
@@ -108,7 +109,7 @@ class PinholeCamera:
r"""Returns the batch size of the storage.
Returns:
- int: batch size value
+ int: scalar with the batch size
"""
return self.intrinsics.shape[0]
@@ -393,6 +394,10 @@ class PinholeCamerasList(PinholeCamera):
def pinhole_matrix(pinholes, eps=1e-6):
r"""Function that returns the pinhole matrix from a pinhole model
+ .. note::
+ This method is going to be deprecated in version 0.2 in favour of
+ :attr:`torchgeometry.PinholeCamera.camera_matrix`.
+
Args:
pinholes (Tensor): tensor of pinhole models.
@@ -427,6 +432,10 @@ def pinhole_matrix(pinholes, eps=1e-6):
def inverse_pinhole_matrix(pinhole, eps=1e-6):
r"""Returns the inverted pinhole matrix from a pinhole model
+ .. note::
+ This method is going to be deprecated in version 0.2 in favour of
+ :attr:`torchgeometry.PinholeCamera.intrinsics_inverse()`.
+
Args:
pinholes (Tensor): tensor with pinhole models.
@@ -442,7 +451,7 @@ def inverse_pinhole_matrix(pinhole, eps=1e-6):
>>> pinhole_matrix_inv = tgm.inverse_pinhole_matrix(pinhole) # Nx4x4
"""
warnings.warn("inverse_pinhole_matrix will be deprecated in version 0.2, "
- "use PinholeCamera.camera_matrix() instead",
+ "use PinholeCamera.intrinsics_inverse() instead",
PendingDeprecationWarning)
assert len(pinhole.shape) == 2 and pinhole.shape[1] == 12, pinhole.shape
# unpack pinhole values
@@ -461,6 +470,10 @@ def inverse_pinhole_matrix(pinhole, eps=1e-6):
def scale_pinhole(pinholes, scale):
r"""Scales the pinhole matrix for each pinhole model.
+ .. note::
+ This method is going to be deprecated in version 0.2 in favour of
+ :attr:`torchgeometry.PinholeCamera.scale()`.
+
Args:
pinholes (Tensor): tensor with the pinhole model.
scale (Tensor): tensor of scales.
@@ -506,6 +519,19 @@ def get_optical_pose_base(pinholes):
def homography_i_H_ref(pinhole_i, pinhole_ref):
r"""Homography from reference to ith pinhole
+ .. note::
+ The pinhole model is represented in a single vector as follows:
+
+ .. math::
+ pinhole = (f_x, f_y, c_x, c_y, height, width,
+ r_x, r_y, r_z, t_x, t_y, t_z)
+
+ where:
+ :math:`(r_x, r_y, r_z)` is the rotation vector in angle-axis
+ convention.
+
+ :math:`(t_x, t_y, t_z)` is the translation vector.
+
.. math::
H_{ref}^{i} = K_{i} * T_{ref}^{i} * K_{ref}^{-1}
@@ -569,6 +595,45 @@ def pixel2cam(depth: torch.Tensor, intrinsics_inv: torch.Tensor,
return cam_coords * depth.permute(0, 2, 3, 1)
+# based on:
+# https://github.com/ClementPinard/SfmLearner-Pytorch/blob/master/inverse_warp.py#L65-L71
+
+def normalize_pixel_coordinates(
+ pixel_coordinates: torch.Tensor,
+ height: float,
+ width: float) -> torch.Tensor:
+ r"""Normalize pixel coordinates between -1 and 1.
+
+ Normalized, -1 if on extreme left, 1 if on extreme right (x = w-1).
+
+ Args:
+ pixel_coordinate (torch.Tensor): the grid with pixel coordinates.
+ Shape must be :math:`(B, H, W, 2)`.
+ width (float): the maximum width in the x-axis.
+ height (float): the maximum height in the y-axis.
+
+ Return:
+ torch.Tensor: the nornmalized pixel coordinates.
+ """
+ if len(pixel_coordinates.shape) != 4 and pixel_coordinates.shape[-1] != 2:
+ raise ValueError("Input pixel_coordinates must be of shape BxHxWx2. "
+ "Got {}".format(pixel_coordinates.shape))
+
+ # unpack pixel coordinates
+ u_coord, v_coord = torch.chunk(pixel_coordinates, dim=-1, chunks=2)
+
+ # apply actual normalization
+ factor_u: float = 2. / (width - 1)
+ factor_v: float = 2. / (height - 1)
+ u_coord_norm: torch.Tensor = factor_u * u_coord - 1.
+ v_coord_norm: torch.Tensor = factor_v * v_coord - 1.
+
+ # stack normalized coordinates and return
+ pixel_coordinates_norm: torch.Tensor = torch.cat(
+ [u_coord_norm, v_coord_norm], dim=-1)
+ return pixel_coordinates_norm
+
+
# based on
# https://github.com/ClementPinard/SfmLearner-Pytorch/blob/master/inverse_warp.py#L43
diff --git a/torchgeometry/utils.py b/torchgeometry/utils.py
index e246c6b4a..2d7c91a59 100644
--- a/torchgeometry/utils.py
+++ b/torchgeometry/utils.py
@@ -1,3 +1,5 @@
+from typing import Optional
+
import torch
import torch.nn as nn
import torchgeometry as tgm
@@ -9,64 +11,33 @@ __all__ = [
"tensor_to_image",
"image_to_tensor",
"create_meshgrid",
- "normalize_pixel_coordinates",
]
-def normalize_pixel_coordinates(
- pixel_coordinates: torch.Tensor,
- height: float,
- width: float) -> torch.Tensor:
- r"""Normalize pixel coordinates between -1 and 1.
-
- Normalized, -1 if on extreme left, 1 if on extreme right (x = w-1).
-
- Args:
- pixel_coordinate (torch.Tensor): the grid with pixel coordinates.
- Shape must be BxHxWx2.
- width (int): the maximum width in the x-axis.
- height (int): the maximum height in the y-axis.
-
- Return:
- torch.Tensor: the nornmalized pixel coordinates.
- """
- if len(pixel_coordinates.shape) != 4 and pixel_coordinates.shape[-1] != 2:
- raise ValueError("Input pixel_coordinates must be of shape BxHxWx2. "
- "Got {}".format(pixel_coordinates.shape))
-
- # unpack pixel coordinates
- u_coord, v_coord = torch.chunk(pixel_coordinates, dim=-1, chunks=2)
-
- # apply actual normalization
- factor_u: float = 2. / (width - 1)
- factor_v: float = 2. / (height - 1)
- u_coord_norm: torch.Tensor = factor_u * u_coord - 1.
- v_coord_norm: torch.Tensor = factor_v * v_coord - 1.
-
- # stack normalized coordinates and return
- pixel_coordinates_norm: torch.Tensor = torch.cat(
- [u_coord_norm, v_coord_norm], dim=-1)
- return pixel_coordinates_norm
-
-
-def create_meshgrid(height, width, normalized_coordinates=True):
+def create_meshgrid(
+ height: int,
+ width: int,
+ normalized_coordinates: Optional[bool] = True):
"""Generates a coordinate grid for an image.
- This is normalized to be in the range [-1,1] to be consistent with the
- pytorch function grid_sample.
+ When the flag `normalized_coordinates` is set to True, the grid is
+ normalized to be in the range [-1,1] to be consistent with the pytorch
+ function grid_sample.
http://pytorch.org/docs/master/nn.html#torch.nn.functional.grid_sample
Args:
height (int): the image height (rows).
width (int): the image width (cols).
- normalized_coordinates (bool): wether to used normalized coordinates in
- the range [-1, 1] in order to be consistent with the PyTorch function
- grid_sample.
+ normalized_coordinates (Optional[bool]): wether to normalize
+ coordinates in the range [-1, 1] in order to be consistent with the
+ PyTorch function grid_sample.
Return:
- Tensor: returns a 1xHxWx2 grid.
+ torch.Tensor: returns a grid tensor with shape :math:`(1, H, W, 2)`.
"""
# generate coordinates
+ xs: Optional[torch.Tensor] = None
+ ys: Optional[torch.Tensor] = None
if normalized_coordinates:
xs = torch.linspace(-1, 1, width)
ys = torch.linspace(-1, 1, height)
@@ -74,18 +45,19 @@ def create_meshgrid(height, width, normalized_coordinates=True):
xs = torch.linspace(0, width - 1, width)
ys = torch.linspace(0, height - 1, height)
# generate grid by stacking coordinates
- base_grid = torch.stack(torch.meshgrid([xs, ys])).transpose(1, 2) # 2xHxW
+ base_grid: torch.Tensor = torch.stack(
+ torch.meshgrid([xs, ys])).transpose(1, 2) # 2xHxW
return torch.unsqueeze(base_grid, dim=0).permute(0, 2, 3, 1) # 1xHxWx2
def image_to_tensor(image):
- """Converts a numpy image to a torch.Tensor image.
+ """Converts a numpy image to a PyTorch tensor image.
Args:
- image (numpy.ndarray): image of the form (H, W, C).
+ image (numpy.ndarray): image of the form :math:`(H, W, C)`.
Returns:
- torch.Tensor: tensor of the form (C, H, W).
+ torch.Tensor: tensor of the form :math:`(C, H, W)`.
"""
if not type(image) == np.ndarray:
@@ -104,14 +76,14 @@ def image_to_tensor(image):
def tensor_to_image(tensor):
- """Converts a torch.Tensor image to a numpy image. In case the tensor is in
- the GPU, it will be copied back to CPU.
+ """Converts a PyTorch tensor image to a numpy image. In case the tensor is
+ in the GPU, it will be copied back to CPU.
Args:
- tensor (Tensor): image of the form (C, H, W).
+ tensor (torch.Tensor): image of the form :math:`(C, H, W)`.
Returns:
- numpy.ndarray: image of the form (H, W, C).
+ numpy.ndarray: image of the form :math:`(H, W, C)`.
"""
if not torch.is_tensor(tensor):
diff --git a/tox.ini b/tox.ini
index 7694b469f..a0ffde377 100644
--- a/tox.ini
+++ b/tox.ini
@@ -1,4 +1,4 @@
[flake8]
max-line-length = 80
-ignore = E305,E402,E721,E722,E741,F401,F403,F405,F821,F841,F999
+ignore = E305,E402,E721,E722,E741,F401,F403,F405,F821,F841,F999,W605
exclude = docs/src