π Geometric Computer Vision Library for Spatial AI
Python artificial-intelligencecomputer-visiondeep-learninghacktoberfestimage-processingmachine-learningneural-networkpythonpytorchroboticsspatial-ai
Add function ``image_list_to_tensor`` to utils (#1393)
Yaniv Hollander8328c31a3e62
diff --git a/docs/source/utils.rst b/docs/source/utils.rstindex b8dd1a5bf..b31a93904 100644--- a/docs/source/utils.rst+++ b/docs/source/utils.rst@@ -8,6 +8,7 @@ Image.. autofunction:: tensor_to_image.. autofunction:: image_to_tensor+.. autofunction:: image_list_to_tensor.. autofunction:: draw_rectangleGriddiff --git a/kornia/__init__.py b/kornia/__init__.pyindex 45881b35a..4eeee8472 100644--- a/kornia/__init__.py+++ b/kornia/__init__.py@@ -102,6 +102,7 @@ from kornia.losses import (from kornia.testing import xla_is_availablefrom kornia.utils import (create_meshgrid,+ image_list_to_tensor,image_to_tensor,load_pointcloud_ply,one_hot,diff --git a/kornia/utils/__init__.py b/kornia/utils/__init__.pyindex e51626986..59c7d89b7 100644--- a/kornia/utils/__init__.py+++ b/kornia/utils/__init__.py@@ -1,7 +1,7 @@from .draw import draw_rectanglefrom .grid import create_meshgrid, create_meshgrid3dfrom .helpers import _extract_device_dtype-from .image import image_to_tensor, ImageToTensor, tensor_to_image+from .image import image_list_to_tensor, image_to_tensor, ImageToTensor, tensor_to_imagefrom .memory import batched_forwardfrom .one_hot import one_hotfrom .pointcloud_io import load_pointcloud_ply, save_pointcloud_ply@@ -13,6 +13,7 @@ __all__ = ["create_meshgrid3d","tensor_to_image","image_to_tensor",+ "image_list_to_tensor","save_pointcloud_ply","load_pointcloud_ply","draw_rectangle",diff --git a/kornia/utils/image.py b/kornia/utils/image.pyindex 9e878f670..3e71fcd51 100644--- a/kornia/utils/image.py+++ b/kornia/utils/image.py@@ -1,5 +1,5 @@from functools import wraps-from typing import Callable, TYPE_CHECKING+from typing import Callable, List, TYPE_CHECKINGimport torchimport torch.nn as nn@@ -56,6 +56,33 @@ def image_to_tensor(image: "np.ndarray", keepdim: bool = True) -> torch.Tensor:return tensor.unsqueeze(0) if not keepdim else tensor+def image_list_to_tensor(images: List["np.ndarray"]) -> torch.Tensor:+ """Converts a list of numpy images to a PyTorch 4d tensor image.++ Args:+ images: list of images, each of the form :math:`(H, W, C)`.+ Image shapes must be consistent++ Returns:+ tensor of the form :math:`(B, C, H, W)`.++ Example:+ >>> imgs = [np.ones((4, 4, 1)), np.zeros((4, 4, 1))]+ >>> image_list_to_tensor(imgs).shape+ torch.Size([2, 1, 4, 4])+ """+ if not images:+ raise ValueError("Input list of numpy images is empty")+ if len(images[0].shape) != 3:+ raise ValueError("Input images must be three dimensional arrays")++ list_of_tensors: List[torch.Tensor] = []+ for image in images:+ list_of_tensors.append(image_to_tensor(image))+ tensor: torch.Tensor = torch.stack(list_of_tensors)+ return tensor++def _to_bchw(tensor: torch.Tensor) -> torch.Tensor:"""Convert a PyTorch tensor image to BCHW format.diff --git a/test/utils/test_image.py b/test/utils/test_image.pyindex dd265b5bf..cc5513baa 100644--- a/test/utils/test_image.py+++ b/test/utils/test_image.py@@ -1,3 +1,5 @@+from typing import List+import numpy as npimport pytestimport torch@@ -15,6 +17,30 @@ def test_image_to_tensor_keep_dtype(input_dtype, expected_dtype):assert tensor.dtype == expected_dtype+ "num_of_images, image_shape",+ [+ (2, (4, 3, 1)),+ (0, (1, 2, 3)),+ (5, (2, 3, 2, 5))+ ]+)+def test_list_of_images_to_tensor(num_of_images, image_shape):+ images: List[np.array] = []+ if num_of_images == 0:+ with pytest.raises(ValueError):+ kornia.image_list_to_tensor([])+ return+ for _ in range(num_of_images):+ images.append(np.ones(shape=image_shape))+ if len(image_shape) != 3:+ with pytest.raises(ValueError):+ kornia.image_list_to_tensor(images)+ return+ tensor = kornia.image_list_to_tensor(images)+ assert tensor.shape == (num_of_images, image_shape[-1], image_shape[-3], image_shape[-2])++@pytest.mark.parametrize("input_shape, expected",[