Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

implement opencv like remap

edgarribaf7e8066729a7
diff --git a/docs/source/geometric.rst b/docs/source/geometric.rst
index 0891c6291..69d1c566f 100644
--- a/docs/source/geometric.rst
+++ b/docs/source/geometric.rst
@@ -9,6 +9,7 @@ The functions in this section perform various geometrical transformations of 2D
.. autofunction:: warp_affine
.. autofunction:: get_perspective_transform
.. autofunction:: get_rotation_matrix2d
+.. autofunction:: remap
.. autofunction:: affine
.. autofunction:: rotate
diff --git a/test/test_imgwarp.py b/test/test_imgwarp.py
index f8a534cf2..5e8df9d80 100644
--- a/test/test_imgwarp.py
+++ b/test/test_imgwarp.py
@@ -271,3 +271,107 @@ class TestWarpAffine:
(height, width),
),
raise_exception=True)
+
+
+class TestRemap:
+ def test_smoke(self):
+ height, width = 3, 4
+ input = torch.ones(1, 1, height, width)
+ grid = tgm.utils.create_meshgrid(
+ height, width, normalized_coordinates=False)
+ input_warped = tgm.remap(input, grid[..., 0], grid[..., 1])
+ assert_allclose(input, input_warped)
+
+ def test_shift(self):
+ height, width = 3, 4
+ inp = torch.tensor([[[
+ [1., 1., 1., 1.],
+ [1., 1., 1., 1.],
+ [1., 1., 1., 1.],
+ ]]])
+ expected = torch.tensor([[[
+ [1., 1., 1., 0.],
+ [1., 1., 1., 0.],
+ [0., 0., 0., 0.],
+ ]]])
+
+ grid = tgm.utils.create_meshgrid(
+ height, width, normalized_coordinates=False)
+ grid += 1. # apply shift in both x/y direction
+
+ input_warped = tgm.remap(inp, grid[..., 0], grid[..., 1])
+ assert_allclose(input_warped, expected)
+
+ def test_shift_batch(self):
+ height, width = 3, 4
+ inp = torch.tensor([[[
+ [1., 1., 1., 1.],
+ [1., 1., 1., 1.],
+ [1., 1., 1., 1.],
+ ]]]).repeat(2, 1, 1, 1)
+
+ expected = torch.tensor([[[
+ [1., 1., 1., 0.],
+ [1., 1., 1., 0.],
+ [1., 1., 1., 0.],
+ ]], [[
+ [1., 1., 1., 1.],
+ [1., 1., 1., 1.],
+ [0., 0., 0., 0.],
+ ]]])
+
+ # generate a batch of grids
+ grid = tgm.utils.create_meshgrid(
+ height, width, normalized_coordinates=False)
+ grid = grid.repeat(2, 1, 1, 1)
+ grid[0, ..., 0] += 1. # apply shift in the x direction
+ grid[1, ..., 1] += 1. # apply shift in the y direction
+
+ input_warped = tgm.remap(inp, grid[..., 0], grid[..., 1])
+ assert_allclose(input_warped, expected)
+
+ def test_shift_batch_broadcast(self):
+ height, width = 3, 4
+ inp = torch.tensor([[[
+ [1., 1., 1., 1.],
+ [1., 1., 1., 1.],
+ [1., 1., 1., 1.],
+ ]]]).repeat(2, 1, 1, 1)
+ expected = torch.tensor([[[
+ [1., 1., 1., 0.],
+ [1., 1., 1., 0.],
+ [0., 0., 0., 0.],
+ ]]])
+
+ grid = tgm.utils.create_meshgrid(
+ height, width, normalized_coordinates=False)
+ grid += 1. # apply shift in both x/y direction
+
+ input_warped = tgm.remap(inp, grid[..., 0], grid[..., 1])
+ assert_allclose(input_warped, expected)
+
+ def test_gradcheck(self):
+ batch_size, channels, height, width = 1, 2, 3, 4
+ img = torch.rand(batch_size, channels, height, width)
+ img = utils.tensor_to_gradcheck_var(img) # to var
+
+ grid = tgm.utils.create_meshgrid(
+ height, width, normalized_coordinates=False)
+ grid = utils.tensor_to_gradcheck_var(
+ grid, requires_grad=False) # to var
+
+ assert gradcheck(tgm.remap, (img, grid[..., 0], grid[..., 1],),
+ raise_exception=True)
+
+ def test_jit(self):
+ batch_size, channels, height, width = 1, 1, 3, 4
+ img = torch.ones(batch_size, channels, height, width)
+
+ grid = tgm.utils.create_meshgrid(
+ height, width, normalized_coordinates=False)
+ grid += 1. # apply some shift
+
+ input = (img, grid[..., 0], grid[..., 1],)
+ remap_traced = torch.jit.trace(tgm.remap, input)
+
+ assert_allclose(tgm.remap(*input), remap_traced(*input))
diff --git a/torchgeometry/core/imgwarp.py b/torchgeometry/core/imgwarp.py
index a1b65a75a..eec0451b4 100644
--- a/torchgeometry/core/imgwarp.py
+++ b/torchgeometry/core/imgwarp.py
@@ -5,6 +5,8 @@ import torch.nn.functional as F
from torchgeometry.core.conversions import deg2rad
from torchgeometry.core.homography_warper import homography_warp
+# TODO: move to utils or conversions
+from torchgeometry.core.pinhole import normalize_pixel_coordinates
__all__ = [
@@ -13,6 +15,7 @@ __all__ = [
"get_perspective_transform",
"get_rotation_matrix2d",
"normal_transform_pixel",
+ "remap",
]
@@ -352,3 +355,59 @@ def get_rotation_matrix2d(
M[..., 1, 1] = alpha
M[..., 1, 2] = beta * x + (torch.tensor(1.) - alpha) * y
return M
+
+
+def remap(tensor: torch.Tensor, map_x: torch.Tensor,
+ map_y: torch.Tensor) -> torch.Tensor:
+ r"""Applies a generic geometrical transformation to a tensor.
+
+ The function remap transforms the source tensor using the specified map:
+
+ .. math::
+ \text{dst}(x, y) = \text{src}(map_x(x, y), map_y(x, y))
+
+ Args:
+ tensor (torch.Tensor): the tensor to remap with shape (B, D, H, W).
+ Where D is the number of channels.
+ map_x (torch.Tensor): the flow in the x-direction in pixel coordinates.
+ The tensor must be in the shape of (B, H, W).
+ map_y (torch.Tensor): the flow in the y-direction in pixel coordinates.
+ The tensor must be in the shape of (B, H, W).
+
+ Returns:
+ torch.Tensor: the warped tensor.
+
+ Example:
+ >>> grid = tgm.utils.create_meshgrid(2, 2, False) # 1x2x2x2
+ >>> grid += 1 # apply offset in both directions
+ >>> input = torch.ones(1, 1, 2, 2)
+ >>> tgm.remap(input, grid[..., 0], grid[..., 1]) # 1x1x2x2
+ tensor([[[[1., 0.],
+ [0., 0.]]]])
+
+ """
+ if not torch.is_tensor(tensor):
+ raise TypeError("Input tensor type is not a torch.Tensor. Got {}"
+ .format(type(tensor)))
+ if not torch.is_tensor(map_x):
+ raise TypeError("Input map_x type is not a torch.Tensor. Got {}"
+ .format(type(map_x)))
+ if not torch.is_tensor(map_y):
+ raise TypeError("Input map_y type is not a torch.Tensor. Got {}"
+ .format(type(map_y)))
+ if not tensor.shape[-2:] == map_x.shape[-2:] == map_y.shape[-2:]:
+ raise ValueError("Inputs last two dimensions must match.")
+
+ batch_size, _, height, width = tensor.shape
+
+ # grid_sample need the grid between -1/1
+ map_xy: torch.Tensor = torch.stack([map_x, map_y], dim=-1)
+ map_xy_norm: torch.Tensor = normalize_pixel_coordinates(
+ map_xy, height, width)
+
+ # simulate broadcasting since grid_sample does not support it
+ map_xy_norm = map_xy_norm.expand(batch_size, -1, -1, -1)
+
+ # warp ans return
+ tensor_warped: torch.Tensor = F.grid_sample(tensor, map_xy_norm)
+ return tensor_warped
diff --git a/torchgeometry/core/pinhole.py b/torchgeometry/core/pinhole.py
index 1a5270f5e..aef9dc226 100644
--- a/torchgeometry/core/pinhole.py
+++ b/torchgeometry/core/pinhole.py
@@ -605,12 +605,15 @@ def normalize_pixel_coordinates(
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.
"""
@@ -633,6 +636,7 @@ def normalize_pixel_coordinates(
# 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,
diff --git a/torchgeometry/image/normalization.py b/torchgeometry/image/normalization.py
index b8f173b32..dec9ac127 100644
--- a/torchgeometry/image/normalization.py
+++ b/torchgeometry/image/normalization.py
@@ -34,7 +34,6 @@ class Normalize(nn.Module):
def normalize(data: torch.Tensor, mean: torch.Tensor,
std: torch.Tensor) -> torch.Tensor:
-
"""Normalise the image with channel-wise mean and standard deviation.
Args: