Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

update kornia_rs and make sure contiguous data (#2828)

Edgar Riba618cd3651054
diff --git a/kornia/io/io.py b/kornia/io/io.py
index 22cbae879..a1979c6f9 100644
--- a/kornia/io/io.py
+++ b/kornia/io/io.py
@@ -1,22 +1,17 @@
from __future__ import annotations
-try:
- import kornia_rs
-except ImportError: # pragma: no cover
- kornia_rs = None
-
-import os
from enum import Enum
from pathlib import Path
+import kornia_rs
import torch
-from torch.utils import dlpack # TODO: remove this if kornia relies on torch>=1.10
from kornia.color import rgb_to_grayscale, rgba_to_rgb
from kornia.color.gray import grayscale_to_rgb
from kornia.color.rgb import rgb_to_rgba
from kornia.core import Device, Tensor
from kornia.core.check import KORNIA_CHECK
+from kornia.utils import image_to_tensor, tensor_to_image
class ImageLoadType(Enum):
@@ -30,28 +25,42 @@ class ImageLoadType(Enum):
RGB32 = 5
-def load_image_to_tensor(path_file: str, device: Device) -> Tensor:
- # load the file and decodes using kornia_rs. Internally it uses a package that
- # combines image-rs a self maintained version of the dlpack-rs. After the decoding,
- # the obtained stream bits are encapusalted to a cv::Tensor data structure without
- # memory ownership and passed as PyCapsule from rust to python.
- cv_tensor = kornia_rs.read_image_rs(path_file)
- # for convenience use the torch dlpack parser to get a zero copy torch.Tensor
- # TODO: evaluate other potential API so that we can return in numpy, jax, mxnet since
- # the kornia_rs cv::Tensor has this ability.
- th_tensor = dlpack.from_dlpack(cv_tensor) # HxWx3
- # move the tensor to the desired device, move the data layout to CHW and clone
- # to return an owned data tensor.
+def _load_image_to_tensor(path_file: Path, device: Device) -> Tensor:
+ """Read an image file and decode using the Kornia Rust backend.
+
+ The decoded image is returned as numpy array with shape HxWxC.
+
+ Args:
+ path_file: Path to a valid image file.
+ device: the device where you want to get your image placed.
+
+ Return:
+ Image tensor with shape :math:`(3,H,W)`.
+ """
+
+ # read image and return as `np.ndarray` with shape HxWxC
+ if path_file.suffix.lower() in [".jpg", ".jpeg"]:
+ img = kornia_rs.read_image_jpeg(str(path_file))
+ else:
+ img = kornia_rs.read_image_any(str(path_file))
+
+ # convert the image to tensor with shape CxHxW
+ img_t = image_to_tensor(img, keepdim=True)
+
+ # move the tensor to the desired device,
dev = device if isinstance(device, torch.device) or device is None else torch.device(device)
- return th_tensor.to(device=dev).permute(2, 0, 1).clone() # CxHxW
+
+ return img_t.to(device=dev)
-def to_float32(image: Tensor) -> Tensor:
+def _to_float32(image: Tensor) -> Tensor:
+ """Convert an image tensor to float32."""
KORNIA_CHECK(image.dtype == torch.uint8)
return image.float() / 255.0
-def to_uint8(image: Tensor) -> Tensor:
+def _to_uint8(image: Tensor) -> Tensor:
+ """Convert an image tensor to uint8."""
KORNIA_CHECK(image.dtype == torch.float32)
return image.mul(255.0).byte()
@@ -67,14 +76,11 @@ def load_image(path_file: str | Path, desired_type: ImageLoadType, device: Devic
Return:
Image tensor with shape :math:`(3,H,W)`.
"""
- if kornia_rs is None: # pragma: no cover
- raise ModuleNotFoundError("The io API is not available: `pip install kornia_rs` in a Linux system.")
+ if not isinstance(path_file, Path):
+ path_file = Path(path_file)
- if isinstance(path_file, Path):
- path_file = str(path_file)
-
- KORNIA_CHECK(os.path.isfile(path_file), f"Invalid file: {path_file}")
- image: Tensor = load_image_to_tensor(path_file, device) # CxHxW
+ # read the image using the kornia_rs package
+ image: Tensor = _load_image_to_tensor(path_file, device) # CxHxW
if desired_type == ImageLoadType.UNCHANGED:
return image
@@ -85,8 +91,8 @@ def load_image(path_file: str | Path, desired_type: ImageLoadType, device: Devic
gray8 = rgb_to_grayscale(image)
return gray8
elif image.shape[0] == 4 and image.dtype == torch.uint8:
- gray32 = rgb_to_grayscale(rgba_to_rgb(to_float32(image)))
- return to_uint8(gray32)
+ gray32 = rgb_to_grayscale(rgba_to_rgb(_to_float32(image)))
+ return _to_uint8(gray32)
elif desired_type == ImageLoadType.RGB8:
if image.shape[0] == 3 and image.dtype == torch.uint8:
@@ -97,24 +103,24 @@ def load_image(path_file: str | Path, desired_type: ImageLoadType, device: Devic
elif desired_type == ImageLoadType.RGBA8:
if image.shape[0] == 3 and image.dtype == torch.uint8:
- rgba32 = rgb_to_rgba(to_float32(image), 0.0)
- return to_uint8(rgba32)
+ rgba32 = rgb_to_rgba(_to_float32(image), 0.0)
+ return _to_uint8(rgba32)
elif desired_type == ImageLoadType.GRAY32:
if image.shape[0] == 1 and image.dtype == torch.uint8:
- return to_float32(image)
+ return _to_float32(image)
elif image.shape[0] == 3 and image.dtype == torch.uint8:
- gray32 = rgb_to_grayscale(to_float32(image))
+ gray32 = rgb_to_grayscale(_to_float32(image))
return gray32
elif image.shape[0] == 4 and image.dtype == torch.uint8:
- gray32 = rgb_to_grayscale(rgba_to_rgb(to_float32(image)))
+ gray32 = rgb_to_grayscale(rgba_to_rgb(_to_float32(image)))
return gray32
elif desired_type == ImageLoadType.RGB32:
if image.shape[0] == 3 and image.dtype == torch.uint8:
- return to_float32(image)
+ return _to_float32(image)
elif image.shape[0] == 1 and image.dtype == torch.uint8:
- rgb32 = grayscale_to_rgb(to_float32(image))
+ rgb32 = grayscale_to_rgb(_to_float32(image))
return rgb32
raise NotImplementedError(f"Unknown type: {desired_type}")
@@ -132,28 +138,15 @@ def write_image(path_file: str | Path, image: Tensor) -> None:
Return:
None.
"""
- if kornia_rs is None: # pragma: no cover
- raise ModuleNotFoundError("The io API is not available: `pip install kornia_rs` in a Linux system.")
-
- if isinstance(path_file, Path):
- path_file = str(path_file)
+ if not isinstance(path_file, Path):
+ path_file = Path(path_file)
- KORNIA_CHECK("jpg" in path_file[-3:], f"Invalid file extension: {path_file}")
+ KORNIA_CHECK(path_file.suffix in [".jpg", ".jpeg"], f"Invalid file extension: {path_file}")
KORNIA_CHECK(image.dim() == 3 and image.shape[0] == 3, f"Invalid image shape: {image.shape}")
KORNIA_CHECK(image.dtype == torch.uint8, f"Invalid image dtype: {image.dtype}")
- # create the image encoder
- image_encoder = kornia_rs.ImageEncoder()
- image_encoder.set_quality(100)
-
- # move the tensor to the cpu and clone to avoid memory ownership issues.
- image = image.cpu().clone() # 3xHxW
-
- # move the data layout to HWC and convert to numpy
- image_np = image.permute(1, 2, 0).numpy() # HxWx3
-
- # encode the image using the kornia_rs
- image_encoded: list[int] = image_encoder.encode(image_np.tobytes(), image_np.shape)
+ # convert the tensor to numpy
+ img_np = tensor_to_image(image, keepdim=True, force_contiguous=True) # HxWx3
# save the image using the
- kornia_rs.write_image_jpeg(path_file, image_encoded)
+ kornia_rs.write_image_jpeg(str(path_file), img_np)
diff --git a/kornia/utils/image.py b/kornia/utils/image.py
index 282e05753..6f559bf58 100644
--- a/kornia/utils/image.py
+++ b/kornia/utils/image.py
@@ -136,7 +136,7 @@ def _to_bcdhw(tensor: Tensor) -> Tensor:
return tensor
-def tensor_to_image(tensor: Tensor, keepdim: bool = False) -> Any:
+def tensor_to_image(tensor: Tensor, keepdim: bool = False, force_contiguous: bool = False) -> Any:
"""Converts a PyTorch tensor image to a numpy image.
In case the tensor is in the GPU, it will be copied back to CPU.
@@ -146,6 +146,7 @@ def tensor_to_image(tensor: Tensor, keepdim: bool = False) -> Any:
:math:`(B, C, H, W)`.
keepdim: If ``False`` squeeze the input image to match the shape
:math:`(H, W, C)` or :math:`(H, W)`.
+ force_contiguous: If ``True`` call `contiguous` to the tensor before
Returns:
image of the form :math:`(H, W)`, :math:`(H, W, C)` or :math:`(B, H, W, C)`.
@@ -166,7 +167,7 @@ def tensor_to_image(tensor: Tensor, keepdim: bool = False) -> Any:
raise ValueError("Input size must be a two, three or four dimensional tensor")
input_shape = tensor.shape
- image = tensor.cpu().detach().numpy()
+ image = tensor.cpu().detach()
if len(input_shape) == 2:
# (H, W) -> (H, W)
@@ -177,10 +178,10 @@ def tensor_to_image(tensor: Tensor, keepdim: bool = False) -> Any:
# Grayscale for proper plt.imshow needs to be (H,W)
image = image.squeeze()
else:
- image = image.transpose(1, 2, 0)
+ image = image.permute(1, 2, 0)
elif len(input_shape) == 4:
# (B, C, H, W) -> (B, H, W, C)
- image = image.transpose(0, 2, 3, 1)
+ image = image.permute(0, 2, 3, 1)
if input_shape[0] == 1 and not keepdim:
image = image.squeeze(0)
if input_shape[1] == 1:
@@ -188,7 +189,11 @@ def tensor_to_image(tensor: Tensor, keepdim: bool = False) -> Any:
else:
raise ValueError(f"Cannot process tensor with shape {input_shape}")
- return image
+ # make sure the image is contiguous
+ if force_contiguous:
+ image = image.contiguous()
+
+ return image.numpy()
class ImageToTensor(nn.Module):
diff --git a/requirements/requirements-dev.txt b/requirements/requirements-dev.txt
index 45aedeefe..557e537ef 100644
--- a/requirements/requirements-dev.txt
+++ b/requirements/requirements-dev.txt
@@ -1,5 +1,4 @@
coverage
-kornia-rs==0.0.8
mypy
numpy
onnx
diff --git a/requirements/requirements.txt b/requirements/requirements.txt
index e14e8c983..e6271a6fa 100644
--- a/requirements/requirements.txt
+++ b/requirements/requirements.txt
@@ -1,2 +1,3 @@
+kornia_rs>=0.1.0
packaging
torch>=1.9.1
diff --git a/tests/utils/test_image_utils.py b/tests/utils/test_image_utils.py
index 8fcb441a1..6221bf874 100644
--- a/tests/utils/test_image_utils.py
+++ b/tests/utils/test_image_utils.py
@@ -108,3 +108,13 @@ def test_image_to_tensor_keepdim(input_shape, expected):
tensor = kornia.utils.image_to_tensor(image, keepdim=True)
assert tensor.shape == expected
assert isinstance(tensor, torch.Tensor)
+
+
+def test_tensor_to_image_contiguous(device, dtype):
+ tensor = torch.rand(2, 3, 4, 4, device=device, dtype=dtype)
+
+ image = kornia.utils.tensor_to_image(tensor)
+ assert not image.flags["C_CONTIGUOUS"]
+
+ image = kornia.utils.tensor_to_image(tensor, force_contiguous=True)
+ assert image.flags["C_CONTIGUOUS"]