Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(geometry): build undistort_image's half-precision map in float32 (#6577)

Viranshul-Pb73e4f4ca1cf
diff --git a/README.md b/README.md
index bc4f3bac2..2b6e9c332 100644
--- a/README.md
+++ b/README.md
@@ -147,7 +147,7 @@ measurement of the whole test suite is [below](#cuda-test-suite-measurement).
| `kornia.augmentation` | ⚠️ | ⚠️ | 59 / 47 | float16: container autocast/runtime errors and accuracy; both dtypes: 3D backward and random-generator accuracy |
| `kornia.geometry.transform` | ⚠️ | ⚠️ | 31 / 31 | Rotation matrices, affine/perspective warps and homography-warper accuracy |
| `kornia.geometry.camera` | ⚠️ | ⚠️ | 13 / 23 | Projection, distortion round trips and stereo reprojection; includes test-side dtype assertions |
-| `kornia.geometry.calibration` | ⚠️ | ⚠️ | 13 / 12 | solve_pnp_dlt rejects half inputs; undistort_points accuracy |
+| `kornia.geometry.calibration` | ⚠️ | ⚠️ | 12 / 12 | solve_pnp_dlt rejects half inputs; undistort_points accuracy |
| `kornia.geometry.epipolar` | ⚠️ | ⚠️ | 36 / 36 | Essential-matrix decomposition/motion and KRt_from_projection lack CPU half kernels; fundamental-matrix accuracy |
| `kornia.geometry.homography` | ⚠️ | ⚠️ | 10 / 16 | DLT solver accuracy, including iterated and line-based variants |
| `kornia.geometry.liegroup` | ✅ | ✅ | 0 / 0 | So2/Se2 reject bfloat16 rotation construction: PyTorch has no complex bfloat16 dtype; these expected errors/skips are outside the manifests |
diff --git a/changelog.d/6577.fixed.md b/changelog.d/6577.fixed.md
new file mode 100644
index 000000000..cbbf0001b
--- /dev/null
+++ b/changelog.d/6577.fixed.md
@@ -0,0 +1 @@
+`undistort_image` builds its sampling map, distorts it and samples in float32 for float16 and bfloat16 images, and returns the image dtype. The map used to be built in the image dtype, where pixel coordinates round to half pixels (float16, from 512 px) or whole pixels (bfloat16, from 128 px): at 640 x 480 with OpenCV-style radial distortion the image was sampled up to 0.79 px (float16) and 6.3 px (bfloat16) away from the float64 positions, on CPU and CUDA. A half image with `K` and `dist` of another dtype, such as float32 or float64, is now also accepted instead of raising a dtype mismatch.
diff --git a/docs/source/get-started/precision.rst b/docs/source/get-started/precision.rst
index 5d46594a0..4621375bb 100644
--- a/docs/source/get-started/precision.rst
+++ b/docs/source/get-started/precision.rst
@@ -61,7 +61,7 @@ measurement of the whole test suite is in :ref:`cuda-test-suite-measurement`.
* - ``kornia.geometry.calibration``
- ⚠️
- ⚠️
- - 13 / 12
+ - 12 / 12
- solve_pnp_dlt rejects half inputs; undistort_points accuracy
* - ``kornia.geometry.epipolar``
- ⚠️
diff --git a/kornia/geometry/calibration/undistort.py b/kornia/geometry/calibration/undistort.py
index be5254098..109de12dd 100644
--- a/kornia/geometry/calibration/undistort.py
+++ b/kornia/geometry/calibration/undistort.py
@@ -215,6 +215,9 @@ def undistort_image(image: torch.Tensor, K: torch.Tensor, dist: torch.Tensor) ->
- the sampling map applies :func:`~kornia.geometry.calibration.distort_points` to the integer pixel
centres (see :class:`~kornia.geometry.camera.pinhole.PinholeCamera`) and is resampled bilinearly with
a fixed ``align_corners=True``, so all-zero coefficients return the input only to rounding.
+ - a float16 or bfloat16 image builds the map, distorts it and samples in float32, with ``K`` and ``dist``
+ cast to float32, and returns the image dtype; in half precision the pixel coordinates themselves round to
+ half pixels (float16, from 512) or whole pixels (bfloat16, from 128).
Args:
image: Input image with shape ``(*, C, H, W)``.
@@ -266,8 +269,14 @@ def undistort_image(image: torch.Tensor, K: torch.Tensor, dist: torch.Tensor) ->
channels, rows, cols = image.shape[-3:]
B = image.numel() // (channels * rows * cols)
+ # Pixel coordinates reach the image size, where float16 rounds them to half pixels from 512 and bfloat16 to whole
+ # pixels from 128, so a half image builds and distorts its map and samples in float32, as the warps do.
+ work_dtype = torch.float32 if image.dtype in (torch.float16, torch.bfloat16) else image.dtype
+ if work_dtype != image.dtype:
+ K, dist = K.to(work_dtype), dist.to(work_dtype)
+
# Create point coordinates for each pixel of the image
- xy_grid: torch.Tensor = create_meshgrid(rows, cols, False, image.device, image.dtype)
+ xy_grid: torch.Tensor = create_meshgrid(rows, cols, False, image.device, work_dtype)
pts = xy_grid.reshape(-1, 2) # (rows*cols)x2 matrix of pixel coordinates
# Distort points and define maps
@@ -276,6 +285,6 @@ def undistort_image(image: torch.Tensor, K: torch.Tensor, dist: torch.Tensor) ->
mapy: torch.Tensor = ptsd[..., 1].reshape(B, rows, cols) # B x rows x cols, float
# Remap image to undistort
- out = remap(image.reshape(B, channels, rows, cols), mapx, mapy, align_corners=True)
+ out = remap(image.reshape(B, channels, rows, cols).to(work_dtype), mapx, mapy, align_corners=True)
- return out.view_as(image)
+ return out.to(image.dtype).view_as(image)
diff --git a/testing/half_precision_xfails/cpu_float16.txt b/testing/half_precision_xfails/cpu_float16.txt
index aa4e463f1..3b95b90da 100644
--- a/testing/half_precision_xfails/cpu_float16.txt
+++ b/testing/half_precision_xfails/cpu_float16.txt
@@ -78,7 +78,6 @@ call kornia.core.exceptions.BaseError tests/geometry/calibration/test_pnp.py::Te
call kornia.core.exceptions.BaseError tests/geometry/calibration/test_pnp.py::TestSolvePnpDlt::test_project[cpu-float16-6]
call kornia.core.exceptions.BaseError tests/geometry/calibration/test_pnp.py::TestSolvePnpDlt::test_smoke[cpu-float16-20]
call kornia.core.exceptions.BaseError tests/geometry/calibration/test_pnp.py::TestSolvePnpDlt::test_smoke[cpu-float16-6]
-call builtins.AssertionError tests/geometry/calibration/test_undistort.py::TestUndistortImage::test_shape_extra_dims[cpu-float16]
call builtins.AssertionError tests/geometry/calibration/test_undistort.py::TestUndistortPoints::test_opencv_all_coeff[cpu-float16]
call builtins.AssertionError tests/geometry/calibration/test_undistort.py::TestUndistortPoints::test_opencv_five_coeff[cpu-float16]
call builtins.AssertionError tests/geometry/calibration/test_undistort.py::TestUndistortPoints::test_opencv_stereo[cpu-float16]
diff --git a/tests/geometry/calibration/test_undistort.py b/tests/geometry/calibration/test_undistort.py
index fdc26fc36..18e2a2c6a 100644
--- a/tests/geometry/calibration/test_undistort.py
+++ b/tests/geometry/calibration/test_undistort.py
@@ -574,19 +574,65 @@ class TestUndistortImage(BaseTester):
def test_convention_resamples_with_align_corners_true(self, device, dtype):
# undistort_image is remap(image, mapx, mapy, align_corners=True) over the map distort_points produces
# on the create_meshgrid pixel grid; align_corners is fixed and not exposed. The align_corners=False arm
- # must differ, so the pin discriminates between the two settings.
+ # must differ, so the pin discriminates between the two settings. A half image builds the map and samples
+ # in float32.
image = _ramp_image(1, 3, 5, 7, device, dtype)
K = _k_short_focal(device, dtype)
dist = torch.tensor([[0.1, 0.01, 0.001, 0.001]], device=device, dtype=dtype)
- grid = create_meshgrid(5, 7, False, device, dtype).reshape(-1, 2)
- distorted = distort_points(grid, K, dist)
+ work = torch.float32 if dtype in (torch.float16, torch.bfloat16) else dtype
+ grid = create_meshgrid(5, 7, False, device, work).reshape(-1, 2)
+ distorted = distort_points(grid, K.to(work), dist.to(work))
assert not torch.allclose(distorted.float(), grid.float())
mapx = distorted[..., 0].reshape(1, 5, 7)
mapy = distorted[..., 1].reshape(1, 5, 7)
out = undistort_image(image, K, dist)
assert not torch.allclose(out.float(), image.float())
- self.assert_close(out, remap(image, mapx, mapy, align_corners=True), atol=0.0, rtol=0.0)
- assert not torch.allclose(out.float(), remap(image, mapx, mapy, align_corners=False).float())
+ expected = remap(image.to(work), mapx, mapy, align_corners=True).to(dtype)
+ self.assert_close(out, expected, atol=0.0, rtol=0.0)
+ assert not torch.allclose(out.float(), remap(image.to(work), mapx, mapy, align_corners=False).float())
+
+ def test_convention_half_image_samples_at_float32_positions(self, device, dtype):
+ # In half precision the pixel coordinates of a 640 px row round to half pixels (float16) or to 4 px
+ # (bfloat16), so a map built in the image dtype sampled up to 0.79 px (float16) and 6.3 px (bfloat16) away
+ # from the float64 positions. On a horizontal ramp the intensity error times the width is that position
+ # error; what remains here is the rounding of the input and output ramps, at most half a step of the values
+ # in [0.5, 1) twice over: 0.31 px in float16 and 2.5 px in bfloat16.
+ # The float64 reference is built on CPU: MPS has no float64.
+ H, W = 480, 640
+ ramp = (torch.arange(W, dtype=torch.float64) / W).expand(1, 1, H, W)
+ K = torch.tensor([[[500.0, 0.0, 320.0], [0.0, 500.0, 240.0], [0.0, 0.0, 1.0]]], dtype=torch.float64)
+ dist = torch.tensor([[-0.2, 0.05, 0.001, 0.001, 0.0]], dtype=torch.float64)
+ expected = undistort_image(ramp, K, dist)
+
+ out = undistort_image(
+ ramp.to(device=device, dtype=dtype), K.to(device=device, dtype=dtype), dist.to(device=device, dtype=dtype)
+ )
+
+ assert out.dtype == dtype
+ error_px = (out.cpu().double() - expected)[..., 40:-40, 40:-40].abs().amax() * W
+ bound = {torch.float16: 0.4, torch.bfloat16: 2.5}.get(dtype, 1e-3)
+ assert error_px < bound, f"sampled {error_px:.3f} px away from the float64 positions"
+
+ def test_convention_half_image_keeps_the_precision_of_float32_calibration(self, device, dtype):
+ # A half image takes K and dist of another dtype and keeps their precision: this focal length and these
+ # coefficients do not survive a round trip through half, so the map below would change if they went through it.
+ if dtype not in (torch.float16, torch.bfloat16):
+ pytest.skip("only a half image builds its map in another dtype than its own")
+ image = _ramp_image(1, 3, 50, 70, device, dtype)
+ K = torch.tensor([[[60.3, 0.0, 35.1], [0.0, 60.7, 25.3], [0.0, 0.0, 1.0]]], device=device)
+ dist = torch.tensor([[-0.2013, 0.0517, 0.0011, 0.0013]], device=device)
+ grid = create_meshgrid(50, 70, False, device, torch.float32).reshape(-1, 2)
+ distorted = distort_points(grid, K, dist)
+ expected = remap(
+ image.float(),
+ distorted[..., 0].reshape(1, 50, 70),
+ distorted[..., 1].reshape(1, 50, 70),
+ align_corners=True,
+ )
+ out = undistort_image(image, K, dist)
+ assert out.dtype == dtype
+ self.assert_close(out, expected.to(dtype), atol=0.0, rtol=0.0)
+ assert not torch.equal(out, undistort_image(image, K.to(dtype), dist.to(dtype)))
def test_gradcheck(self, device):
im = torch.rand(1, 1, 15, 15, device=device, dtype=torch.float64, requires_grad=True)