Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

Add function ``image_list_to_tensor`` to utils (#1393)

Yaniv Hollander8328c31a3e62
diff --git a/docs/source/utils.rst b/docs/source/utils.rst
index 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_rectangle
Grid
diff --git a/kornia/__init__.py b/kornia/__init__.py
index 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_available
from 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__.py
index e51626986..59c7d89b7 100644
--- a/kornia/utils/__init__.py
+++ b/kornia/utils/__init__.py
@@ -1,7 +1,7 @@
from .draw import draw_rectangle
from .grid import create_meshgrid, create_meshgrid3d
from .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_image
from .memory import batched_forward
from .one_hot import one_hot
from .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.py
index 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_CHECKING
import torch
import 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.py
index 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 np
import pytest
import 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",
[