Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

Breaking change

Dmytro Mishkin7e9dc4af80b9
diff --git a/kornia/utils/image.py b/kornia/utils/image.py
index f39ad8a1a..5d098fa16 100644
--- a/kornia/utils/image.py
+++ b/kornia/utils/image.py
@@ -5,7 +5,7 @@ import torch
def image_to_tensor(image: np.array) -> torch.Tensor:
- """Converts a numpy image to a PyTorch tensor image.
+ """Converts a numpy image to a PyTorch 4d tensor image.
Args:
image (numpy.ndarray): image of the form :math:`(H, W)`,
@@ -13,7 +13,7 @@ def image_to_tensor(image: np.array) -> torch.Tensor:
Returns:
torch.Tensor: tensor of the form :math:`(H, W)`,
- math:`(C, H, W)`, or math:`(B, C, H, W)`.
+ math:`(B, C, H, W)`.
"""
if not isinstance(image, np.ndarray):
@@ -27,11 +27,11 @@ def image_to_tensor(image: np.array) -> torch.Tensor:
input_shape = image.shape
tensor: torch.Tensor = torch.from_numpy(image)
if len(input_shape) == 2:
- # (H, W) -> (H, W)
- tensor = tensor
+ # (H, W) -> (1, 1, H, W)
+ tensor = tensor.unsqueeze(0).unsqueeze(0)
elif len(input_shape) == 3:
# (H, W, C) -> (C, H, W)
- tensor = tensor.permute(2, 0, 1)
+ tensor = tensor.permute(2, 0, 1).unsqueeze(0)
elif len(input_shape) == 4:
# (B, H, W, C) -> (B, C, H, W)
tensor = tensor.permute(0, 3, 1, 2)
@@ -51,7 +51,7 @@ def tensor_to_image(tensor: torch.Tensor) -> np.array:
Returns:
numpy.ndarray: image of the form :math:`(H, W)`,
- math:`(H, W, C)`, or math:`(B, H, W, C)`.
+ math:`(H, W)`, math:`(H, W, C)`, or math:`(B, H, W, C)`.
"""
if not torch.is_tensor(tensor):
@@ -77,6 +77,10 @@ def tensor_to_image(tensor: torch.Tensor) -> np.array:
elif len(input_shape) == 4:
# (B, C, H, W) -> (B, H, W, C)
image = image.transpose(0, 2, 3, 1)
+ if input_shape[0] == 1:
+ image = image.squeeze(0)
+ if input_shape[1] == 1:
+ image = image.squeeze(-1)
else:
raise ValueError(
"Cannot process tensor with shape {}".format(input_shape))
diff --git a/test/utils/test_image.py b/test/utils/test_image.py
index 1775ba06d..1d0283459 100644
--- a/test/utils/test_image.py
+++ b/test/utils/test_image.py
@@ -8,10 +8,11 @@ import kornia.testing as utils # test utils
@pytest.mark.parametrize("input_shape, expected",
[((4, 4), (4, 4)),
- ((1, 4, 4), (4, 4, 1)),
+ ((1, 4, 4), (4, 4)),
+ ((1, 1, 4, 4), (4, 4)),
((3, 4, 4), (4, 4, 3)),
((2, 3, 4, 4), (2, 4, 4, 3)),
- ((1, 3, 4, 4), (1, 4, 4, 3)), ])
+ ((1, 3, 4, 4), (4, 4, 3)), ])
def test_tensor_to_image(input_shape, expected):
tensor = torch.ones(input_shape)
image = kornia.utils.tensor_to_image(tensor)
@@ -20,9 +21,10 @@ def test_tensor_to_image(input_shape, expected):
@pytest.mark.parametrize("input_shape, expected",
- [((4, 4), (4, 4)),
- ((4, 4, 1), (1, 4, 4)),
- ((4, 4, 3), (3, 4, 4)),
+ [((4, 4), (1, 1, 4, 4)),
+ ((1, 4, 4), (1, 4, 1, 4)),
+ ((2, 3, 4), (1, 4, 2, 3)),
+ ((4, 4, 3), (1, 3, 4, 4)),
((2, 4, 4, 3), (2, 3, 4, 4)),
((1, 4, 4, 3), (1, 3, 4, 4)), ])
def test_image_to_tensor(input_shape, expected):