π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
Add ``undistort_image`` function (#1303)
Jhacson Meza2ccb1c138e11
diff --git a/docs/source/geometry.calibration.rst b/docs/source/geometry.calibration.rstindex 2ba8b2d39..2d4fa5dea 100644--- a/docs/source/geometry.calibration.rst+++ b/docs/source/geometry.calibration.rst@@ -5,11 +5,120 @@ kornia.geometry.calibrationModule with useful functionalities for camera calibration.+The pinhole model is an ideal projection model that not considers lens distortion for the projection of a 3D point :math:`(X, Y, Z)` onto the image plane. To model the distortion of a projected 2D pixel point :math:`(u,v)` with the linear pinhole model, we need first to estimate the normalized 2D points coordinates :math:`(\bar{u}, \bar{v})`. For that, we can use the calibration matrix :math:`\mathbf{K}` with the following expression++.. math::+ \begin{align}+ \begin{bmatrix}+ \bar{u}\\+ \bar{v}\\+ 1+ \end{bmatrix} = \mathbf{K}^{-1} \begin{bmatrix}+ u \\+ v \\+ 1+ \end{bmatrix} \enspace,+ \end{align}+which is equivalent to directly using the internal parameters: focals :math:`f_u, f_v` and principal point :math:`(u_0, v_0)` to estimated the normalized coordinates++.. math::+ \begin{equation}+ \bar{u} = (u - u_0)/f_u \enspace, \\+ \bar{v} = (v - v_0)/f_v \enspace.+ \end{equation}++The normalized distorted point :math:`(\bar{u}_d, \bar{v}_d)` is given by++.. math::+ \begin{align}+ \begin{bmatrix}+ \bar{u}_d\\+ \bar{v}_d+ \end{bmatrix} = \dfrac{1+k_1r^2+k_2r^4+k_3r^6}{1+k_4r^2+k_5r^4+k_6r^6} \begin{bmatrix}+ \bar{u}\\+ \bar{v}+ \end{bmatrix} ++ \begin{bmatrix}+ 2p_1\bar{u}\bar{v} + p_2(r^2 + 2\bar{u}^2) + s_1r^2 + s_2r^4\\+ 2p_2\bar{u}\bar{v} + p_1(r^2 + 2\bar{v}^2) + s_3r^2 + s_4r^4+ \end{bmatrix} \enspace,+ \end{align}++where :math:`r = \bar{u}^2 + \bar{v}^2`. With this model we consider radial :math:`(k_1, k_2, k_3, k_4, k_4, k_6)`, tangential :math:`(p_1, p_2)`, and thin prism :math:`(s_1, s_2, s_3, s_4)` distortion. If we want to consider tilt distortion :math:`(\tau_x, \tau_y)`, we need an additional step where we estimate a point :math:`(\bar{u}'_d, \bar{v}'_d)`++.. math::+ \begin{align}+ \begin{bmatrix}+ \bar{u}'_d\\+ \bar{v}'_d\\+ 1+ \end{bmatrix} = \begin{bmatrix}+ \mathbf{R}_{33}(\tau_x, \tau_y) & 0 & -\mathbf{R}_{13}(\tau_x, \tau_y)\\+ 0 & \mathbf{R}_{33}(\tau_x, \tau_y) & -\mathbf{R}_{23}(\tau_x, \tau_y)\\+ 0 & 0 & 1+ \end{bmatrix}+ \mathbf{R}(\tau_x, \tau_y) \begin{bmatrix}+ \bar{u}_d \\+ \bar{v}_d \\+ 1+ \end{bmatrix} \enspace,+ \end{align}++where :math:`\mathbf{R}(\tau_x, \tau_y)` is a 3D rotation matrix defined by an :math:`X` and :math:`Y` rotation given by the angles :math:`\tau_x` and :math:`\tau_y`. Furthermore, :math:`\mathbf{R}_{ij}(\tau_x, \tau_y)` represent the :math:`i`-th row and :math:`j`-th column from :math:`\mathbf{R}(\tau_x, \tau_y)` matrix.++.. math::+ \begin{align}+ \mathbf{R}(\tau_x, \tau_y) =+ \begin{bmatrix}+ \cos \tau_y & 0 & -\sin \tau_y \\+ 0 & 1 & 0 \\+ \sin \tau_y & 0 & \cos \tau_y+ \end{bmatrix}+ \begin{bmatrix}+ 1 & 0 & 0 \\+ 0 & \cos \tau_x & \sin \tau_x \\+ 0 & -\sin \tau_x & \cos \tau_x+ \end{bmatrix} \enspace.+ \end{align}+++Finally, we just need to come back to the original (unnormalized) pixel space. For that we can use the intrinsic matrix++.. math::+ \begin{align}+ \begin{bmatrix}+ u_d\\+ v_d\\+ 1+ \end{bmatrix} = \mathbf{K} \begin{bmatrix}+ \bar{u}'_d\\+ \bar{v}'_d\\+ 1+ \end{bmatrix} \enspace,+ \end{align}+++which is equivalent to++.. math::+ \begin{equation}+ u_d = f_u \bar{u}'_d + u_0 \enspace, \\+ v_d = f_v \bar{v}'_d + v_0 \enspace.+ \end{equation}+Undistortion------------+To compensate for lens distortion a set of 2D points, i.e., to estimate the undistorted coordinates for a given set of distorted points, we need to inverse the previously explained distortion model. For the case of undistorting an image, instead of estimating the undistorted location for each pixel, we distort each pixel in the destination image (final undistorted image) to match them with the input image. We finally interpolate the intensity values at each pixel.++.. autofunction:: undistort_image+.. autofunction:: undistort_points+.. autofunction:: distort_points++.. autofunction:: tilt_projection+Perspective-n-Point (PnP)-------------------------diff --git a/kornia/geometry/calibration/__init__.py b/kornia/geometry/calibration/__init__.pyindex 115f7605d..3d0403027 100644--- a/kornia/geometry/calibration/__init__.py+++ b/kornia/geometry/calibration/__init__.py@@ -1,2 +1,3 @@+from kornia.geometry.calibration.distort import *from kornia.geometry.calibration.pnp import *from kornia.geometry.calibration.undistort import *diff --git a/kornia/geometry/calibration/distort.py b/kornia/geometry/calibration/distort.pynew file mode 100644index 000000000..c1388fd41--- /dev/null+++ b/kornia/geometry/calibration/distort.py@@ -0,0 +1,143 @@+import torch++__all__ = [+ "tilt_projection",+ "distort_points",+]+++# Based on https://github.com/opencv/opencv/blob/master/modules/calib3d/src/distortion_model.hpp#L75+def tilt_projection(taux: torch.Tensor, tauy: torch.Tensor, return_inverse: bool = False) -> torch.Tensor:+ r"""Estimate the tilt projection matrix or the inverse tilt projection matrix.++ Args:+ taux: Rotation angle in radians around the :math:`x`-axis with shape :math:`(*, 1)`.+ tauy: Rotation angle in radians around the :math:`y`-axis with shape :math:`(*, 1)`.+ return_inverse: False to obtain the the tilt projection matrix. True for the inverse matrix.++ Returns:+ torch.Tensor: Inverse tilt projection matrix with shape :math:`(*, 3, 3)`.+ """+ if taux.shape != tauy.shape:+ raise ValueError(f'Shape of taux {taux.shape} and tauy {tauy.shape} do not match.')++ ndim: int = 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++ if return_inverse:+ 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)++ inv_tilt = R.transpose(-1, -2) @ invPz+ if ndim == 0:+ inv_tilt = torch.squeeze(inv_tilt)++ return inv_tilt++ Pz = torch.stack(+ [R[..., 2, 2], zero, -R[..., 0, 2], zero, R[..., 2, 2], -R[..., 1, 2], zero, zero, one], -1+ ).reshape(-1, 3, 3)++ tilt = Pz @ R.transpose(-1, -2)+ if ndim == 0:+ tilt = torch.squeeze(tilt)++ return tilt+++def distort_points(points: torch.Tensor, K: torch.Tensor, dist: torch.Tensor) -> torch.Tensor:+ r"""Distortion of a set of 2D points based on the lens distortion model.++ 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: Input image points with shape :math:`(*, N, 2)`.+ K: Intrinsic camera matrix with shape :math:`(*, 3, 3)`.+ dist: 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:+ Undistorted 2D points with shape :math:`(*, N, 2)`.++ Example:+ >>> points = torch.rand(1, 1, 2)+ >>> K = torch.eye(3)[None]+ >>> dist_coeff = torch.rand(1, 4)+ >>> distort_points(points, K, dist_coeff)+ tensor([[[3.6138, 5.4226]]])++ """+ if points.dim() < 2 and points.shape[-1] != 2:+ raise ValueError(f'points shape is invalid. Got {points.shape}.')++ if K.shape[-2:] != (3, 3):+ raise ValueError(f'K matrix shape is invalid. Got {K.shape}.')++ if dist.shape[-1] not in [4, 5, 8, 12, 14]:+ raise ValueError(f'Invalid number of distortion coefficients. Got {dist.shape[-1]}')++ # Adding zeros to obtain vector with 14 coeffs.+ 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 or (N,)+ y: torch.Tensor = (points[..., 1] - cy) / fy # (BxN - Bx1)/Bx1 -> BxN or (N,)++ # Distort points+ r2 = x * x + y * y++ rad_poly = (1 + dist[..., 0:1] * r2 + dist[..., 1:2] * r2 * r2 + dist[..., 4:5] * r2 ** 3) / (+ 1 + dist[..., 5:6] * r2 + dist[..., 6:7] * r2 * r2 + dist[..., 7:8] * r2 ** 3+ )+ xd = (+ x * rad_poly+ + 2 * dist[..., 2:3] * x * y+ + dist[..., 3:4] * (r2 + 2 * x * x)+ + dist[..., 8:9] * r2+ + dist[..., 9:10] * r2 * r2+ )+ yd = (+ y * rad_poly+ + dist[..., 2:3] * (r2 + 2 * y * y)+ + 2 * dist[..., 3:4] * x * y+ + dist[..., 10:11] * r2+ + dist[..., 11:12] * r2 * r2+ )++ # Compensate for tilt distortion+ if torch.any(dist[..., 12] != 0) or torch.any(dist[..., 13] != 0):+ tilt = tilt_projection(dist[..., 12], dist[..., 13])++ # Transposed untilt points (instead of [x,y,1]^T, we obtain [x,y,1])+ points_untilt = torch.stack([xd, yd, torch.ones_like(xd)], -1) @ tilt.transpose(-2, -1)+ xd = points_untilt[..., 0] / points_untilt[..., 2]+ yd = points_untilt[..., 1] / points_untilt[..., 2]++ # Convert points from normalized camera coordinates to pixel coordinates+ x = fx * xd + cx+ y = fy * yd + cy++ return torch.stack([x, y], -1)diff --git a/kornia/geometry/calibration/pnp.py b/kornia/geometry/calibration/pnp.pyindex 916545bc5..d49b7fa0e 100644--- a/kornia/geometry/calibration/pnp.py+++ b/kornia/geometry/calibration/pnp.py@@ -4,7 +4,11 @@ import torchimport korniafrom kornia.geometry.conversions import convert_points_to_homogeneous-from kornia.geometry.linalg import compose_transformations, transform_points+from kornia.geometry.linalg import transform_points++__all__ = [+ "solve_pnp_dlt",+]def _mean_isotropic_scale_normalize(diff --git a/kornia/geometry/calibration/undistort.py b/kornia/geometry/calibration/undistort.pyindex aa2f1b348..9a0685d52 100644--- a/kornia/geometry/calibration/undistort.py+++ b/kornia/geometry/calibration/undistort.py@@ -1,47 +1,14 @@import torch+from kornia.geometry.calibration.distort import distort_points, tilt_projection+from kornia.geometry.linalg import transform_points+from kornia.geometry.transform.imgwarp import remap+from kornia.utils import create_meshgrid-# 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: Rotation angle in radians around the :math:`x`-axis with shape :math:`(*, 1)`.- tauy: Rotation angle in radians around the :math:`y`-axis with shape :math:`(*, 1)`.-- Returns:- Inverse tilt projection matrix with shape :math:`(*, 3, 3)`.- """- if taux.dim() != tauy.dim():- raise AssertionError- if taux.numel() != tauy.numel():- raise AssertionError-- 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+__all__ = [+ "undistort_points",+ "undistort_image",+]# Based on https://github.com/opencv/opencv/blob/master/modules/calib3d/src/undistort.dispatch.cpp#L384@@ -57,28 +24,32 @@ def undistort_points(points: torch.Tensor, K: torch.Tensor, dist: torch.Tensor)K: Intrinsic camera matrix with shape :math:`(*, 3, 3)`.dist: 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)`+ a vector with 4, 5, 8, 12 or 14 elements with shape :math:`(*, n)`.Returns:Undistorted 2D points with shape :math:`(*, N, 2)`.Example:+ >>> _ = torch.manual_seed(0)>>> x = torch.rand(1, 4, 2)>>> K = torch.eye(3)[None]>>> dist = torch.rand(1, 4)>>> undistort_points(x, K, dist)- tensor([[[ 0.6198, 0.5452],- [ 0.7274, 0.6173],- [ 0.7422, -0.7141],- [ 0.5008, -0.1313]]])+ tensor([[[-0.1513, -0.1165],+ [ 0.0711, 0.1100],+ [-0.0697, 0.0228],+ [-0.1843, -0.1606]]])"""- if not (points.dim() >= 2 and points.shape[-1] == 2):- raise AssertionError+ if points.dim() < 2 and points.shape[-1] != 2:+ raise ValueError(f'points shape is invalid. Got {points.shape}.')+if K.shape[-2:] != (3, 3):- raise AssertionError+ raise ValueError(f'K matrix shape is invalid. Got {K.shape}.')+if dist.shape[-1] not in [4, 5, 8, 12, 14]:- raise AssertionError+ raise ValueError(f"Invalid number of distortion coefficients. Got {dist.shape[-1]}")+ # Adding zeros to obtain vector with 14 coeffs.if dist.shape[-1] < 14:dist = torch.nn.functional.pad(dist, [0, 14 - dist.shape[-1]])@@ -93,14 +64,10 @@ def undistort_points(points: torch.Tensor, K: torch.Tensor, dist: torch.Tensor)# Compensate for tilt distortionif torch.any(dist[..., 12] != 0) or torch.any(dist[..., 13] != 0):- invTilt = inverseTiltProjection(dist[..., 12], dist[..., 13])+ inv_tilt = tilt_projection(dist[..., 12], dist[..., 13], True)# 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]+ x, y = transform_points(inv_tilt, torch.stack([x, y], dim=-1)).unbind(-1)# Iteratively undistort pointsx0, y0 = x, y@@ -131,3 +98,59 @@ def undistort_points(points: torch.Tensor, K: torch.Tensor, dist: torch.Tensor)y = fy * y + cyreturn torch.stack([x, y], -1)+++# Based on https://github.com/opencv/opencv/blob/master/modules/calib3d/src/undistort.dispatch.cpp#L287+def undistort_image(image: torch.Tensor, K: torch.Tensor, dist: torch.Tensor) -> torch.Tensor:+ r"""Compensate an image for lens distortion.++ 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:+ image: Input image with shape :math:`(*, C, H, W)`.+ K: Intrinsic camera matrix with shape :math:`(*, 3, 3)`.+ dist: 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:+ Undistorted image with shape :math:`(*, C, H, W)`.++ Example:+ >>> img = torch.rand(1, 3, 5, 5)+ >>> K = torch.eye(3)[None]+ >>> dist_coeff = torch.rand(4)+ >>> out = undistort_image(img, K, dist_coeff)+ >>> out.shape+ torch.Size([1, 3, 5, 5])++ """+ if len(image.shape) < 2:+ raise ValueError(f"Image shape is invalid. Got: {image.shape}.")++ if K.shape[-2:] != (3, 3):+ raise ValueError(f'K matrix shape is invalid. Got {K.shape}.')++ if dist.shape[-1] not in [4, 5, 8, 12, 14]:+ raise ValueError(f'Invalid number of distortion coefficients. Got {dist.shape[-1]}.')++ if not image.is_floating_point():+ raise ValueError(f'Invalid input image data type. Input should be float. Got {image.dtype}.')++ B, _, rows, cols = image.shape++ # Create point coordinates for each pixel of the image+ xy_grid: torch.Tensor = create_meshgrid(rows, cols, False, image.device, image.dtype)+ pts = xy_grid.reshape(-1, 2) # (rows*cols)x2 matrix of pixel coordinates++ # Distort points and define maps+ ptsd: torch.Tensor = distort_points(pts, K, dist) # Bx(rows*cols)x2+ mapx: torch.Tensor = ptsd[..., 0].reshape(B, rows, cols) # B x rows x cols, float+ mapy: torch.Tensor = ptsd[..., 1].reshape(B, rows, cols) # B x rows x cols, float++ # Remap image to undistort+ out = remap(image, mapx, mapy, align_corners=True)++ return outdiff --git a/kornia/geometry/camera/perspective.py b/kornia/geometry/camera/perspective.pyindex e021dd22c..6e8c5a905 100644--- a/kornia/geometry/camera/perspective.py+++ b/kornia/geometry/camera/perspective.py@@ -17,10 +17,11 @@ def project_points(point_3d: torch.Tensor, camera_matrix: torch.Tensor) -> torchtensor of (u, v) cam coordinates with shape :math:`(*, 2)`.Example:+ >>> _ = torch.manual_seed(0)>>> X = torch.rand(1, 3)>>> K = torch.eye(3)[None]>>> project_points(X, K)- tensor([[1.4210, 0.9953]])+ tensor([[5.6088, 8.6827]])"""if not isinstance(point_3d, torch.Tensor):raise TypeError(f"Input point_3d type is not a torch.Tensor. Got {type(point_3d)}")@@ -81,11 +82,12 @@ def unproject_points(tensor of (x, y, z) world coordinates with shape :math:`(*, 3)`.Example:+ >>> _ = torch.manual_seed(0)>>> x = torch.rand(1, 2)>>> depth = torch.ones(1, 1)>>> K = torch.eye(3)[None]>>> unproject_points(x, depth, K)- tensor([[0.2711, 0.6923, 1.0000]])+ tensor([[0.4963, 0.7682, 1.0000]])"""if not isinstance(point_2d, torch.Tensor):raise TypeError(f"Input point_2d type is not a torch.Tensor. Got {type(point_2d)}")diff --git a/test/geometry/calibration/test_distort.py b/test/geometry/calibration/test_distort.pynew file mode 100644index 000000000..9ea116dbf--- /dev/null+++ b/test/geometry/calibration/test_distort.py@@ -0,0 +1,52 @@+import pytest+import torch+from torch.autograd import gradcheck++from kornia.geometry.calibration.distort import distort_points+from kornia.testing import assert_close+++class TestDistortPoints:+ 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 = distort_points(points, K, distCoeff)+ assert points.shape == pointsu.shape++ def test_smoke_batch(self, device, dtype):+ 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 = distort_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 = distort_points(points, K, distCoeff)+ assert pointsu.shape == (B, N, 2)++ 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(distort_points, (points, K, distCoeff), raise_exception=True)++ def test_jit(self, device, dtype):+ 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)+ inputs = (points, K, distCoeff)++ op = distort_points+ op_jit = torch.jit.script(op)+ assert_close(op(*inputs), op_jit(*inputs))diff --git a/test/geometry/calibration/test_undistort.py b/test/geometry/calibration/test_undistort.pyindex c635c38c2..8797319d2 100644--- a/test/geometry/calibration/test_undistort.py+++ b/test/geometry/calibration/test_undistort.py@@ -2,11 +2,11 @@ import pytestimport torchfrom torch.autograd import gradcheck-from kornia.geometry.calibration.undistort import undistort_points+from kornia.geometry.calibration.undistort import undistort_image, undistort_pointsfrom kornia.testing import assert_close-class TestUndistortion:+class TestUndistortPoints:def test_smoke(self, device, dtype):points = torch.rand(1, 2, device=device, dtype=dtype)K = torch.rand(3, 3, device=device, dtype=dtype)@@ -191,3 +191,85 @@ class TestUndistortion:distCoeff = torch.rand(1, 4, device=device, dtype=torch.float64)assert gradcheck(undistort_points, (points, K, distCoeff), raise_exception=True)++ def test_jit(self, device, dtype):+ 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)+ inputs = (points, K, distCoeff)++ op = undistort_points+ op_jit = torch.jit.script(op)+ assert_close(op(*inputs), op_jit(*inputs))+++class TestUndistortImage:+ def test_shape(self, device, dtype):+ im = torch.rand(1, 3, 5, 5, device=device, dtype=dtype)+ K = torch.rand(3, 3, device=device, dtype=dtype)+ distCoeff = torch.rand(4, device=device, dtype=dtype)++ imu = undistort_image(im, K, distCoeff)+ assert imu.shape == (1, 3, 5, 5)++ def test_opencv(self, device, dtype):+ im = torch.tensor(+ [+ [+ [+ [116, 75, 230, 5, 32],+ [9, 182, 97, 213, 3],+ [91, 10, 33, 141, 230],+ [229, 63, 221, 244, 61],+ [19, 137, 23, 59, 227]+ ]+ ]+ ],+ device=device, dtype=dtype+ )++ K = torch.tensor(+ [[2, 0, 2], [0, 2, 2], [0, 0, 1]],+ device=device,+ dtype=dtype+ )++ dist = torch.tensor([0.2290, 0.9565, 0.0083, 0.0475], device=device, dtype=dtype)++ # Expected output generated with OpenCV:+ # import cv2+ # imu_expected = cv2.undistort(np.uint8(im[0,0].numpy()), K.numpy(), dist.numpy())+ imu_expected = torch.tensor(+ [+ [+ [+ [0, 0, 0, 0, 0],+ [0, 124, 112, 82, 0],+ [0, 13, 33, 158, 0],+ [0, 108, 197, 150, 0],+ [0, 0, 0, 0, 0]+ ]+ ]+ ],+ device=device, dtype=dtype+ )++ imu = undistort_image(im / 255., K, dist)+ assert_close(imu, imu_expected / 255., rtol=1e-2, atol=1e-2)++ def test_gradcheck(self, device):+ im = torch.rand(1, 1, 15, 15, device=device, dtype=torch.float64, requires_grad=True)+ K = torch.rand(3, 3, device=device, dtype=torch.float64)+ distCoeff = torch.rand(4, device=device, dtype=torch.float64)++ assert gradcheck(undistort_image, (im, K, distCoeff), raise_exception=True)++ def test_jit(self, device, dtype):+ im = torch.rand(1, 3, 5, 5, device=device, dtype=dtype)+ K = torch.rand(3, 3, device=device, dtype=dtype)+ distCoeff = torch.rand(4, device=device, dtype=dtype)+ inputs = (im, K, distCoeff)++ op = undistort_image+ op_jit = torch.jit.script(op)+ assert_close(op(*inputs), op_jit(*inputs))