π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
move cam2pixel and pixel2cam to pinhole submodule
edgarriba1a01a76fb5ec
diff --git a/docs/source/pinhole.rst b/docs/source/pinhole.rstindex 4761c222f..4c6958b77 100644--- a/docs/source/pinhole.rst+++ b/docs/source/pinhole.rst@@ -65,6 +65,8 @@ The camera rotation and translation are expressed in terms of Euclidean coordina.. autofunction:: inverse_pinhole_matrix.. autofunction:: scale_pinhole.. autofunction:: homography_i_H_ref+.. autofunction:: cam2pixel+.. autofunction:: pixel2cam.. autoclass:: PinholeMatrix.. autoclass:: InversePinholeMatrixdiff --git a/docs/source/utils.rst b/docs/source/utils.rstindex 542acc996..0a8de5644 100644--- a/docs/source/utils.rst+++ b/docs/source/utils.rst@@ -5,4 +5,6 @@ torchgeometry.utils.. autofunction:: tensor_to_image.. autofunction:: image_to_tensor+.. autofunction:: create_meshgrid+.. autofunction:: normalize_pixel_coordinatesdiff --git a/test/test_contrib.py b/test/test_contrib.pyindex db3bb0a83..4e9ad8c72 100644--- a/test/test_contrib.py+++ b/test/test_contrib.py@@ -82,9 +82,12 @@ class TestExtractTensorPatches:patches = m(input)assert patches.shape == (batch_size, 16, 1, 2, 2)for i in range(batch_size):- assert utils.check_equal_torch(input[i, :, 0:2, 0:2], patches[i, 5])- assert utils.check_equal_torch(input[i, :, 0:2, 1:3], patches[i, 6])- assert utils.check_equal_torch(input[i, :, 1:3, 0:2], patches[i, 9])+ assert utils.check_equal_torch(+ input[i, :, 0:2, 0:2], patches[i, 5])+ assert utils.check_equal_torch(+ input[i, :, 0:2, 1:3], patches[i, 6])+ assert utils.check_equal_torch(+ input[i, :, 1:3, 0:2], patches[i, 9])assert utils.check_equal_torch(input[i, :, 1:3, 1:3], patches[i, 10])diff --git a/test/test_depth_warper.py b/test/test_depth_warper.pyindex 3143e7717..2a62aacc8 100644--- a/test/test_depth_warper.py+++ b/test/test_depth_warper.py@@ -254,9 +254,15 @@ class TestDepthWarper:# evaluate function gradientassert gradcheck(tgm.depth_warp,- ([pinhole_dst,], pinhole_src, depth_src, img_dst, height, width,),- raise_exception=True)-+ ([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):diff --git a/test/test_pinhole.py b/test/test_pinhole.pyindex 5d90d7a5e..3147f6158 100644--- a/test/test_pinhole.py+++ b/test/test_pinhole.py@@ -145,7 +145,9 @@ class TestPinholeCamera:assert torch.allclose(pinhole_1.ty, pinhole_11.ty)assert torch.allclose(pinhole_1.tz, pinhole_11.tz)assert torch.allclose(pinhole_1.rt_matrix, pinhole_11.rt_matrix)- assert torch.allclose(pinhole_1.camera_matrix, pinhole_11.camera_matrix)+ assert torch.allclose(+ pinhole_1.camera_matrix,+ pinhole_11.camera_matrix)assert torch.allclose(pinhole_1.rotation_matrix, pinhole_11.rotation_matrix)assert torch.allclose(@@ -167,14 +169,18 @@ class TestPinholeCamera:pinhole = tgm.PinholeCamera(intrinsics, extrinsics, height, width)pinhole_scale = pinhole.scale(scale_factor)- assert utils.check_equal_torch(pinhole_scale.intrinsics[..., 0, 0],- pinhole.intrinsics[..., 0, 0] * scale_val) # fx- assert utils.check_equal_torch(pinhole_scale.intrinsics[..., 1, 1],- pinhole.intrinsics[..., 1, 1] * scale_val) # fy- assert utils.check_equal_torch(pinhole_scale.intrinsics[..., 0, 2],- 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.intrinsics[..., 0, 0],+ pinhole.intrinsics[..., 0, 0] * scale_val) # fx+ assert utils.check_equal_torch(+ pinhole_scale.intrinsics[..., 1, 1],+ pinhole.intrinsics[..., 1, 1] * scale_val) # fy+ assert utils.check_equal_torch(+ pinhole_scale.intrinsics[..., 0, 2],+ pinhole.intrinsics[..., 0, 2] * scale_val) # cx+ assert utils.check_equal_torch(+ pinhole_scale.intrinsics[..., 1, 2],+ pinhole.intrinsics[..., 1, 2] * scale_val) # cyassert utils.check_equal_torch(pinhole_scale.height,pinhole.height * scale_val)@@ -183,50 +189,55 @@ class TestPinholeCamera: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- assert utils.check_equal_torch(pinhole_scale.intrinsics[..., 1, 1],- pinhole.intrinsics[..., 1, 1] * scale_val) # fy- assert utils.check_equal_torch(pinhole_scale.intrinsics[..., 0, 2],- 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.intrinsics[..., 0, 0],+ pinhole.intrinsics[..., 0, 0] * scale_val) # fx+ assert utils.check_equal_torch(+ pinhole_scale.intrinsics[..., 1, 1],+ pinhole.intrinsics[..., 1, 1] * scale_val) # fy+ assert utils.check_equal_torch(+ pinhole_scale.intrinsics[..., 0, 2],+ pinhole.intrinsics[..., 0, 2] * scale_val) # cx+ assert utils.check_equal_torch(+ pinhole_scale.intrinsics[..., 1, 2],+ pinhole.intrinsics[..., 1, 2] * scale_val) # cyassert 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 varassert gradcheck(tgm.scale_pinhole, (pinholes, scales,),raise_exception=True)@@ -235,21 +246,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())@@ -259,7 +270,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 varassert gradcheck(tgm.pinhole_matrix, (pinhole,),raise_exception=True)@@ -268,21 +279,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(@@ -294,7 +305,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 varassert gradcheck(tgm.pinhole_matrix, (pinhole,),raise_exception=True)@@ -303,20 +314,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,@@ -329,14 +340,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) + epsassert utils.check_equal_torch(i_H_ref_inv, ref_H_i)# evaluate function gradientdiff --git a/torchgeometry/core/depth_warper.py b/torchgeometry/core/depth_warper.pyindex 036ef4a75..265b61c02 100644--- a/torchgeometry/core/depth_warper.py+++ b/torchgeometry/core/depth_warper.py@@ -1,14 +1,14 @@from typing import Optional, Iterable, Union-import torchimport torch.nn as nnimport torch.nn.functional as F-from torchgeometry.utils import create_meshgridfrom torchgeometry.core.transformations import relative_posefrom torchgeometry.core.conversions import transform_pointsfrom torchgeometry.core.conversions import convert_points_to_homogeneousfrom torchgeometry.core.pinhole import PinholeCamera, PinholeCamerasList+from torchgeometry.core.pinhole import cam2pixel, pixel2cam+from torchgeometry.utils import create_meshgrid, normalize_pixel_coordinates__all__ = [@@ -17,114 +17,6 @@ __all__ = []-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---# based on:-# https://github.com/ClementPinard/SfmLearner-Pytorch/blob/master/inverse_warp.py#L26--def pixel2cam(depth: torch.Tensor, intrinsics_inv: torch.Tensor,- pixel_coords: torch.Tensor) -> torch.Tensor:- r"""Transform coordinates in the pixel frame to the camera frame.-- Args:- depth (torch.Tensor): the source depth maps. Shape must be Bx1xHxW.- intrinsics_inv (torch.Tensor): the inverse intrinsics camera matrix.- Shape must be Bx4x4.- pixel_coords (torch.Tensor): the grid with the homogeneous camera- coordinates. Shape must be BxHxWx3.-- Returns:- torch.Tensor: array of (u, v, 1) cam coordinates with shape BxHxWx3.- """- if not len(depth.shape) == 4 and depth.shape[1] == 1:- raise ValueError("Input depth has to be in the shape of "- "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(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(intrinsics_inv.shape))- cam_coords: torch.Tensor = transform_points(- intrinsics_inv[:, None], pixel_coords)- return cam_coords * depth.permute(0, 2, 3, 1)---# based on-# https://github.com/ClementPinard/SfmLearner-Pytorch/blob/master/inverse_warp.py#L43--def cam2pixel(- cam_coords_src: torch.Tensor,- dst_proj_src: torch.Tensor,- eps: Optional[float] = 1e-6) -> torch.Tensor:- r"""Transform coordinates in the camera frame to the pixel frame.-- Args:- cam_coords (torch.Tensor): pixel coordinates defined in the first- camera coordinates system. Shape must be BxHxWx3.- dst_proj_src (torch.Tensor): the projection matrix between the- reference and the non reference camera frame. Shape must be Bx4x4.-- Returns:- torch.Tensor: array of [-1, 1] coordinates of shape BxHxWx2.- """- 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(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))- b, h, w, _ = cam_coords_src.shape- # apply projection matrix to points- 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]-- # compute pixel coordinates- u_coord: torch.Tensor = x_coord / (z_coord + eps)- v_coord: torch.Tensor = y_coord / (z_coord + eps)-- # 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 # (B*N)xHxWx2--class DepthWarper(nn.Module):"""Warps a patch by depth.@@ -161,24 +53,6 @@ class DepthWarper(nn.Module):height, width, normalized_coordinates=False) # 1xHxWx2return convert_points_to_homogeneous(grid) # append ones to last dim- # TODO(edgar): remove- '''def compute_homographies(self, pinhole, scale=None):- if scale is None:- batch_size = pinhole.shape[0]- scale = torch.ones(- batch_size).to(- pinhole.device).type_as(pinhole)- # TODO: add type and value checkings- pinhole_ref = scale_pinhole(pinhole, scale)- if self.width is None:- self.width = pinhole_ref[..., 5:6]- if self.height is None:- self.height = pinhole_ref[..., 4:5]- 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)'''-def compute_projection_matrix(self, pinhole_src: PinholeCamera):if not isinstance(pinhole_src, PinholeCamera):raise TypeError("Argument pinhole_src expected to be of class "diff --git a/torchgeometry/core/pinhole.py b/torchgeometry/core/pinhole.pyindex 82fab305e..07864d8c8 100644--- a/torchgeometry/core/pinhole.py+++ b/torchgeometry/core/pinhole.py@@ -1,11 +1,11 @@-from typing import Iterable+from typing import Iterable, Optionalimport warningsimport torchimport torch.nn as nn-from .conversions import rtvec_to_pose-from .transformations import inverse_pose+from torchgeometry.core.transformations import inverse_pose+from torchgeometry.core.conversions import rtvec_to_pose, transform_points__all__ = [@@ -16,6 +16,8 @@ __all__ = ["inverse_pinhole_matrix","scale_pinhole","homography_i_H_ref",+ "pixel2cam",+ "cam2pixel",# layer api"PinholeMatrix","InversePinholeMatrix",@@ -535,6 +537,78 @@ def homography_i_H_ref(pinhole_i, pinhole_ref):pinhole_matrix(pinhole_i),torch.matmul(i_pose_ref, inverse_pinhole_matrix(pinhole_ref)))+# based on:+# https://github.com/ClementPinard/SfmLearner-Pytorch/blob/master/inverse_warp.py#L26+++def pixel2cam(depth: torch.Tensor, intrinsics_inv: torch.Tensor,+ pixel_coords: torch.Tensor) -> torch.Tensor:+ r"""Transform coordinates in the pixel frame to the camera frame.++ Args:+ depth (torch.Tensor): the source depth maps. Shape must be Bx1xHxW.+ intrinsics_inv (torch.Tensor): the inverse intrinsics camera matrix.+ Shape must be Bx4x4.+ pixel_coords (torch.Tensor): the grid with the homogeneous camera+ coordinates. Shape must be BxHxWx3.++ Returns:+ torch.Tensor: array of (u, v, 1) cam coordinates with shape BxHxWx3.+ """+ if not len(depth.shape) == 4 and depth.shape[1] == 1:+ raise ValueError("Input depth has to be in the shape of "+ "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(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(intrinsics_inv.shape))+ cam_coords: torch.Tensor = transform_points(+ intrinsics_inv[:, None], pixel_coords)+ return cam_coords * depth.permute(0, 2, 3, 1)+++# based on+# https://github.com/ClementPinard/SfmLearner-Pytorch/blob/master/inverse_warp.py#L43++def cam2pixel(+ cam_coords_src: torch.Tensor,+ dst_proj_src: torch.Tensor,+ eps: Optional[float] = 1e-6) -> torch.Tensor:+ r"""Transform coordinates in the camera frame to the pixel frame.++ Args:+ cam_coords (torch.Tensor): pixel coordinates defined in the first+ camera coordinates system. Shape must be BxHxWx3.+ dst_proj_src (torch.Tensor): the projection matrix between the+ reference and the non reference camera frame. Shape must be Bx4x4.++ Returns:+ torch.Tensor: array of [-1, 1] coordinates of shape BxHxWx2.+ """+ 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(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))+ b, h, w, _ = cam_coords_src.shape+ # apply projection matrix to points+ 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]++ # compute pixel coordinates+ u_coord: torch.Tensor = x_coord / (z_coord + eps)+ v_coord: torch.Tensor = y_coord / (z_coord + eps)++ # 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 # (B*N)xHxWx2+# layer apidiff --git a/torchgeometry/utils.py b/torchgeometry/utils.pyindex 9c920318a..e246c6b4a 100644--- a/torchgeometry/utils.py+++ b/torchgeometry/utils.py@@ -9,9 +9,46 @@ __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):"""Generates a coordinate grid for an image.