π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
Chore shape checks (#3041)
Dmytro Mishkin7dc5fa468192
diff --git a/kornia/geometry/calibration/pnp.py b/kornia/geometry/calibration/pnp.pyindex 61a8d7272..e3aebcd52 100644--- a/kornia/geometry/calibration/pnp.py+++ b/kornia/geometry/calibration/pnp.py@@ -8,6 +8,7 @@ from kornia.geometry.conversions import convert_points_to_homogeneousfrom kornia.geometry.linalg import transform_pointsfrom kornia.utils import eye_likefrom kornia.utils.helpers import _torch_linalg_svdvals+from kornia.core.check import KORNIA_CHECK_SHAPE, KORNIA_CHECK_IS_TENSOR, KORNIA_CHECK_SAME_SHAPEdef _mean_isotropic_scale_normalize(points: torch.Tensor, eps: float = 1e-8) -> Tuple[torch.Tensor, torch.Tensor]:@@ -21,12 +22,7 @@ def _mean_isotropic_scale_normalize(points: torch.Tensor, eps: float = 1e-8) ->Tuple containing the normalized points in the shape :math:`(B, N, D)` and the transformation matrixin the shape :math:`(B, D+1, D+1)`."""- if not isinstance(points, torch.Tensor):- raise AssertionError(f"points is not an instance of torch.Tensor. Type of points is {type(points)}")-- if len(points.shape) != 3:- raise AssertionError(f"points must be of shape (B, N, D). Got shape {points.shape}.")-+ KORNIA_CHECK_SHAPE(points, ["B", "N", "D"])x_mean = torch.mean(points, dim=1, keepdim=True) # Bx1xDscale = (points - x_mean).norm(dim=-1, p=2).mean(dim=-1) # B@@ -127,17 +123,9 @@ def solve_pnp_dlt(# 3. http://rpg.ifi.uzh.ch/docs/teaching/2020/03_camera_calibration.pdf# 4. http://www.cs.cmu.edu/~16385/s17/Slides/11.3_Pose_Estimation.pdf# 5. https://www.ece.mcmaster.ca/~shirani/vision/hartley_ch7.pdf-- if not isinstance(world_points, torch.Tensor):- raise AssertionError(- f"world_points is not an instance of torch.Tensor. Type of world_points is {type(world_points)}"- )-- if not isinstance(img_points, torch.Tensor):- raise AssertionError(f"img_points is not an instance of torch.Tensor. Type of img_points is {type(img_points)}")-- if not isinstance(intrinsics, torch.Tensor):- raise AssertionError(f"intrinsics is not an instance of torch.Tensor. Type of intrinsics is {type(intrinsics)}")+ KORNIA_CHECK_IS_TENSOR(world_points)+ KORNIA_CHECK_IS_TENSOR(img_points)+ KORNIA_CHECK_IS_TENSOR(intrinsics)if (weights is not None) and (not isinstance(weights, torch.Tensor)):raise AssertionError(@@ -166,20 +154,10 @@ def solve_pnp_dlt(f"intrinsics must have one of the following dtypes {accepted_dtypes}. Currently it has {intrinsics.dtype}.")- if (len(world_points.shape) != 3) or (world_points.shape[2] != 3):- raise AssertionError(f"world_points must be of shape (B, N, 3). Got shape {world_points.shape}.")-- if (len(img_points.shape) != 3) or (img_points.shape[2] != 2):- raise AssertionError(f"img_points must be of shape (B, N, 2). Got shape {img_points.shape}.")-- if (len(intrinsics.shape) != 3) or (intrinsics.shape[1:] != (3, 3)):- raise AssertionError(f"intrinsics must be of shape (B, 3, 3). Got shape {intrinsics.shape}.")-- if world_points.shape[1] != img_points.shape[1]:- raise AssertionError("world_points and img_points must have equal number of points.")-- if (world_points.shape[0] != img_points.shape[0]) or (world_points.shape[0] != intrinsics.shape[0]):- raise AssertionError("world_points, img_points and intrinsics must have the same batch size.")+ KORNIA_CHECK_SHAPE(world_points, ["B", "N", "3"])+ KORNIA_CHECK_SHAPE(img_points, ["B", "N", "2"])+ KORNIA_CHECK_SHAPE(intrinsics, ["B", "3", "3"])+ KORNIA_CHECK_SAME_SHAPE(world_points[:,:, 0], img_points[:,:, 0])if world_points.shape[1] < 6:raise AssertionError(diff --git a/kornia/geometry/calibration/undistort.py b/kornia/geometry/calibration/undistort.pyindex 4a809b4fc..93f21403c 100644--- a/kornia/geometry/calibration/undistort.py+++ b/kornia/geometry/calibration/undistort.py@@ -8,6 +8,7 @@ from kornia.core import stackfrom kornia.geometry.linalg import transform_pointsfrom kornia.geometry.transform import remapfrom kornia.utils import create_meshgrid+from kornia.core.check import KORNIA_CHECK_SHAPEfrom .distort import distort_points, tilt_projection@@ -45,16 +46,16 @@ def undistort_points([-0.0697, 0.0228],[-0.1843, -0.1606]]])"""+ KORNIA_CHECK_SHAPE(points, ["*", "N", "2"])+ KORNIA_CHECK_SHAPE(K, ["*", "3", "3"])+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 new_K is None:new_K = K- elif new_K.shape[-2:] != (3, 3):- raise ValueError(f"new_K matrix shape is invalid. Got {new_K.shape}.")+ else:+ KORNIA_CHECK_SHAPE(new_K, ["*", "3", "3"])if dist.shape[-1] not in [4, 5, 8, 12, 14]:raise ValueError(f"Invalid number of distortion coefficients. Got {dist.shape[-1]}")diff --git a/kornia/geometry/epipolar/essential.py b/kornia/geometry/epipolar/essential.pyindex b00bab43e..2d0a429e7 100644--- a/kornia/geometry/epipolar/essential.py+++ b/kornia/geometry/epipolar/essential.py@@ -273,15 +273,9 @@ def essential_from_fundamental(F_mat: torch.Tensor, K1: torch.Tensor, K2: torch.Returns:The essential matrix with shape :math:`(*, 3, 3)`."""- if not (len(F_mat.shape) >= 2 and F_mat.shape[-2:] == (3, 3)):- raise AssertionError(F_mat.shape)- if not (len(K1.shape) >= 2 and K1.shape[-2:] == (3, 3)):- raise AssertionError(K1.shape)- if not (len(K2.shape) >= 2 and K2.shape[-2:] == (3, 3)):- raise AssertionError(K2.shape)- if not len(F_mat.shape[:-2]) == len(K1.shape[:-2]) == len(K2.shape[:-2]):- raise AssertionError-+ KORNIA_CHECK_SHAPE(F_mat, ["*", "3", "3"])+ KORNIA_CHECK_SHAPE(K1, ["*", "3", "3"])+ KORNIA_CHECK_SHAPE(K2, ["*", "3", "3"])return K2.transpose(-2, -1) @ F_mat @ K1@@ -298,8 +292,7 @@ def decompose_essential_matrix(E_mat: torch.Tensor) -> Tuple[torch.Tensor, torchA tuple containing the first and second possible rotation matrices and the translation vector.The shape of the tensors with be same input :math:`[(*, 3, 3), (*, 3, 3), (*, 3, 1)]`."""- if not (len(E_mat.shape) >= 2 and E_mat.shape[-2:]):- raise AssertionError(E_mat.shape)+ KORNIA_CHECK_SHAPE(E_mat, ["*", "3", "3"])# decompose matrix by its singular valuesU, _, V = _torch_svd_cast(E_mat)@@ -342,9 +335,8 @@ def decompose_essential_matrix_no_svd(E_mat: torch.Tensor) -> Tuple[torch.TensorA tuple containing the first and second possible rotation matrices and the translation vector.The shape of the tensors with be same input :math:`[(*, 3, 3), (*, 3, 3), (*, 3, 1)]`."""- if not (len(E_mat.shape) >= 2 and E_mat.shape[-2:] == (3, 3)):- raise AssertionError(E_mat.shape)- elif len(E_mat.shape) != 3:+ KORNIA_CHECK_SHAPE(E_mat, ["*", "3", "3"])+ if len(E_mat.shape) != 3:E_mat = E_mat.view(-1, 3, 3)B = E_mat.shape[0]@@ -407,15 +399,11 @@ def essential_from_Rt(R1: torch.Tensor, t1: torch.Tensor, R2: torch.Tensor, t2:Returns:The Essential matrix with the shape :math:`(*, 3, 3)`."""- if not (len(R1.shape) >= 2 and R1.shape[-2:] == (3, 3)):- raise AssertionError(R1.shape)- if not (len(t1.shape) >= 2 and t1.shape[-2:] == (3, 1)):- raise AssertionError(t1.shape)- if not (len(R2.shape) >= 2 and R2.shape[-2:] == (3, 3)):- raise AssertionError(R2.shape)- if not (len(t2.shape) >= 2 and t2.shape[-2:] == (3, 1)):- raise AssertionError(t2.shape)-+ KORNIA_CHECK_SHAPE(R1, ["*", "3", "3"])+ KORNIA_CHECK_SHAPE(R2, ["*", "3", "3"])+ KORNIA_CHECK_SHAPE(t1, ["*", "3", "1"])+ KORNIA_CHECK_SHAPE(t2, ["*", "3", "1"])+# first compute the camera relative motionR, t = relative_camera_motion(R1, t1, R2, t2)@@ -438,8 +426,7 @@ def motion_from_essential(E_mat: torch.Tensor) -> Tuple[torch.Tensor, torch.TensThe rotation and translation containing the four possible combination for the retrieved motion.The tuple is as following :math:`[(*, 4, 3, 3), (*, 4, 3, 1)]`."""- if not (len(E_mat.shape) >= 2 and E_mat.shape[-2:] == (3, 3)):- raise AssertionError(E_mat.shape)+ KORNIA_CHECK_SHAPE(E_mat, ["*", "3", "3"])# decompose the essential matrix by its possible posesR1, R2, t = decompose_essential_matrix(E_mat)@@ -483,23 +470,16 @@ def motion_from_essential_choose_solution(The rotation and translation plus the 3d triangulated points.The tuple is as following :math:`[(*, 3, 3), (*, 3, 1), (*, N, 3)]`."""- if not (len(E_mat.shape) >= 2 and E_mat.shape[-2:] == (3, 3)):- raise AssertionError(E_mat.shape)- if not (len(K1.shape) >= 2 and K1.shape[-2:] == (3, 3)):- raise AssertionError(K1.shape)- if not (len(K2.shape) >= 2 and K2.shape[-2:] == (3, 3)):- raise AssertionError(K2.shape)- if not (len(x1.shape) >= 2 and x1.shape[-1] == 2):- raise AssertionError(x1.shape)- if not (len(x2.shape) >= 2 and x2.shape[-1] == 2):- raise AssertionError(x2.shape)- if not len(E_mat.shape[:-2]) == len(K1.shape[:-2]) == len(K2.shape[:-2]):- raise AssertionError+ KORNIA_CHECK_SHAPE(E_mat, ["*", "3", "3"])+ KORNIA_CHECK_SHAPE(K1, ["*", "3", "3"])+ KORNIA_CHECK_SHAPE(K2, ["*", "3", "3"])+ KORNIA_CHECK_SHAPE(x1, ["*", "N", "2"])+ KORNIA_CHECK_SHAPE(x2, ["*", "N", "2"])+ KORNIA_CHECK(len(E_mat.shape[:-2]) == len(K1.shape[:-2]) == len(K2.shape[:-2]))+if mask is not None:- if len(mask.shape) < 1:- raise AssertionError(mask.shape)- if mask.shape != x1.shape[:-1]:- raise AssertionError(mask.shape)+ KORNIA_CHECK_SHAPE(mask, ["*", "N"])+ KORNIA_CHECK(mask.shape == x1.shape[:-1])unbatched = len(E_mat.shape) == 2@@ -581,14 +561,10 @@ def relative_camera_motion(A tuple with the relative rotation matrix andtranslation vector with the shape of :math:`[(*, 3, 3), (*, 3, 1)]`."""- if not (len(R1.shape) >= 2 and R1.shape[-2:] == (3, 3)):- raise AssertionError(R1.shape)- if not (len(t1.shape) >= 2 and t1.shape[-2:] == (3, 1)):- raise AssertionError(t1.shape)- if not (len(R2.shape) >= 2 and R2.shape[-2:] == (3, 3)):- raise AssertionError(R2.shape)- if not (len(t2.shape) >= 2 and t2.shape[-2:] == (3, 1)):- raise AssertionError(t2.shape)+ KORNIA_CHECK_SHAPE(R1, ["*", "3", "3"])+ KORNIA_CHECK_SHAPE(R2, ["*", "3", "3"])+ KORNIA_CHECK_SHAPE(t1, ["*", "3", "1"])+ KORNIA_CHECK_SHAPE(t2, ["*", "3", "1"])# compute first the relative rotationR = R2 @ R1.transpose(-2, -1)@@ -615,5 +591,4 @@ def find_essential("""E = run_5point(points1, points2, weights).to(points1.dtype)-return Ediff --git a/kornia/geometry/epipolar/fundamental.py b/kornia/geometry/epipolar/fundamental.pyindex c07d0ff76..5d0497544 100644--- a/kornia/geometry/epipolar/fundamental.py+++ b/kornia/geometry/epipolar/fundamental.py@@ -5,7 +5,7 @@ from typing import Literal, Optional, Tupleimport torchfrom kornia.core import Tensor, concatenate, ones_like, stack, where, zeros-from kornia.core.check import KORNIA_CHECK_SHAPE+from kornia.core.check import KORNIA_CHECK_SHAPE, KORNIA_CHECK_SAME_SHAPEfrom kornia.geometry.conversions import convert_points_from_homogeneous, convert_points_to_homogeneousfrom kornia.geometry.linalg import transform_pointsfrom kornia.geometry.solvers import solve_cubic@@ -179,12 +179,14 @@ def run_8point(points1: Tensor, points2: Tensor, weights: Optional[Tensor] = NonReturns:the computed fundamental matrix with shape :math:`(B, 3, 3)`."""- if points1.shape != points2.shape:- raise AssertionError(points1.shape, points2.shape)+ KORNIA_CHECK_SHAPE(points1, ["B", "N", "2"])+ KORNIA_CHECK_SHAPE(points2, ["B", "N", "2"])+ KORNIA_CHECK_SAME_SHAPE(points1, points2)if points1.shape[1] < 8:raise AssertionError(points1.shape)if weights is not None:- if not (len(weights.shape) == 2 and weights.shape[1] == points1.shape[1]):+ KORNIA_CHECK_SHAPE(weights, ["B", "N"])+ if not (weights.shape[1] == points1.shape[1]):raise AssertionError(weights.shape)points1_norm, transform1 = normalize_points(points1)@@ -345,12 +347,9 @@ def fundamental_from_essential(E_mat: Tensor, K1: Tensor, K2: Tensor) -> Tensor:Returns:The fundamental matrix with shape :math:`(*, 3, 3)`."""- if not (len(E_mat.shape) >= 2 and E_mat.shape[-2:] == (3, 3)):- raise AssertionError(E_mat.shape)- if not (len(K1.shape) >= 2 and K1.shape[-2:] == (3, 3)):- raise AssertionError(K1.shape)- if not (len(K2.shape) >= 2 and K2.shape[-2:] == (3, 3)):- raise AssertionError(K2.shape)+ KORNIA_CHECK_SHAPE(E_mat, ["*", "3", "3"])+ KORNIA_CHECK_SHAPE(K1, ["*", "3", "3"])+ KORNIA_CHECK_SHAPE(K2, ["*", "3", "3"])if not len(E_mat.shape[:-2]) == len(K1.shape[:-2]) == len(K2.shape[:-2]):raise AssertionError@@ -372,10 +371,8 @@ def fundamental_from_projections(P1: Tensor, P2: Tensor) -> Tensor:Returns:The fundamental matrix with shape :math:`(*, 3, 3)`."""- if not (len(P1.shape) >= 2 and P1.shape[-2:] == (3, 4)):- raise AssertionError(P1.shape)- if not (len(P2.shape) >= 2 and P2.shape[-2:] == (3, 4)):- raise AssertionError(P2.shape)+ KORNIA_CHECK_SHAPE(P1, ["*", "3", "4"])+ KORNIA_CHECK_SHAPE(P2, ["*", "3", "4"])if P1.shape[:-2] != P2.shape[:-2]:raise AssertionErrordiff --git a/kornia/geometry/epipolar/projection.py b/kornia/geometry/epipolar/projection.pyindex 76bcb86de..abc253f84 100644--- a/kornia/geometry/epipolar/projection.py+++ b/kornia/geometry/epipolar/projection.py@@ -8,7 +8,7 @@ from torch.linalg import qr as linalg_qrfrom kornia.core import Tensor, concatenate, ones_like, pad, stack, zeros_likefrom kornia.utils import eye_like, vec_likefrom kornia.utils.helpers import _torch_svd_cast-+from kornia.core.check import KORNIA_CHECK_SHAPEfrom .numeric import cross_product_matrix@@ -91,12 +91,9 @@ def projection_from_KRt(K: Tensor, R: Tensor, t: Tensor) -> Tensor:Returns:The projection matrix P with shape :math:`(B, 4, 4)`."""- if K.shape[-2:] != (3, 3):- raise AssertionError(K.shape)- if R.shape[-2:] != (3, 3):- raise AssertionError(R.shape)- if t.shape[-2:] != (3, 1):- raise AssertionError(t.shape)+ KORNIA_CHECK_SHAPE(K, ["*", "3", "3"])+ KORNIA_CHECK_SHAPE(R, ["*", "3", "3"])+ KORNIA_CHECK_SHAPE(t, ["*", "3", "1"])if not len(K.shape) == len(R.shape) == len(t.shape):raise AssertionError@@ -121,11 +118,7 @@ def KRt_from_projection(P: Tensor, eps: float = 1e-6) -> Tuple[Tensor, Tensor, T- The Rotation matrix with shape :math:`(B, 3, 3)`.- The Translation vector with shape :math:`(B, 3)`."""- if P.shape[-2:] != (3, 4):- raise AssertionError("P must be of shape [B, 3, 4]")- if len(P.shape) != 3:- raise AssertionError-+ KORNIA_CHECK_SHAPE(P, ["*", "3", "4"])submat_3x3 = P[:, 0:3, 0:3]last_column = P[:, 0:3, 3].unsqueeze(-1)@@ -185,10 +178,7 @@ def projections_from_fundamental(F_mat: Tensor) -> Tensor:Returns:The projection matrices with shape :math:`(B, 3, 4, 2)`."""- if len(F_mat.shape) != 3:- raise AssertionError(F_mat.shape)- if F_mat.shape[-2:] != (3, 3):- raise AssertionError(F_mat.shape)+ KORNIA_CHECK_SHAPE(F_mat, ["*", "3", "3"])R1 = eye_like(3, F_mat) # Bx3x3t1 = vec_like(3, F_mat) # Bx3diff --git a/kornia/geometry/epipolar/triangulation.py b/kornia/geometry/epipolar/triangulation.pyindex e1f73b6b1..dbaceb453 100644--- a/kornia/geometry/epipolar/triangulation.py+++ b/kornia/geometry/epipolar/triangulation.py@@ -5,6 +5,7 @@ import torchfrom kornia.core import zerosfrom kornia.geometry.conversions import convert_points_from_homogeneousfrom kornia.utils.helpers import _torch_svd_cast+from kornia.core.check import KORNIA_CHECK_SHAPE, KORNIA_CHECK_SAME_SHAPE# https://github.com/opencv/opencv_contrib/blob/master/modules/sfm/src/triangulation.cpp#L68@@ -31,20 +32,10 @@ def triangulate_points(Returns:The reconstructed 3d points in the world frame with shape :math:`(*, N, 3)`."""- if not (len(P1.shape) >= 2 and P1.shape[-2:] == (3, 4)):- raise AssertionError(P1.shape)- if not (len(P2.shape) >= 2 and P2.shape[-2:] == (3, 4)):- raise AssertionError(P2.shape)- if len(P1.shape[:-2]) != len(P2.shape[:-2]):- raise AssertionError(P1.shape, P2.shape)- if not (len(points1.shape) >= 2 and points1.shape[-1] == 2):- raise AssertionError(points1.shape)- if not (len(points2.shape) >= 2 and points2.shape[-1] == 2):- raise AssertionError(points2.shape)- if len(points1.shape[:-2]) != len(points2.shape[:-2]):- raise AssertionError(points1.shape, points2.shape)- if len(P1.shape[:-2]) != len(points1.shape[:-2]):- raise AssertionError(P1.shape, points1.shape)+ KORNIA_CHECK_SHAPE(P1, ["*", "3", "4"])+ KORNIA_CHECK_SHAPE(P2, ["*", "3", "4"])+ KORNIA_CHECK_SHAPE(points1, ["*", "N", "2"])+ KORNIA_CHECK_SHAPE(points2, ["*", "N", "2"])# allocate and construct the equations matrix with shape (*, 4, 4)points_shape = max(points1.shape, points2.shape) # this allows broadcasting