π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
fix(geometry): build the depth pixel grid in the promoted dtype (#6153)
niukanen1d30139e1e85f
diff --git a/changelog.d/6153.fixed.md b/changelog.d/6153.fixed.mdnew file mode 100644index 000000000..5a3976fd0--- /dev/null+++ b/changelog.d/6153.fixed.md@@ -0,0 +1 @@+`depth_to_3d`, `depth_to_3d_v2`, `warp_frame_depth` and `depth_to_normals` now build the pixel grid in the promoted dtype of `depth` and `camera_matrix` instead of in the dtype of `depth`. In 0.9.0, `uint8` and `int8` depth wrapped the column index past 255 and 127, and `uint16` and `uint32` depth raised `NotImplementedError`, in all four. In the first three, a bfloat16 depth map with float32 intrinsics also rounded the column index, putting `X` up to 2 px off at 640 px wide; float16 depth did so past 2048 px.diff --git a/kornia/geometry/depth.py b/kornia/geometry/depth.pyindex 7067d6aa5..c03300c1a 100644--- a/kornia/geometry/depth.py+++ b/kornia/geometry/depth.py@@ -51,6 +51,28 @@ __all__ = []+def _depth_grid_dtype(depth: torch.Tensor, camera_matrix: torch.Tensor) -> torch.dtype:+ """Return the dtype the pixel grid is built in before unprojection.++ The grid holds the integer pixel indices at the precision of the promoted inputs: a bfloat16 or+ float16 grid rounds them, and an integer grid cannot represent them. Integer inputs promote to+ the default floating dtype instead: ``promote_types`` does not support unsigned/signed integer+ pairs. A complex promotion keeps a real grid, because ``arange`` has no complex kernels and the+ subsequent arithmetic promotes to complex anyway, which also unblocks complex inputs. An all-half+ call keeps its half grid.+ """+ depth_is_float = depth.is_floating_point()+ camera_is_float = camera_matrix.is_floating_point()+ if not depth_is_float and not camera_is_float and not depth.is_complex() and not camera_matrix.is_complex():+ return torch.empty(0, device=depth.device).dtype+ promoted = torch.promote_types(depth.dtype, camera_matrix.dtype)+ # A complex32 promotion is checked through the tensors, not the promoted dtype: TorchScript sees a+ # dtype as an integer, so a membership test on dtype attributes would not compile.+ if depth.is_complex() or camera_matrix.is_complex():+ return torch.empty(0, device=depth.device, dtype=promoted).real.dtype+ return promoted++def unproject_meshgrid(height: int,width: int,@@ -82,7 +104,7 @@ def unproject_meshgrid(normalize_points: whether to normalize the pointcloud. This must be set to `True` when the depth isrepresented as the Euclidean ray length from the camera position.device: device to place the result on.- dtype: dtype of the result.+ dtype: dtype of the pixel grid; the output dtype follows promotion with ``camera_matrix``.Return:tensor with a 3d point per pixel, with shape :math:`(B, H, W, 3)`.@@ -133,10 +155,13 @@ def depth_to_3d_v2(:class:`~kornia.geometry.camera.pinhole.PinholeCamera`). It equals:func:`~kornia.geometry.depth.depth_to_3d` after ``permute(0, 2, 3, 1)``.- without ``xyz_grid``, ``camera_matrix`` must be exactly :math:`(B, 3, 3)` (another shape raises- ``ShapeError``); with ``xyz_grid`` it is never read.+ ``ShapeError``); with ``xyz_grid`` only its shape is checked.- ``normalize_points=True`` reads ``depth`` as the Euclidean ray length instead of ``z``.- ``xyz_grid`` replaces the grid construction; pass what :func:`~kornia.geometry.depth.unproject_meshgrid`returns for the same camera.+ - without ``xyz_grid``, the pixel grid is built in ``promote_types(depth.dtype, camera_matrix.dtype)``+ when either input is floating (the default floating dtype when both are integer), so half-precision+ depth does not round the pixel indices below the intrinsics' precision.Args:depth: image tensor containing a depth value per pixel with shape :math:`(*, H, W)`.@@ -167,7 +192,9 @@ def depth_to_3d_v2(points_xyz: torch.Tensor = (xyz_gridif xyz_grid is not None- else unproject_meshgrid(height, width, camera_matrix, normalize_points, depth.device, depth.dtype)+ else unproject_meshgrid(+ height, width, camera_matrix, normalize_points, depth.device, _depth_grid_dtype(depth, camera_matrix)+ ))KORNIA_CHECK_SHAPE(points_xyz, ["*", "H", "W", "3"])@@ -191,6 +218,9 @@ def depth_to_3d(depth: torch.Tensor, camera_matrix: torch.Tensor, normalize_poin:func:`~kornia.geometry.depth.depth_to_3d_v2` after ``permute(0, 2, 3, 1)``.- ``normalize_points=True`` reads ``depth`` as the Euclidean ray length instead of ``z``.- an integer ``depth`` is not rejected; the result takes the floating dtype of ``camera_matrix``.+ The pixel grid is built in ``promote_types(depth.dtype, camera_matrix.dtype)`` when either input is+ floating (the default floating dtype when both are integer), so half-precision ``depth`` does not+ round the pixel indices below the intrinsics' precision.Args:depth: image tensor containing a depth value per pixel with shape :math:`(B, 1, H, W)`.@@ -216,7 +246,11 @@ def depth_to_3d(depth: torch.Tensor, camera_matrix: torch.Tensor, normalize_poin# create base coordinates grid_, _, height, width = depth.shapepoints_2d: torch.Tensor = create_meshgrid(- height, width, normalized_coordinates=False, device=depth.device, dtype=depth.dtype+ height,+ width,+ normalized_coordinates=False,+ device=depth.device,+ dtype=_depth_grid_dtype(depth, camera_matrix),) # 1xHxWx2# depth should come in Bx1xHxW@@ -280,7 +314,7 @@ def depth_to_normals(depth: torch.Tensor, camera_matrix: torch.Tensor, normalizedtype = torch.promote_types(depth.dtype, camera_matrix.dtype)# Compute in float32 when either input is half precision: bfloat16 cannot hold the pixel grid past 256 and the- # float16 cross product of small pixel tangents underflows. The grid takes ``depth``'s dtype, so cast each input.+ # float16 cross product of small pixel tangents underflows. The grid takes the promoted dtype, so cast each input.if depth.dtype in (torch.float16, torch.bfloat16):depth = depth.float()if camera_matrix.dtype in (torch.float16, torch.bfloat16):diff --git a/tests/geometry/test_depth.py b/tests/geometry/test_depth.pyindex 789bf15ec..f04a6f2c1 100644--- a/tests/geometry/test_depth.py+++ b/tests/geometry/test_depth.py@@ -317,6 +317,148 @@ class TestDepthTo3d(BaseTester):with pytest.raises(ShapeError):depth_to_3d_v2(depth, camera_matrix[0])+ @pytest.mark.parametrize("half_dtype", [torch.bfloat16, torch.float16])+ def test_half_depth_with_float32_intrinsics_keeps_pixel_precision_6148(self, half_dtype, device, dtype):+ # kornia#6148: a half-precision depth map with float32 intrinsics built its pixel grid in the depth's+ # dtype, so the integer column indices were rounded (bfloat16 holds integers only to 256) and X drifted+ # by up to 2 px at 640 px wide. The grid is now built in the promoted dtype, so the points match the+ # float64 reference at float32 roundoff. float16 keeps the same behaviour past 2048 columns.+ width = 640 if half_dtype == torch.bfloat16 else 2051+ camera_matrix = torch.tensor(+ [[[500.0, 0.0, 320.0], [0.0, 500.0, 0.5], [0.0, 0.0, 1.0]]], device=device, dtype=torch.float32+ )+ depth = torch.full((1, 1, 2, width), 2.0, device=device, dtype=half_dtype)++ points_v1 = depth_to_3d(depth, camera_matrix)+ points_v2 = depth_to_3d_v2(depth[:, 0], camera_matrix)+ assert points_v1.dtype == torch.float32+ assert points_v2.dtype == torch.float32++ # float64 reference on CPU: MPS has no float64 kernels+ x64 = (torch.arange(width, dtype=torch.float64) - 320.0) * 2.0 / 500.0+ self.assert_close(points_v2[..., 0].cpu().double(), x64[None, None].expand(1, 2, width), rtol=0, atol=5e-7)+ assert torch.equal(points_v1.permute(0, 2, 3, 1), points_v2)++ def test_uint16_depth_unprojects_like_int32_6148(self, device, dtype):+ # kornia#6148: uint16 is what a 16-bit millimetre depth PNG decodes to; it used to raise+ # NotImplementedError from arange_cpu because the grid was built in the depth's dtype. It now follows+ # the floating intrinsics exactly like the int32 arm of the integer-depth convention test.+ camera_matrix = _k_asymmetric(device, dtype)+ for depth_value in (1, 1000, 40000, 65535):+ depth = torch.full((1, 1, 2, 3), depth_value, device=device, dtype=torch.uint16)+ reference = torch.full((1, 1, 2, 3), depth_value, device=device, dtype=torch.int32)++ points = depth_to_3d(depth, camera_matrix)+ points_v2 = depth_to_3d_v2(depth[:, 0], camera_matrix)+ assert points.dtype == dtype+ assert torch.equal(points, depth_to_3d(reference, camera_matrix))+ assert torch.equal(points_v2, depth_to_3d_v2(reference[:, 0], camera_matrix))++ @pytest.mark.parametrize("depth_dtype", [torch.uint8, torch.int8])+ def test_8bit_depth_does_not_wrap_the_column_index_6148(self, depth_dtype, device, dtype):+ # A grid built in the depth's dtype wrapped the column index past 255 (uint8) or 127 (int8), so column 256+ # unprojected like column 0. The grid now follows the intrinsics, as it does for int32 depth.+ camera_matrix = _k_asymmetric(device, dtype)+ depth = torch.full((1, 1, 2, 300), 3, device=device, dtype=depth_dtype)+ reference = depth.to(torch.int32)+ assert torch.equal(depth_to_3d(depth, camera_matrix), depth_to_3d(reference, camera_matrix))+ assert torch.equal(depth_to_3d_v2(depth[:, 0], camera_matrix), depth_to_3d_v2(reference[:, 0], camera_matrix))++ def test_integer_depth_and_intrinsics_use_the_default_floating_dtype_6148(self, device, dtype):+ # Both inputs integer: promote_types does not support the unsigned/signed pair, so the grid falls back+ # to the default floating dtype instead of raising. MPS cannot compute in float64.+ if device.type == "mps":+ pytest.skip("float64 default dtype, which MPS does not compute in")+ depth = torch.full((1, 1, 2, 3), 2, device=device, dtype=torch.uint16)+ camera_matrix = torch.tensor([[[100, 0, 4], [0, 100, 3], [0, 0, 1]]], device=device, dtype=torch.int32)+ previous_dtype = torch.get_default_dtype()+ try:+ torch.set_default_dtype(torch.float64)+ points_v2 = depth_to_3d_v2(depth[:, 0], camera_matrix)+ assert points_v2.dtype == torch.float64+ expected = torch.tensor([-0.08, -0.06, 2.0], device=device, dtype=torch.float64)+ self.assert_close(points_v2[0, 0, 0], expected)+ finally:+ torch.set_default_dtype(previous_dtype)++ def test_all_half_inputs_keep_the_half_grid_6148(self, device, dtype):+ # An all-bfloat16 call keeps its bfloat16 grid (the wider half-precision policy belongs to #5814), so+ # only the mixed case changes. With fx = 1 and cx = 1, column 257 unprojects to x = 256 in exact+ # arithmetic, which a bfloat16 grid stores as 255 while a float32 computation cast back gives 256:+ # the pinned literal proves the grid itself stayed bfloat16, not a float32 pipeline narrowing late.+ camera_matrix = torch.tensor(+ [[[1.0, 0.0, 1.0], [0.0, 1.0, 0.5], [0.0, 0.0, 1.0]]], device=device, dtype=torch.bfloat16+ )+ depth = torch.full((1, 1, 2, 259), 1.0, device=device, dtype=torch.bfloat16)++ points_v1 = depth_to_3d(depth, camera_matrix)+ points_v2 = depth_to_3d_v2(depth[:, 0], camera_matrix)+ assert points_v2.dtype == torch.bfloat16+ assert points_v1[0, 0, 0, 257].item() == 255.0+ assert points_v2[0, 0, 257, 0].item() == 255.0++ def test_real_depth_with_complex_intrinsics_promotes_through_the_grid_6148(self, device, dtype):+ # A complex promotion keeps a real grid (arange has no complex kernels); the arithmetic still+ # promotes to complex, which also unblocks complex inputs that failed on main during grid+ # construction.+ camera_matrix = torch.eye(3, device=device, dtype=torch.complex64)[None]+ depth = torch.full((1, 1, 2, 3), 2.0, device=device, dtype=torch.float32)++ points = depth_to_3d(depth, camera_matrix)+ points_v2 = depth_to_3d_v2(depth[:, 0], camera_matrix)+ assert points.dtype == torch.complex64+ assert points_v2.dtype == torch.complex64+ expected = torch.tensor([0.0, 0.0, 2.0], device=device, dtype=torch.complex64)+ self.assert_close(points_v2[0, 0, 0], expected)++ def test_complex32_depth_with_half_intrinsics_unprojects_6148(self, device, dtype):+ # complex32 depth promotes with float16 intrinsics to complex32, which also has no arange kernel:+ # the grid stays real (float16) and only the final multiplication sees the complex depth. The+ # imaginary part reaches the output: at pixel (u=2, v=1) an identity camera unprojects z = 2+1j+ # to (x, y, z) = (2z, z, z) = (4+2j, 2+1j, 2+1j). Compared in complex64, because torch has no+ # ComplexHalf comparison kernels either.+ camera_matrix = torch.eye(3, device=device, dtype=torch.float16)[None]+ depth = torch.full((1, 1, 3, 4), 2 + 1j, device=device, dtype=torch.complex32)++ points = depth_to_3d(depth, camera_matrix)+ points_v2 = depth_to_3d_v2(depth[:, 0], camera_matrix)+ assert points.dtype == torch.complex32+ assert points_v2.dtype == torch.complex32+ expected = torch.tensor([4 + 2j, 2 + 1j, 2 + 1j], device=device, dtype=torch.complex64)+ self.assert_close(points[0, :, 1, 2].to(torch.complex64), expected)+ self.assert_close(points_v2[0, 1, 2].to(torch.complex64), expected)++ def test_all_complex32_inputs_get_a_real_grid_6148(self, device, dtype):+ # Two complex32 inputs cannot run through torch (no ComplexHalf division kernel), but the grid+ # dtype itself is well defined: the real component of the promotion, float16.+ from kornia.geometry.depth import _depth_grid_dtype++ depth = torch.empty(1, 2, 3, device=device, dtype=torch.complex32)+ camera_matrix = torch.empty(1, 3, 3, device=device, dtype=torch.complex32)++ assert _depth_grid_dtype(depth, camera_matrix) == torch.float16++ @pytest.mark.parametrize(+ "depth_dtype",+ [torch.float16, torch.float32, torch.int32, torch.bfloat16],+ )+ def test_float32_intrinsics_results_are_bitwise_unchanged_6148(self, depth_dtype, device, dtype):+ # Control: for every depth dtype whose old grid was already built in the dtype the promotion keeps,+ # every output bit is preserved. On the half profiles the fixture dtype matches the depth dtype, so+ # the promoted grid dtype is the same half and the comparison covers the all-half policy of #5814.+ camera_matrix = _k_asymmetric(device, dtype)+ depth_values = torch.rand(1, 1, 2, 6, device=device).mul(5).add(1)+ depth = depth_values.to(depth_dtype)++ points_v1 = depth_to_3d(depth, camera_matrix)+ points_v2 = depth_to_3d_v2(depth[:, 0], camera_matrix)+ old_grid = unproject_meshgrid(2, 6, camera_matrix, device=device, dtype=depth.dtype)+ expected_v2 = old_grid * depth[:, 0, ..., None]++ assert points_v1.dtype == expected_v2.dtype+ assert torch.equal(points_v1.permute(0, 2, 3, 1).contiguous(), expected_v2.contiguous())+ assert torch.equal(points_v2, expected_v2)+class TestUnprojectMeshgrid(BaseTester):def test_convention_returns_b_h_w_3_and_equals_depth_to_3d_v2_at_depth_one(self, device, dtype):@@ -555,6 +697,24 @@ class TestDepthToNormals(BaseTester):class TestWarpFrameDepth(BaseTester):+ @pytest.mark.parametrize("half_dtype", [torch.bfloat16, torch.float16])+ def test_half_depth_with_float32_intrinsics_is_the_identity_6148(self, half_dtype, device, dtype):+ # kornia#6148 on the wrapper path: warp_frame_depth reaches the mixed-dtype fix through+ # depth_to_3d_v2, so an identity warp with half-precision depth and float32 intrinsics and+ # transform reproduces the float32-depth image instead of sampling off-by-pixels. float16 holds the+ # column indices exactly up to 2048, so its case needs a wider image.+ height, width = 2, (640 if half_dtype == torch.bfloat16 else 2051)+ camera_matrix = torch.tensor(+ [[[500.0, 0.0, 320.0], [0.0, 500.0, 0.5], [0.0, 0.0, 1.0]]], device=device, dtype=torch.float32+ )+ image = torch.rand(1, 1, height, width, device=device, dtype=torch.float32)+ depth = torch.full((1, 1, height, width), 2.0, device=device, dtype=half_dtype)+ transform = torch.eye(4, device=device, dtype=torch.float32)[None]++ warped = warp_frame_depth(image, depth, transform, camera_matrix)+ assert warped.dtype == torch.float32+ self.assert_close(warped, image, rtol=0, atol=5e-4)+@pytest.mark.parametrize("normalize_points", [False, True])def test_jit(self, normalize_points, device, dtype):image = torch.rand(2, 3, 3, 4, device=device, dtype=dtype)