Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

Undistort 2D points function (#1026)

Jhacson Mezaf4bcc5ecd1fd
diff --git a/kornia/geometry/calibration/undistort.py b/kornia/geometry/calibration/undistort.py
new file mode 100644
index 000000000..3aa698af0
--- /dev/null
+++ b/kornia/geometry/calibration/undistort.py
@@ -0,0 +1,116 @@
+import torch
+
+
+# Based on https://github.com/opencv/opencv/blob/master/modules/calib3d/src/distortion_model.hpp#L75
+def inverseTiltProjection(taux: torch.Tensor, tauy: torch.Tensor) -> torch.Tensor:
+ r"""Estimate the inverse of the tilt projection matrix
+
+ Args:
+ taux (torch.Tensor): Rotation angle in radians around the :math:`x`-axis with shape :math:`(*, 1)`.
+ tauy (torch.Tensor): Rotation angle in radians around the :math:`y`-axis with shape :math:`(*, 1)`.
+
+ Returns:
+ torch.Tensor: Inverse tilt projection matrix with shape :math:`(*, 3, 3)`.
+ """
+ assert taux.dim() == tauy.dim()
+ assert taux.numel() == tauy.numel()
+
+ ndim = taux.dim()
+ taux = taux.reshape(-1)
+ tauy = tauy.reshape(-1)
+
+ cTx = torch.cos(taux)
+ sTx = torch.sin(taux)
+ cTy = torch.cos(tauy)
+ sTy = torch.sin(tauy)
+ zero = torch.zeros_like(cTx)
+ one = torch.ones_like(cTx)
+
+ Rx = torch.stack([one, zero, zero, zero, cTx, sTx, zero, -sTx, cTx], -1).reshape(-1, 3, 3)
+ Ry = torch.stack([cTy, zero, -sTy, zero, one, zero, sTy, zero, cTy], -1).reshape(-1, 3, 3)
+
+ R = Ry @ Rx
+ invR22 = 1 / R[..., 2, 2]
+ invPz = torch.stack(
+ [invR22, zero, R[..., 0, 2] * invR22, zero, invR22, R[..., 1, 2] * invR22, zero, zero, one], -1
+ ).reshape(-1, 3, 3)
+
+ invTilt = R.transpose(-1, -2) @ invPz
+ if ndim == 0:
+ invTilt = torch.squeeze(invTilt)
+
+ return invTilt
+
+
+# Based on https://github.com/opencv/opencv/blob/master/modules/calib3d/src/undistort.dispatch.cpp#L384
+def undistort_points(points: torch.Tensor, K: torch.Tensor, dist: torch.Tensor) -> torch.Tensor:
+ r"""Compensate for lens distortion a set of 2D image points. Radial :math:`(k_1, k_2, k_3, k_4, k_4, k_6)`,
+ tangential :math:`(p_1, p_2)`, thin prism :math:`(s_1, s_2, s_3, s_4)`, and tilt :math:`(\tau_x, \tau_y)`
+ distortion models are considered in this function.
+
+ Args:
+ points (torch.Tensor): Input image points with shape :math:`(*, N, 2)`.
+ K (torch.Tensor): Intrinsic camera matrix with shape :math:`(*, 3, 3)`.
+ dist (torch.Tensor): Distortion coefficients
+ :math:`(k_1,k_2,p_1,p_2[,k_3[,k_4,k_5,k_6[,s_1,s_2,s_3,s_4[,\tau_x,\tau_y]]]])`. This is
+ a vector with 4, 5, 8, 12 or 14 elements with shape :math:`(*, n)`
+
+ Returns:
+ torch.Tensor: Undistorted 2D points with shape :math:`(*, N, 2)`.
+ """
+ assert points.dim() >= 2 and points.shape[-1] == 2
+ assert K.shape[-2:] == (3, 3)
+ assert dist.shape[-1] in [4, 5, 8, 12, 14]
+
+ if dist.shape[-1] < 14:
+ dist = torch.nn.functional.pad(dist, [0, 14 - dist.shape[-1]])
+
+ # Convert 2D points from pixels to normalized camera coordinates
+ cx: torch.Tensor = K[..., 0:1, 2] # princial point in x (Bx1)
+ cy: torch.Tensor = K[..., 1:2, 2] # princial point in y (Bx1)
+ fx: torch.Tensor = K[..., 0:1, 0] # focal in x (Bx1)
+ fy: torch.Tensor = K[..., 1:2, 1] # focal in y (Bx1)
+ # This is equivalent to K^-1 [u,v,1]^T
+ x: torch.Tensor = (points[..., 0] - cx) / fx # (BxN - Bx1)/Bx1 -> BxN
+ y: torch.Tensor = (points[..., 1] - cy) / fy # (BxN - Bx1)/Bx1 -> BxN
+
+ # Compensate for tilt distortion
+ if torch.any(dist[..., 12] != 0) or torch.any(dist[..., 13] != 0):
+ invTilt = inverseTiltProjection(dist[..., 12], dist[..., 13])
+
+ # Transposed untilt points (instead of [x,y,1]^T, we obtain [x,y,1])
+ pointsUntilt = torch.stack([x, y, torch.ones(x.shape, device=x.device, dtype=x.dtype)], -1) @ invTilt.transpose(
+ -2, -1
+ )
+ x = pointsUntilt[..., 0] / pointsUntilt[..., 2]
+ y = pointsUntilt[..., 1] / pointsUntilt[..., 2]
+
+ # Iteratively undistort points
+ x0, y0 = x, y
+ for _ in range(5):
+ r2 = x * x + y * y
+
+ inv_rad_poly = (1 + dist[..., 5:6] * r2 + dist[..., 6:7] * r2 * r2 + dist[..., 7:8] * r2 ** 3) / (
+ 1 + dist[..., 0:1] * r2 + dist[..., 1:2] * r2 * r2 + dist[..., 4:5] * r2 ** 3
+ )
+ deltaX = (
+ 2 * dist[..., 2:3] * x * y
+ + dist[..., 3:4] * (r2 + 2 * x * x)
+ + dist[..., 8:9] * r2
+ + dist[..., 9:10] * r2 * r2
+ )
+ deltaY = (
+ dist[..., 2:3] * (r2 + 2 * y * y)
+ + 2 * dist[..., 3:4] * x * y
+ + dist[..., 10:11] * r2
+ + dist[..., 11:12] * r2 * r2
+ )
+
+ x = (x0 - deltaX) * inv_rad_poly
+ y = (y0 - deltaY) * inv_rad_poly
+
+ # Covert points from normalized camera coordinates to pixel coordinates
+ x = fx * x + cx
+ y = fy * y + cy
+
+ return torch.stack([x, y], -1)
diff --git a/test/geometry/calibration/test_undistort.py b/test/geometry/calibration/test_undistort.py
new file mode 100644
index 000000000..a816e92de
--- /dev/null
+++ b/test/geometry/calibration/test_undistort.py
@@ -0,0 +1,193 @@
+import pytest
+import torch
+from torch.autograd import gradcheck
+from torch.testing import assert_allclose
+
+from kornia.geometry.calibration.undistort import undistort_points
+
+
+class TestUndistortion:
+ def test_smoke(self, device, dtype):
+ points = torch.rand(1, 2, device=device, dtype=dtype)
+ K = torch.rand(3, 3, device=device, dtype=dtype)
+ distCoeff = torch.rand(4, device=device, dtype=dtype)
+ pointsu = undistort_points(points, K, distCoeff)
+ assert points.shape == pointsu.shape
+
+ points = torch.rand(1, 1, 2, device=device, dtype=dtype)
+ K = torch.rand(1, 3, 3, device=device, dtype=dtype)
+ distCoeff = torch.rand(1, 4, device=device, dtype=dtype)
+ pointsu = undistort_points(points, K, distCoeff)
+ assert points.shape == pointsu.shape
+
+ @pytest.mark.parametrize(
+ "batch_size, num_points, num_distcoeff", [(1, 3, 4), (2, 4, 5), (3, 5, 8), (4, 6, 12), (5, 7, 14)]
+ )
+ def test_shape(self, batch_size, num_points, num_distcoeff, device, dtype):
+ B, N, Ndist = batch_size, num_points, num_distcoeff
+
+ points = torch.rand(B, N, 2, device=device, dtype=dtype)
+ K = torch.rand(B, 3, 3, device=device, dtype=dtype)
+ distCoeff = torch.rand(B, Ndist, device=device, dtype=dtype)
+
+ pointsu = undistort_points(points, K, distCoeff)
+ assert points.shape == (B, N, 2)
+
+ def test_opencv_five_coeff(self, device, dtype):
+ # Test using 5 distortion coefficients
+ pts = torch.tensor(
+ [[1028.0374, 788.7520], [1025.1218, 716.8726], [1022.1792, 645.1857]], device=device, dtype=dtype
+ )
+
+ K = torch.tensor(
+ [[1.7315e03, 0.0000e00, 6.2289e02], [0.0000e00, 1.7320e03, 5.3537e02], [0.0000e00, 0.0000e00, 1.0000e00]],
+ device=device,
+ dtype=dtype,
+ )
+
+ dist = torch.tensor([-0.1007, 0.2650, -0.0018, 0.0007, -0.2597], device=device, dtype=dtype)
+
+ # Expected ouput generated with OpenCV:
+ # import cv2
+ # ptsu_expected = cv2.undistortPoints(pts.numpy().reshape(-1,1,2), K.numpy(),
+ # dist1.numpy(), None, None, K.numpy()).reshape(-1,2)
+ ptsu_expected = torch.tensor(
+ [[1030.5992, 790.65533], [1027.3059, 718.10020], [1024.0700, 645.90600]], device=device, dtype=dtype
+ )
+ ptsu = undistort_points(pts, K, dist)
+ assert_allclose(ptsu, ptsu_expected, rtol=1e-4, atol=1e-4)
+
+ def test_opencv_all_coeff(self, device, dtype):
+ # Test using 14 distortion coefficients
+ pts = torch.tensor(
+ [[1028.0374, 788.7520], [1025.1218, 716.8726], [1022.1792, 645.1857]], device=device, dtype=dtype
+ )
+
+ K = torch.tensor(
+ [[1.7315e03, 0.0000e00, 6.2289e02], [0.0000e00, 1.7320e03, 5.3537e02], [0.0000e00, 0.0000e00, 1.0000e00]],
+ device=device,
+ dtype=dtype,
+ )
+
+ dist = torch.tensor(
+ [
+ -5.6388e-02,
+ 2.3881e-01,
+ 8.3374e-02,
+ 2.0710e-03,
+ 7.1349e00,
+ 5.6335e-02,
+ -3.1738e-01,
+ 4.9981e00,
+ -4.0287e-03,
+ -2.8246e-02,
+ -8.6064e-02,
+ 1.5543e-02,
+ -1.7322e-01,
+ 2.3154e-03,
+ ],
+ device=device,
+ dtype=dtype,
+ )
+
+ # Expected ouput generated with OpenCV:
+ # import cv2
+ # ptsu_expected = cv2.undistortPoints(pts.numpy().reshape(-1,1,2), K.numpy(),
+ # dist2.numpy(), None, None, K.numpy()).reshape(-1,2)
+ ptsu_expected = torch.tensor(
+ [[1030.8245, 786.3807], [1027.5505, 715.0732], [1024.2753, 644.0319]], device=device, dtype=dtype
+ )
+ ptsu = undistort_points(pts, K, dist)
+ assert_allclose(ptsu, ptsu_expected, rtol=1e-4, atol=1e-4)
+
+ def test_opencv_stereo(self, device, dtype):
+ # Udistort stereo points with data given in two batches using 14 distortion coefficients
+ pts = torch.tensor(
+ [
+ [[1028.0374, 788.7520], [1025.1218, 716.8726], [1022.1792, 645.1857]],
+ [[345.9135, 847.9113], [344.0880, 773.9890], [342.2381, 700.3029]],
+ ],
+ device=device,
+ dtype=dtype,
+ )
+
+ K = torch.tensor(
+ [
+ [
+ [3.3197e03, 0.0000e00, 6.1813e02],
+ [0.0000e00, 3.3309e03, 5.2281e02],
+ [0.0000e00, 0.0000e00, 1.0000e00],
+ ],
+ [
+ [1.9206e03, 0.0000e00, 6.1395e02],
+ [0.0000e00, 1.9265e03, 7.7164e02],
+ [0.0000e00, 0.0000e00, 1.0000e00],
+ ],
+ ],
+ device=device,
+ dtype=dtype,
+ )
+
+ dist = torch.tensor(
+ [
+ [
+ -5.6388e-02,
+ 2.3881e-01,
+ 8.3374e-02,
+ 2.0710e-03,
+ 7.1349e00,
+ 5.6335e-02,
+ -3.1738e-01,
+ 4.9981e00,
+ -4.0287e-03,
+ -2.8246e-02,
+ -8.6064e-02,
+ 1.5543e-02,
+ -1.7322e-01,
+ 2.3154e-03,
+ ],
+ [
+ 1.4050e-03,
+ -3.0691e00,
+ -1.0209e-01,
+ -2.3687e-02,
+ -1.7082e02,
+ 4.3593e-03,
+ -3.1904e00,
+ -1.7050e02,
+ 1.7854e-02,
+ 1.8999e-02,
+ 9.9122e-02,
+ 3.6675e-02,
+ 3.0816e-03,
+ -5.7133e-02,
+ ],
+ ],
+ device=device,
+ dtype=dtype,
+ )
+
+ # Expected ouput generated with OpenCV:
+ # import cv2
+ # ptsu_expected1 = cv2.undistortPoints(pts[0].numpy().reshape(-1,1,2), K[0].numpy(),
+ # dist[0].numpy(), None, None, K[0].numpy()).reshape(-1,2)
+ # ptsu_expected2 = cv2.undistortPoints(pts[1].numpy().reshape(-1,1,2), K[1].numpy(),
+ # dist[1].numpy(), None, None, K[1].numpy()).reshape(-1,2)
+ ptsu_expected1 = torch.tensor(
+ [[1029.3234, 785.4813], [1026.1599, 714.3689], [1023.02045, 643.5359]], device=device, dtype=dtype
+ )
+
+ ptsu_expected2 = torch.tensor(
+ [[344.04456, 848.7696], [344.27606, 774.1254], [344.47018, 700.8522]], device=device, dtype=dtype
+ )
+
+ ptsu = undistort_points(pts, K, dist)
+ assert_allclose(ptsu[0], ptsu_expected1, rtol=1e-4, atol=1e-4)
+ assert_allclose(ptsu[1], ptsu_expected2, rtol=1e-4, atol=1e-4)
+
+ def test_gradcheck(self, device):
+ points = torch.rand(1, 8, 2, device=device, dtype=torch.float64, requires_grad=True)
+ K = torch.rand(1, 3, 3, device=device, dtype=torch.float64)
+ distCoeff = torch.rand(1, 4, device=device, dtype=torch.float64)
+
+ assert gradcheck(undistort_points, (points, K, distCoeff), raise_exception=True)