Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

img to tensor with PIL

dvd42b7996e59f369
diff --git a/kornia/utils/image.py b/kornia/utils/image.py
index 5d098fa16..bbb6bfc98 100644
--- a/kornia/utils/image.py
+++ b/kornia/utils/image.py
@@ -1,49 +1,56 @@
-from typing import Optional
+from typing import Union
+from PIL import Image
import numpy as np
import torch
-def image_to_tensor(image: np.array) -> torch.Tensor:
- """Converts a numpy image to a PyTorch 4d tensor image.
+def image_to_tensor(image: Union[np.ndarray, Image.Image], keepdim: bool = True) -> torch.Tensor:
+ """Converts a numpy or PIL image to a PyTorch 4d tensor image.
Args:
- image (numpy.ndarray): image of the form :math:`(H, W)`,
- math:`(H, W, C)`, or math:`(B, H, W, C)`.
+ image (numpy.ndarray or PIL Image): image of the form math:`(H, W, C)`, math: `(H, W)` or math:`(B, H, W, C)`.
+ keepdim (bool): If ``False`` unsqueeze the input image to match the shape
+ math: `(B, H, W, C)`. Default: ``True``
Returns:
- torch.Tensor: tensor of the form :math:`(H, W)`,
- math:`(B, C, H, W)`.
+ torch.Tensor: tensor of the form math:`(B, C, H, W)` if keepdim is ``False``, math:`(C, H, W)` otherwise.
"""
- if not isinstance(image, np.ndarray):
- raise TypeError("Input type is not a numpy.ndarray. Got {}".format(
+ if not isinstance(image, (np.ndarray, Image.Image)):
+ raise TypeError("Input type must be a numpy.ndarray or PIL Image. Got {}".format(
type(image)))
+ if isinstance(image, Image.Image):
+ image = np.array(image)
+
if len(image.shape) > 4 or len(image.shape) < 2:
raise ValueError(
"Input size must be a two, three or four dimensional array")
input_shape = image.shape
- tensor: torch.Tensor = torch.from_numpy(image)
+ tensor: torch.Tensor = torch.from_numpy(image).to(torch.float)
+
if len(input_shape) == 2:
- # (H, W) -> (1, 1, H, W)
- tensor = tensor.unsqueeze(0).unsqueeze(0)
+ # (H, W) -> (1, H, W)
+ tensor = tensor.unsqueeze(0)
elif len(input_shape) == 3:
# (H, W, C) -> (C, H, W)
- tensor = tensor.permute(2, 0, 1).unsqueeze(0)
+ tensor = tensor.permute(2, 0, 1)
elif len(input_shape) == 4:
# (B, H, W, C) -> (B, C, H, W)
tensor = tensor.permute(0, 3, 1, 2)
+ keepdim = True # no need to unsqueeze
else:
raise ValueError(
"Cannot process image with shape {}".format(input_shape))
- return tensor
+
+ return tensor.unsqueeze(0) if not keepdim else tensor
def tensor_to_image(tensor: torch.Tensor) -> np.array:
- """Converts a PyTorch tensor image to a numpy image. In case the tensor is
- in the GPU, it will be copied back to CPU.
+ """Converts a PyTorch tensor image to a numpy image. In case the tensor is in the GPU,
+ it will be copied back to CPU.
Args:
tensor (torch.Tensor): image of the form :math:`(H, W)`,
diff --git a/requirements.txt b/requirements.txt
index 6ebdf613c..699f8d27b 100644
--- a/requirements.txt
+++ b/requirements.txt
@@ -1,5 +1,6 @@
# core dependencies
pytorch==1.3.0
+pillow==6.2.0
# package
setuptools==41.4.0
diff --git a/test/utils/test_image.py b/test/utils/test_image.py
index 1d0283459..4e7d52550 100644
--- a/test/utils/test_image.py
+++ b/test/utils/test_image.py
@@ -29,6 +29,20 @@ def test_tensor_to_image(input_shape, expected):
((1, 4, 4, 3), (1, 3, 4, 4)), ])
def test_image_to_tensor(input_shape, expected):
image = np.ones(input_shape)
- tensor = kornia.utils.image_to_tensor(image)
+ tensor = kornia.utils.image_to_tensor(image, keepdim=False)
+ assert tensor.shape == expected
+ assert isinstance(tensor, torch.Tensor)
+
+
[email protected]("input_shape, expected",
+ [((4, 4), (1, 4, 4)),
+ ((1, 4, 4), (4, 1, 4)),
+ ((2, 3, 4), (4, 2, 3)),
+ ((4, 4, 3), (3, 4, 4)),
+ ((2, 4, 4, 3), (2, 3, 4, 4)),
+ ((1, 4, 4, 3), (1, 3, 4, 4)), ])
+def test_image_to_tensor_keepdim(input_shape, expected):
+ image = np.ones(input_shape)
+ tensor = kornia.utils.image_to_tensor(image, keepdim=True)
assert tensor.shape == expected
assert isinstance(tensor, torch.Tensor)