π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
:minidisc: add missing snippets and improvements (#1336)
Edgar Ribad43edc239e83
diff --git a/conftest.py b/conftest.pyindex 94771f510..9f02acf1b 100644--- a/conftest.py+++ b/conftest.py@@ -1,6 +1,7 @@from itertools import productfrom typing import Dict+import numpyimport pytestimport torch@@ -85,3 +86,9 @@ def pytest_generate_tests(metafunc):def pytest_addoption(parser):parser.addoption('--device', action="store", default="cpu")parser.addoption('--dtype', action="store", default="float32")++[email protected](autouse=True)+def add_np(doctest_namespace):+ doctest_namespace["np"] = numpy+ doctest_namespace["torch"] = torchdiff --git a/docs/source/contrib.rst b/docs/source/contrib.rstindex 7de546470..ea42c3862 100644--- a/docs/source/contrib.rst+++ b/docs/source/contrib.rst@@ -3,16 +3,22 @@ kornia.contrib.. currentmodule:: kornia.contrib+Image Segmentation+------------------+.. autofunction:: connected_components++Image Patches+-------------+.. autofunction:: extract_tensor_patches+.. autofunction:: combine_tensor_patches++.. autoclass:: ExtractTensorPatches+.. autoclass:: CombineTensorPatchesImage Classification--------------------.. autoclass:: VisionTransformer.. autoclass:: ClassificationHead--Module---------.. autoclass:: ExtractTensorPatchesdiff --git a/docs/source/losses.rst b/docs/source/losses.rstindex 070ddcd3c..472ed595a 100644--- a/docs/source/losses.rst+++ b/docs/source/losses.rst@@ -25,6 +25,12 @@ Distributions.. autofunction:: js_div_loss_2d.. autofunction:: kl_div_loss_2d+Morphology+----------++.. autoclass:: HausdorffERLoss+.. autoclass:: HausdorffERLoss3D+Module------@@ -36,5 +42,3 @@ Module.. autoclass:: TotalVariation.. autoclass:: PSNRLoss.. autoclass:: BinaryFocalLossWithLogits-.. autoclass:: HausdorffERLoss-.. autoclass:: HausdorffERLoss3Ddiff --git a/kornia/contrib/connected_components.py b/kornia/contrib/connected_components.pyindex c02159f12..4602d464c 100644--- a/kornia/contrib/connected_components.py+++ b/kornia/contrib/connected_components.py@@ -11,7 +11,7 @@ def connected_components(input: torch.Tensor, num_iterations: int = 100) -> torchttps://gist.github.com/efirdc/5d8bd66859e574c683a504a4690ae8bc- .. note::+ .. warning::This is an experimental API subject to changes and optimization improvements... note::diff --git a/kornia/contrib/extract_patches.py b/kornia/contrib/extract_patches.pyindex dd4b61a38..7dfbb0d32 100644--- a/kornia/contrib/extract_patches.py+++ b/kornia/contrib/extract_patches.py@@ -143,17 +143,16 @@ def combine_tensor_patches(stride: Tuple[int, int] = (4, 4),unpadding: Optional[Tuple[int, int, int, int]] = None,) -> torch.Tensor:- """Restore input from patches.+ r"""Restore input from patches.Args:- patches: patched tensor.+ patches: patched tensor with shape :math:`(B, N, C, H_{out}, W_{out})`.window_size: the size of the sliding window and the output patch size.stride: stride of the sliding window.unpadding: remove the padding added to both side of the input.- Shape:- - Input: :math:`(B, N, C, H_{out}, W_{out})`- - Output: :math:`(B, C, H, W)`+ Return:+ The combined patches in an image tensor with shape :math:`(B, C, H, W)`.Example:>>> out = extract_tensor_patches(torch.arange(16).view(1, 1, 4, 4), window_size=(2, 2), stride=(2, 2))@@ -202,9 +201,30 @@ def extract_tensor_patches(r"""Function that extract patches from tensors and stack them.See :class:`~kornia.contrib.ExtractTensorPatches` for details.++ Args:+ input: tensor image where to extract the patches with shape :math:`(B, C, H, W)`.+ window_size: the size of the sliding window and the output patch size.+ stride: stride of the sliding window.+ padding: Zero-padding added to both side of the input.++ Returns:+ the tensor with the extracted patches with shape :math:`(B, N, C, H_{out}, W_{out})`.++ Examples:+ >>> input = torch.arange(9.).view(1, 1, 3, 3)+ >>> patches = extract_tensor_patches(input, (2, 3))+ >>> input+ tensor([[[[0., 1., 2.],+ [3., 4., 5.],+ [6., 7., 8.]]]])+ >>> patches[:, -1]+ tensor([[[[3., 4., 5.],+ [6., 7., 8.]]]])"""if not torch.is_tensor(input):raise TypeError(f"Input input type is not a torch.Tensor. Got {type(input)}")+if not len(input.shape) == 4:raise ValueError(f"Invalid input shape, we expect BxCxHxW. Got: {input.shape}")diff --git a/kornia/geometry/calibration/undistort.py b/kornia/geometry/calibration/undistort.pyindex 11c2e594a..aa2f1b348 100644--- a/kornia/geometry/calibration/undistort.py+++ b/kornia/geometry/calibration/undistort.py@@ -6,11 +6,11 @@ def inverseTiltProjection(taux: torch.Tensor, tauy: torch.Tensor) -> torch.Tensor"""Estimate the inverse of the tilt projection matrixArgs:- 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)`.+ 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:- torch.Tensor: Inverse tilt projection matrix with shape :math:`(*, 3, 3)`.+ Inverse tilt projection matrix with shape :math:`(*, 3, 3)`."""if taux.dim() != tauy.dim():raise AssertionError@@ -61,6 +61,16 @@ def undistort_points(points: torch.Tensor, K: torch.Tensor, dist: torch.Tensor)Returns:Undistorted 2D points with shape :math:`(*, N, 2)`.++ Example:+ >>> 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]]])"""if not (points.dim() >= 2 and points.shape[-1] == 2):raise AssertionErrordiff --git a/kornia/geometry/camera/perspective.py b/kornia/geometry/camera/perspective.pyindex bc335e3c9..e021dd22c 100644--- a/kornia/geometry/camera/perspective.py+++ b/kornia/geometry/camera/perspective.py@@ -15,6 +15,12 @@ def project_points(point_3d: torch.Tensor, camera_matrix: torch.Tensor) -> torchReturns:tensor of (u, v) cam coordinates with shape :math:`(*, 2)`.++ Example:+ >>> X = torch.rand(1, 3)+ >>> K = torch.eye(3)[None]+ >>> project_points(X, K)+ tensor([[1.4210, 0.9953]])"""if not isinstance(point_3d, torch.Tensor):raise TypeError(f"Input point_3d type is not a torch.Tensor. Got {type(point_3d)}")@@ -73,6 +79,13 @@ def unproject_points(Returns:tensor of (x, y, z) world coordinates with shape :math:`(*, 3)`.++ Example:+ >>> 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]])"""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/kornia/geometry/conversions.py b/kornia/geometry/conversions.pyindex 34557100e..2656ac5b7 100644--- a/kornia/geometry/conversions.py+++ b/kornia/geometry/conversions.py@@ -48,8 +48,9 @@ def rad2deg(tensor: torch.Tensor) -> torch.Tensor:Tensor with same shape as input.Example:- >>> input = torch.tensor(3.1415926535) * torch.rand(1, 3, 3)- >>> output = rad2deg(input)+ >>> input = torch.tensor(3.1415926535)+ >>> rad2deg(input)+ tensor(180.)"""if not isinstance(tensor, torch.Tensor):raise TypeError(f"Input type is not a torch.Tensor. Got {type(tensor)}")@@ -67,8 +68,9 @@ def deg2rad(tensor: torch.Tensor) -> torch.Tensor:tensor with same shape as input.Examples:- >>> input = 360. * torch.rand(1, 3, 3)- >>> output = deg2rad(input)+ >>> input = torch.tensor(180.)+ >>> deg2rad(input)+ tensor(3.1416)"""if not isinstance(tensor, torch.Tensor):raise TypeError(f"Input type is not a torch.Tensor. Got {type(tensor)}")@@ -127,15 +129,16 @@ def convert_points_from_homogeneous(points: torch.Tensor, eps: float = 1e-8) ->r"""Function that converts points from homogeneous to Euclidean space.Args:- points: the points to be transformed.+ points: the points to be transformed of shape :math:`(B, N, D)`.eps: to avoid division by zero.Returns:- the points in Euclidean space.+ the points in Euclidean space :math:`(B, N, D-1)`.Examples:- >>> input = torch.rand(2, 4, 3) # BxNx3- >>> output = convert_points_from_homogeneous(input) # BxNx2+ >>> input = torch.tensor([[0., 0., 1.]])+ >>> convert_points_from_homogeneous(input)+ tensor([[0., 0.]])"""if not isinstance(points, torch.Tensor):raise TypeError(f"Input type is not a torch.Tensor. Got {type(points)}")@@ -159,14 +162,15 @@ def convert_points_to_homogeneous(points: torch.Tensor) -> torch.Tensor:r"""Function that converts points from Euclidean to homogeneous space.Args:- points: the points to be transformed.+ points: the points to be transformed with shape :math:`(B, N, D)`.Returns:- the points in homogeneous coordinates.+ the points in homogeneous coordinates :math:`(B, N, D+1)`.Examples:- >>> input = torch.rand(2, 4, 3) # BxNx3- >>> output = convert_points_to_homogeneous(input) # BxNx4+ >>> input = torch.tensor([[0., 0.]])+ >>> convert_points_to_homogeneous(input)+ tensor([[0., 0., 1.]])"""if not isinstance(points, torch.Tensor):raise TypeError(f"Input type is not a torch.Tensor. Got {type(points)}")@@ -192,13 +196,19 @@ def convert_affinematrix_to_homography(A: torch.Tensor) -> torch.Tensor:the homography matrix with shape of :math:`(B,3,3)`.Examples:- >>> input = torch.rand(2, 2, 3) # Bx2x3- >>> output = convert_affinematrix_to_homography(input) # Bx3x3+ >>> A = torch.tensor([[[1., 0., 0.],+ ... [0., 1., 0.]]])+ >>> convert_affinematrix_to_homography(A)+ tensor([[[1., 0., 0.],+ [0., 1., 0.],+ [0., 0., 1.]]])"""if not isinstance(A, torch.Tensor):raise TypeError(f"Input type is not a torch.Tensor. Got {type(A)}")+if not (len(A.shape) == 3 and A.shape[-2:] == (2, 3)):raise ValueError(f"Input matrix must be a Bx2x3 tensor. Got {A.shape}")+return _convert_affinematrix_to_homography_impl(A)@@ -212,13 +222,21 @@ def convert_affinematrix_to_homography3d(A: torch.Tensor) -> torch.Tensor:the homography matrix with shape of :math:`(B,4,4)`.Examples:- >>> input = torch.rand(2, 3, 4) # Bx3x4- >>> output = convert_affinematrix_to_homography3d(input) # Bx4x4+ >>> A = torch.tensor([[[1., 0., 0., 0.],+ ... [0., 1., 0., 0.],+ ... [0., 0., 1., 0.]]])+ >>> convert_affinematrix_to_homography3d(A)+ tensor([[[1., 0., 0., 0.],+ [0., 1., 0., 0.],+ [0., 0., 1., 0.],+ [0., 0., 0., 1.]]])"""if not isinstance(A, torch.Tensor):raise TypeError(f"Input type is not a torch.Tensor. Got {type(A)}")+if not (len(A.shape) == 3 and A.shape[-2:] == (3, 4)):raise ValueError(f"Input matrix must be a Bx3x4 tensor. Got {A.shape}")+return _convert_affinematrix_to_homography_impl(A)@@ -226,18 +244,23 @@ def angle_axis_to_rotation_matrix(angle_axis: torch.Tensor) -> torch.Tensor:r"""Convert 3d vector of axis-angle rotation to 3x3 rotation matrix.Args:- angle_axis: tensor of 3d vector of axis-angle rotations in radians.+ angle_axis: tensor of 3d vector of axis-angle rotations in radians with shape :math:`(N, 3)`.Returns:- tensor of 3x3 rotation matrices.-- Shape:- - Input: :math:`(N, 3)`- - Output: :math:`(N, 3, 3)`+ tensor of rotation matrices of shape :math:`(N, 3, 3)`.Example:- >>> input = torch.rand(1, 3) # Nx3- >>> output = angle_axis_to_rotation_matrix(input) # Nx3x3+ >>> input = torch.tensor([[0., 0., 0.]])+ >>> angle_axis_to_rotation_matrix(input)+ tensor([[[1., 0., 0.],+ [0., 1., 0.],+ [0., 0., 1.]]])++ >>> input = torch.tensor([[1.5708, 0., 0.]])+ >>> angle_axis_to_rotation_matrix(input)+ tensor([[[ 1.0000e+00, 0.0000e+00, 0.0000e+00],+ [ 0.0000e+00, -3.6200e-06, -1.0000e+00],+ [ 0.0000e+00, 1.0000e+00, -3.6200e-06]]])"""if not isinstance(angle_axis, torch.Tensor):raise TypeError(f"Input type is not a torch.Tensor. Got {type(angle_axis)}")@@ -303,18 +326,23 @@ def rotation_matrix_to_angle_axis(rotation_matrix: torch.Tensor) -> torch.Tensorr"""Convert 3x3 rotation matrix to Rodrigues vector in radians.Args:- rotation_matrix: rotation matrix.+ rotation_matrix: rotation matrix of shape :math:`(N, 3, 3)`.Returns:- Rodrigues vector transformation.-- Shape:- - Input: :math:`(N, 3, 3)`- - Output: :math:`(N, 3)`+ Rodrigues vector transformation of shape :math:`(N, 3)`.Example:- >>> input = torch.rand(2, 3, 3) # Nx3x3- >>> output = rotation_matrix_to_angle_axis(input) # Nx3+ >>> input = torch.tensor([[1., 0., 0.],+ ... [0., 1., 0.],+ ... [0., 0., 1.]])+ >>> rotation_matrix_to_angle_axis(input)+ tensor([0., 0., 0.])++ >>> input = torch.tensor([[1., 0., 0.],+ ... [0., 0., -1.],+ ... [0., 1., 0.]])+ >>> rotation_matrix_to_angle_axis(input)+ tensor([1.5708, 0.0000, 0.0000])"""if not isinstance(rotation_matrix, torch.Tensor):raise TypeError(f"Input type is not a torch.Tensor. Got {type(rotation_matrix)}")@@ -336,21 +364,20 @@ def rotation_matrix_to_quaternion(The (x, y, z, w) order is going to be deprecated in favor of efficiency.Args:- rotation_matrix: the rotation matrix to convert.+ rotation_matrix: the rotation matrix to convert with shape :math:`(*, 3, 3)`.eps: small value to avoid zero division.order: quaternion coefficient order. Note: 'xyzw' will be deprecated in favor of 'wxyz'.Return:- the rotation in quaternion.-- Shape:- - Input: :math:`(*, 3, 3)`- - Output: :math:`(*, 4)`+ the rotation in quaternion with shape :math:`(*, 4)`.Example:- >>> input = torch.rand(4, 3, 3) # Nx3x3- >>> output = rotation_matrix_to_quaternion(input, eps=torch.finfo(input.dtype).eps,- ... order=QuaternionCoeffOrder.WXYZ) # Nx4+ >>> input = torch.tensor([[1., 0., 0.],+ ... [0., 1., 0.],+ ... [0., 0., 1.]])+ >>> rotation_matrix_to_quaternion(input, eps=torch.finfo(input.dtype).eps,+ ... order=QuaternionCoeffOrder.WXYZ)+ tensor([1., 0., 0., 0.])"""if not isinstance(rotation_matrix, torch.Tensor):raise TypeError(f"Input type is not a torch.Tensor. Got {type(rotation_matrix)}")@@ -561,8 +588,9 @@ def quaternion_to_angle_axis(- Output: :math:`(*, 3)`Example:- >>> quaternion = torch.rand(2, 4) # Nx4- >>> angle_axis = quaternion_to_angle_axis(quaternion) # Nx3+ >>> quaternion = torch.tensor((1., 0., 0., 0.))+ >>> quaternion_to_angle_axis(quaternion)+ tensor([3.1416, 0.0000, 0.0000])"""if not torch.is_tensor(quaternion):raise TypeError(f"Input type is not a torch.Tensor. Got {type(quaternion)}")@@ -756,8 +784,9 @@ def angle_axis_to_quaternion(- Output: :math:`(*, 4)`Example:- >>> angle_axis = torch.rand(2, 3) # Nx3- >>> quaternion = angle_axis_to_quaternion(angle_axis, order=QuaternionCoeffOrder.WXYZ) # Nx4+ >>> angle_axis = torch.tensor((0., 1., 0.))+ >>> angle_axis_to_quaternion(angle_axis, order=QuaternionCoeffOrder.WXYZ)+ tensor([0.8776, 0.0000, 0.4794, 0.0000])"""if not torch.is_tensor(angle_axis):raise TypeError(f"Input type is not a torch.Tensor. Got {type(angle_axis)}")@@ -827,10 +856,16 @@ def normalize_pixel_coordinates(eps: safe division by zero.Return:- the normalized pixel coordinates.+ the normalized pixel coordinates with shape :math:`(*, 2)`.++ Examples:+ >>> coords = torch.tensor([[50., 100.]])+ >>> normalize_pixel_coordinates(coords, 100, 50)+ tensor([[1.0408, 1.0202]])"""if pixel_coordinates.shape[-1] != 2:raise ValueError("Input pixel_coordinates must be of shape (*, 2). " "Got {}".format(pixel_coordinates.shape))+# compute normalization factorhw: torch.Tensor = torch.stack([@@ -860,7 +895,12 @@ def denormalize_pixel_coordinates(eps: safe division by zero.Return:- the denormalized pixel coordinates.+ the denormalized pixel coordinates with shape :math:`(*, 2)`.++ Examples:+ >>> coords = torch.tensor([[-1., -1.]])+ >>> denormalize_pixel_coordinates(coords, 100, 50)+ tensor([[0., 0.]])"""if pixel_coordinates.shape[-1] != 2:raise ValueError("Input pixel_coordinates must be of shape (*, 2). " "Got {}".format(pixel_coordinates.shape))diff --git a/kornia/geometry/depth.py b/kornia/geometry/depth.pyindex 6cd40f1a1..cf8e064a2 100644--- a/kornia/geometry/depth.py+++ b/kornia/geometry/depth.py@@ -23,17 +23,19 @@ def depth_to_3d(depth: torch.Tensor, camera_matrix: torch.Tensor, normalize_poin"""Compute a 3d point per pixel given its depth value and the camera intrinsics.Args:- depth: image tensor containing a depth value per pixel.- camera_matrix: tensor containing the camera intrinsics.+ depth: image tensor containing a depth value per pixel with shape :math:`(B, 1, H, W)`.+ camera_matrix: tensor containing the camera intrinsics with shape :math:`(B, 3, 3)`.normalize_points: whether to normalise the pointcloud. This must be set to `True` when the depth isrepresented as the Euclidean ray length from the camera position.- Shape:- - Input: :math:`(B, 1, H, W)` and :math:`(B, 3, 3)`- - Output: :math:`(B, 3, H, W)`-Return:- tensor with a 3d point per pixel of the same resolution as the input.+ tensor with a 3d point per pixel of the same resolution as the input :math:`(B, 3, H, W)`.++ Example:+ >>> depth = torch.rand(1, 1, 4, 4)+ >>> K = torch.eye(3)[None]+ >>> depth_to_3d(depth, K).shape+ torch.Size([1, 3, 4, 4])"""if not isinstance(depth, torch.Tensor):raise TypeError(f"Input depht type is not a torch.Tensor. Got {type(depth)}.")@@ -68,17 +70,19 @@ def depth_to_normals(depth: torch.Tensor, camera_matrix: torch.Tensor, normalize"""Compute the normal surface per pixel.Args:- depth: image tensor containing a depth value per pixel.- camera_matrix: tensor containing the camera intrinsics.+ depth: image tensor containing a depth value per pixel with shape :math:`(B, 1, H, W)`.+ camera_matrix: tensor containing the camera intrinsics with shape :math:`(B, 3, 3)`.normalize_points: whether to normalise the pointcloud. This must be set to `True` when the depth isrepresented as the Euclidean ray length from the camera position.- Shape:- - Input: :math:`(B, 1, H, W)` and :math:`(B, 3, 3)`- - Output: :math:`(B, 3, H, W)`-Return:- tensor with a normal surface vector per pixel of the same resolution as the input.+ tensor with a normal surface vector per pixel of the same resolution as the input :math:`(B, 3, H, W)`.++ Example:+ >>> depth = torch.rand(1, 1, 4, 4)+ >>> K = torch.eye(3)[None]+ >>> depth_to_normals(depth, K).shape+ torch.Size([1, 3, 4, 4])"""if not isinstance(depth, torch.Tensor):raise TypeError(f"Input depht type is not a torch.Tensor. Got {type(depth)}.")diff --git a/kornia/metrics/accuracy.py b/kornia/metrics/accuracy.pyindex a0ab9a66b..b06a88ed2 100644--- a/kornia/metrics/accuracy.py+++ b/kornia/metrics/accuracy.py@@ -10,6 +10,12 @@ def accuracy(input: torch.Tensor, target: torch.Tensor, topk=(1,)) -> List[torchinput: the input tensor with the logits to evaluate.target: the tensor containing the ground truth.topk: the expected topk ranking.++ Example:+ >>> logits = torch.tensor([[0, 1, 0]])+ >>> target = torch.tensor([[1]])+ >>> accuracy(logits, target)+ [tensor(100.)]"""maxk = min(max(topk), input.size()[1])batch_size = target.size(0)diff --git a/kornia/metrics/confusion_matrix.py b/kornia/metrics/confusion_matrix.pyindex 8bc6ef2e2..996e9c101 100644--- a/kornia/metrics/confusion_matrix.py+++ b/kornia/metrics/confusion_matrix.py@@ -25,6 +25,14 @@ def confusion_matrix(Returns:a tensor containing the confusion matrix with shape:math:`(B, K, K)` where K is the number of classes.++ Example:+ >>> logits = torch.tensor([[0, 1, 0]])+ >>> target = torch.tensor([[0, 1, 0]])+ >>> confusion_matrix(logits, target, num_classes=3)+ tensor([[[2., 0., 0.],+ [0., 1., 0.],+ [0., 0., 0.]]])"""if not torch.is_tensor(input) and input.dtype is not torch.int64:raise TypeError("Input input type is not a torch.Tensor with " "torch.int64 dtype. Got {}".format(type(input)))diff --git a/kornia/metrics/mean_iou.py b/kornia/metrics/mean_iou.pyindex adb9d57f4..9d9b4b1cd 100644--- a/kornia/metrics/mean_iou.py+++ b/kornia/metrics/mean_iou.py@@ -21,6 +21,12 @@ def mean_iou(input: torch.Tensor, target: torch.Tensor, num_classes: int, eps: fReturns:ta tensor representing the mean intersection-over unionwith shape :math:`(B, K)` where K is the number of classes.++ Example:+ >>> logits = torch.tensor([[0, 1, 0]])+ >>> target = torch.tensor([[0, 1, 0]])+ >>> mean_iou(logits, target, num_classes=3)+ tensor([[1., 1., 1.]])"""if not torch.is_tensor(input) and input.dtype is not torch.int64:raise TypeError("Input input type is not a torch.Tensor with " "torch.int64 dtype. Got {}".format(type(input)))diff --git a/kornia/utils/image.py b/kornia/utils/image.pyindex 7f0c131e5..9e878f670 100644--- a/kornia/utils/image.py+++ b/kornia/utils/image.py@@ -20,6 +20,19 @@ def image_to_tensor(image: "np.ndarray", keepdim: bool = True) -> torch.Tensor:Returns:tensor of the form :math:`(B, C, H, W)` if keepdim is ``False``,:math:`(C, H, W)` otherwise.++ Example:+ >>> img = np.ones((3, 3))+ >>> image_to_tensor(img).shape+ torch.Size([1, 3, 3])++ >>> img = np.ones((4, 4, 1))+ >>> image_to_tensor(img).shape+ torch.Size([1, 4, 4])++ >>> img = np.ones((4, 4, 3))+ >>> image_to_tensor(img, keepdim=False).shape+ torch.Size([1, 3, 4, 4])"""if len(image.shape) > 4 or len(image.shape) < 2:raise ValueError("Input size must be a two, three or four dimensional array")@@ -108,9 +121,17 @@ def tensor_to_image(tensor: torch.Tensor, keepdim: bool = False) -> "np.ndarray"keepdim: If ``False`` squeeze the input image to match the shape:math:`(H, W, C)` or :math:`(H, W)`.-Returns:image of the form :math:`(H, W)`, :math:`(H, W, C)` or :math:`(B, H, W, C)`.++ Example:+ >>> img = torch.ones(1, 3, 3)+ >>> tensor_to_image(img).shape+ (3, 3)++ >>> img = torch.ones(3, 4, 4)+ >>> tensor_to_image(img).shape+ (4, 4, 3)"""if not isinstance(tensor, torch.Tensor):raise TypeError(f"Input type is not a torch.Tensor. Got {type(tensor)}")