🐍 Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(geometry): reorder the 3D sampling grid to (x, y, z) in homography_warp3d (#4514)
Leonardo Vanni38fa107a3803
diff --git a/changelog.d/4514.fixed.md b/changelog.d/4514.fixed.mdnew file mode 100644index 000000000..32d060bca--- /dev/null+++ b/changelog.d/4514.fixed.md@@ -0,0 +1,10 @@+`warp_perspective3d` and `homography_warp3d` reproduce an identity warp. `homography_warp3d`+handed the `(d, x, y)` grid that `create_meshgrid3d` produces straight to `warp_grid3d` and+`torch.nn.functional.grid_sample`, both of which read the last axis as `(x, y, z)`, so every+voxel was sampled from the wrong place: an identity homography on a 4x4x4 `arange` volume+deviated by 45.0 at `align_corners=True` and 55.125 at `False`, and a +1 translation along `x`+moved slices instead of columns. The grid is reordered at that call site; `create_meshgrid3d`,+`normalize_pixel_coordinates3d` and `conv_soft_argmax3d` keep their documented `(d, x, y)`+order and `warp_affine3d`, which builds its grid with `F.affine_grid`, was never affected. The+`align_corners=False` identity still deviates after this change; that remaining residual is the+3D normalization convention tracked in #4503. Fixes #4502.diff --git a/kornia/geometry/transform/imgwarp.py b/kornia/geometry/transform/imgwarp.pyindex 84abfee72..331b7de39 100644--- a/kornia/geometry/transform/imgwarp.py+++ b/kornia/geometry/transform/imgwarp.py@@ -1785,7 +1785,13 @@ def homography_warp3d(Convention:- input: :math:`(N, C, D, H, W)`; ``dsize`` is ``(d, h, w)``- ``src_homo_dst`` is the destination→source homography :math:`(N, 4, 4)`, in normalized- :math:`[-1, 1]` coordinates by default (``normalized_coordinates=True``)+ :math:`[-1, 1]` coordinates by default (``normalized_coordinates=True``), and acts on+ ``(x, y, z, 1)`` column vectors: ``x`` indexes ``W``, ``y`` indexes ``H``, ``z`` indexes+ ``D``. That is the order :func:`torch.nn.functional.grid_sample` reads a 5-D grid in, and+ the order :func:`warp_grid3d` takes. kornia's own 3-D grids and pixel coordinates are+ ``(d, x, y)`` (see :func:`~kornia.geometry.grid.create_meshgrid3d`), so the sampling grid+ is reordered here before the homography is applied; nothing else in the module changes+ its order- align_corners: ``False`` by default- padding_mode: ``'zeros'`` by default- negative output dimensions raise ``ValueError``@@ -1821,6 +1827,10 @@ def homography_warp3d(grid = create_meshgrid3d(depth, height, width, normalized_coordinates=normalized_coordinates, device=patch_src.device)+ # ``create_meshgrid3d`` follows kornia's ``(d, x, y)`` convention, which+ # ``normalize_pixel_coordinates3d`` and ``conv_soft_argmax3d`` rely on. ``warp_grid3d`` and+ # ``grid_sample`` both read the last axis as ``(x, y, z)``, so the depth channel moves last.+ grid = grid[..., [1, 2, 0]]warped_grid = warp_grid3d(grid, src_homo_dst)return F.grid_sample(patch_src, warped_grid, mode=mode, padding_mode=padding_mode, align_corners=align_corners)diff --git a/tests/geometry/transform/test_imgwarp3d.py b/tests/geometry/transform/test_imgwarp3d.pyindex a6d0b0f0d..7fa99df47 100644--- a/tests/geometry/transform/test_imgwarp3d.py+++ b/tests/geometry/transform/test_imgwarp3d.py@@ -139,6 +139,110 @@ def test_homography_warp3d_negative_destination_raises(device, dtype):proj.homography_warp3d(src, transform, (-1, 4, 5))+class TestWarpPerspective3d(BaseTester):+ # Before #4502 none of these could pass: homography_warp3d handed create_meshgrid3d's (d, x, y)+ # grid straight to warp_grid3d and grid_sample, which both read (x, y, z), so even an identity+ # homography sampled the wrong voxel. Measured on main with the arange volumes below:+ # identity, (4, 4, 4): max|out - in| = 45.0 at align_corners=True, 55.125 at False+ # identity, (2, 3, 4): 9.0 and 20.125; (1, 5, 3): 10.5 at False+ # The only prior numerical test compared an unbatched call with a batched one, and both were+ # wrong the same way. align_corners=False is pinned as a strict xfail: after this fix the+ # remaining residual is the 3D normalization convention tracked in #4503, not the grid order.++ @staticmethod+ def _arange_volume(dsize, device, dtype):+ d, h, w = dsize+ return torch.arange(float(d * h * w), device=device, dtype=dtype).view(1, 1, d, h, w)++ @pytest.mark.parametrize("dsize", [(4, 4, 4), (2, 3, 4), (1, 5, 3), (3, 1, 4)])+ def test_convention_identity_reproduces_input(self, dsize, device, dtype):+ sample = self._arange_volume(dsize, device, dtype)+ identity = torch.eye(4, device=device, dtype=dtype)[None]+ out = proj.warp_perspective3d(sample, identity, dsize, align_corners=True)+ self.assert_close(out, sample)++ @pytest.mark.parametrize("dsize", [(4, 4, 4), (2, 3, 4)])+ @pytest.mark.xfail(strict=True, raises=AssertionError, reason="3D normalization ignores align_corners, #4503")+ def test_convention_identity_reproduces_input_align_corners_false(self, dsize, device, dtype):+ # Strict xfail: turns XPASS, and so fails loudly, once #4503 threads align_corners through+ # normal_transform_pixel3d, which is the signal to fold this into the test above.+ sample = self._arange_volume(dsize, device, dtype)+ identity = torch.eye(4, device=device, dtype=dtype)[None]+ out = proj.warp_perspective3d(sample, identity, dsize, align_corners=False)+ self.assert_close(out, sample)++ @pytest.mark.parametrize("dsize", [(5, 5, 5), (2, 3, 5), (3, 2, 5)])+ def test_convention_agrees_with_warp_affine3d(self, dsize, device, dtype):+ # warp_affine3d builds its grid with F.affine_grid, which is (x, y, z) already, so it never+ # had the channel-order defect. Given the same affine matrix the two warps must agree.+ # Every size is one more than a power of two so the corner-aligned scale 2 / (size - 1) is+ # exact in every dtype; the two routes (affine_grid against meshgrid-then-matmul) then+ # agree bit for bit at float16 and bfloat16 as well, whereas a size-4 axis makes them round+ # differently, by up to 0.023 at bfloat16 over ten seeds, which would say nothing about the+ # channel order under test. No singleton axis: torch's CPU F.affine_grid has no+ # float16/bfloat16 kernel for a size-1 dimension, and that is the reference, not the+ # subject. The identity test above covers singleton depth and height.+ sample = torch.rand(1, 2, *dsize, device=device, dtype=dtype)+ _, _, D, H, W = sample.shape+ center = torch.tensor([[(W - 1) / 2, (H - 1) / 2, (D - 1) / 2]], device=device, dtype=dtype)+ angles = torch.tensor([[20.0, -15.0, 30.0]], device=device, dtype=dtype)+ scales = torch.ones_like(angles)+ P = proj.get_projective_transform(center, angles, scales) # (1, 3, 4)+ M = kornia.geometry.convert_affinematrix_to_homography3d(P) # (1, 4, 4)+ out_perspective = proj.warp_perspective3d(sample, M, dsize, align_corners=True)+ out_affine = proj.warp_affine3d(sample, P, dsize, align_corners=True)+ self.assert_close(out_perspective, out_affine)++ @pytest.mark.parametrize("axis", [0, 1, 2], ids=["x", "y", "z"])+ def test_convention_whole_voxel_translation(self, axis, device, dtype):+ # A +1 translation along x must shift columns (W), along y rows (H), along z slices (D).+ # With the channels in the wrong order a shift along x moved slices instead. The three+ # sizes differ so that shifting the wrong axis cannot reproduce the expected volume, and+ # each is one more than a power of two so that the corner-aligned scale 2 / (size - 1) is+ # exact in every dtype: with W = 4 that scale is 2/3, and at float16/bfloat16 the shift+ # lands a fraction of a voxel off, exactly as the 2D test_translation manifest entries+ # record for the same reason.+ dsize = (2, 3, 5)+ sample = self._arange_volume(dsize, device, dtype)+ M = torch.eye(4, device=device, dtype=dtype)[None].clone()+ M[:, axis, 3] = 1.0+ expected = torch.zeros_like(sample)+ if axis == 0:+ expected[..., 1:] = sample[..., :-1]+ elif axis == 1:+ expected[..., 1:, :] = sample[..., :-1, :]+ else:+ expected[:, :, 1:] = sample[:, :, :-1]+ out = proj.warp_perspective3d(sample, M, dsize, align_corners=True)+ self.assert_close(out, expected)++ def test_convention_projective_row_is_honoured(self, device, dtype):+ # A (B, 4, 4) matrix with a non-trivial last row must change the output; otherwise the+ # fix would only have made the function a slower warp_affine3d.+ dsize = (2, 3, 4)+ sample = self._arange_volume(dsize, device, dtype)+ M = torch.eye(4, device=device, dtype=dtype)[None].clone()+ M[:, 3, 0] = 0.05+ out = proj.warp_perspective3d(sample, M, dsize, align_corners=True)+ assert not torch.allclose(out, sample)++ def test_homography_warp3d_identity(self, device, dtype):+ # The functional entry point with an already-normalized identity, both grid conventions.+ dsize = (2, 3, 4)+ sample = self._arange_volume(dsize, device, dtype)+ identity = torch.eye(4, device=device, dtype=dtype)[None]+ out = proj.homography_warp3d(sample, identity, dsize, align_corners=True)+ self.assert_close(out, sample)+ out_pix = proj.homography_warp3d(sample, identity, dsize, align_corners=True, normalized_coordinates=False)+ assert out_pix.shape == sample.shape++ def test_gradcheck(self, device):+ sample = torch.rand(1, 1, 2, 3, 4, device=device, dtype=torch.float64, requires_grad=True)+ M = torch.eye(4, device=device, dtype=torch.float64)[None].clone()+ M[:, :3, 3] = 0.3+ self.gradcheck(proj.warp_perspective3d, (sample, M, (2, 3, 4)), requires_grad=(True, False, False))++class TestWarpAffine3d(BaseTester):def test_smoke(self, device, dtype):sample = torch.rand(1, 3, 3, 4, 5, device=device, dtype=dtype)