Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

create `kornia.io` and implement `load_image` with rust (#1701)

Edgar Riba8cd54e81727e
diff --git a/docs/source/index.rst b/docs/source/index.rst
index 1068b52df..02cd9c501 100644
--- a/docs/source/index.rst
+++ b/docs/source/index.rst
@@ -87,6 +87,7 @@ Join the community
feature
filters
geometry
+ io
losses
metrics
morphology
diff --git a/docs/source/io.rst b/docs/source/io.rst
new file mode 100644
index 000000000..628cebe16
--- /dev/null
+++ b/docs/source/io.rst
@@ -0,0 +1,44 @@
+kornia.io
+=========
+
+.. currentmodule:: kornia.io
+
+Package to load and save image data.
+
+The package internally implements `kornia_rs <https://github.com/kornia/kornia-rs>`_ which contains a low level implementation
+for Computer Vision in the `Rust <https://www.rust-lang.org/>`_ language. In addition, we implement the `DLPack <https://github.com/dmlc/dlpack>`_ protocol
+natively in Rust to reduce the memory footprint during the decoding and types conversion.
+
+.. tip::
+ You need to ``pip install kornia_rs`` to use this package. For now we only support Linux platforms.
+ Contact us or sponsor the project for more support (mac, win, rust, c++, video and camera). See:
+ `https://opencollective.com/kornia <https://opencollective.com/kornia>`_
+
+.. note::
+ The package needs at least PyTorch 1.10.0 installed.
+
+.. code-block:: python
+
+ import kornia as K
+ from kornia.core import Tensor
+
+ img: Tensor = K.io.load_image(file_path, ImageType.UNCHANGED, device="cuda")
+ # will load CxHxW / in the original format in "cuda"
+
+ img: Tensor = K.io.load_image(file_path, ImageType.RGB8, device="cpu")
+ # will load 3xHxW / in torch.uint in range [0,255] in "cpu"
+
+ img: Tensor = K.io.load_image(file_path, ImageType.GRAY8, device="cuda")
+ # will load 1xHxW / in torch.uint8 in range [0,255] in "cuda"
+
+ img: Tensor = K.io.load_image(file_path, ImageType.GRAY32, device="cpu")
+ # will load 1xHxW / in torch.float32 in range [0,1] in "cpu"
+
+ img: Tensor = K.io.load_image(file_path, ImageType.RGB32, device="cuda")
+ # will load 3xHxW / in torch.float32 in range [0,1] in "cuda"
+
+.. autofunction:: load_image
+
+.. autoclass:: ImageLoadType
+ :members:
+ :undoc-members:
diff --git a/kornia/__init__.py b/kornia/__init__.py
index ffebab6a2..aaf5fec5b 100644
--- a/kornia/__init__.py
+++ b/kornia/__init__.py
@@ -12,8 +12,10 @@ from . import (
augmentation,
color,
contrib,
+ core,
enhance,
feature,
+ io,
losses,
metrics,
morphology,
diff --git a/kornia/core/__init__.py b/kornia/core/__init__.py
new file mode 100644
index 000000000..4976385c5
--- /dev/null
+++ b/kornia/core/__init__.py
@@ -0,0 +1,3 @@
+from ._backend import Module, Tensor, concatenate
+
+__all__ = ["concatenate", "Module", "Tensor"]
diff --git a/kornia/core/_backend.py b/kornia/core/_backend.py
new file mode 100644
index 000000000..f84421041
--- /dev/null
+++ b/kornia/core/_backend.py
@@ -0,0 +1,9 @@
+# File containing the backend that defaults to Pytorch.
+import torch
+
+# classes
+Tensor = torch.Tensor
+Module = torch.nn.Module
+
+# functions
+concatenate = torch.cat
diff --git a/kornia/io/__init__.py b/kornia/io/__init__.py
new file mode 100644
index 000000000..df214dc0f
--- /dev/null
+++ b/kornia/io/__init__.py
@@ -0,0 +1 @@
+from .io import ImageLoadType, load_image
diff --git a/kornia/io/io.py b/kornia/io/io.py
new file mode 100644
index 000000000..995d7ec53
--- /dev/null
+++ b/kornia/io/io.py
@@ -0,0 +1,108 @@
+try:
+ import kornia_rs
+except ImportError:
+ kornia_rs = None
+
+import os
+from enum import Enum
+
+import torch
+
+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 Tensor
+from kornia.testing import KORNIA_CHECK
+
+
+class ImageLoadType(Enum):
+ r"""Enum to specify the desired image type"""
+ UNCHANGED = 0
+ GRAY8 = 1
+ RGB8 = 2
+ RGBA8 = 3
+ GRAY32 = 4
+ RGB32 = 5
+
+
+def load_image_to_tensor(path_file: str, device: str) -> 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 = torch.utils.dlpack.from_dlpack(cv_tensor) # type: ignore # HxWx3
+ # move the tensor to the desired device, move the data layout to CHW and clone
+ # to return an owned data tensor.
+ return th_tensor.to(torch.device(device)).permute(2, 0, 1).clone() # CxHxW
+
+
+def to_float32(image: Tensor) -> Tensor:
+ KORNIA_CHECK(image.dtype == torch.uint8)
+ return image.float() / 255.0
+
+
+def to_uint8(image: Tensor) -> Tensor:
+ KORNIA_CHECK(image.dtype == torch.float32)
+ return image.mul(255.0).byte()
+
+
+def load_image(path_file: str, desired_type: ImageLoadType, device: str = "cpu") -> Tensor:
+ """Read an image file and decode using the Kornia Rust backend.
+
+ Args:
+ path_file: Path to a valid image file.
+ desired_type: the desired image type, defined by color space and dtype.
+ device: the device where you want to get your image placed.
+
+ Return:
+ Image tensor with shape :math:`(3,H,W)`.
+ """
+ if kornia_rs is None:
+ raise ModuleNotFoundError("The io API is not available: `pip install kornia_rs` in a Linux system.")
+
+ KORNIA_CHECK(os.path.isfile(path_file), f"Invalid file: {path_file}")
+ image: Tensor = load_image_to_tensor(path_file, device) # CxHxW
+
+ if desired_type == ImageLoadType.UNCHANGED:
+ return image
+ elif desired_type == ImageLoadType.GRAY8:
+ if image.shape[0] == 1 and image.dtype == torch.uint8:
+ return image
+ elif image.shape[0] == 3 and image.dtype == torch.uint8:
+ gray32 = rgb_to_grayscale(to_float32(image))
+ return to_uint8(gray32)
+ elif image.shape[0] == 4 and image.dtype == torch.uint8:
+ 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:
+ return image
+ elif image.shape[0] == 1 and image.dtype == torch.uint8:
+ rgb32 = grayscale_to_rgb(to_float32(image))
+ return to_uint8(rgb32)
+ 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)
+ elif desired_type == ImageLoadType.GRAY32:
+ if image.shape[0] == 1 and image.dtype == torch.uint8:
+ return to_float32(image)
+ elif image.shape[0] == 3 and image.dtype == torch.uint8:
+ 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)))
+ return gray32
+ elif desired_type == ImageLoadType.RGB32:
+ if image.shape[0] == 3 and image.dtype == torch.uint8:
+ return to_float32(image)
+ elif image.shape[0] == 1 and image.dtype == torch.uint8:
+ rgb32 = grayscale_to_rgb(to_float32(image))
+ return rgb32
+ else:
+ raise NotImplementedError(f"Unknown type: {desired_type}")
+ return Tensor([])
diff --git a/requirements/dev.txt b/requirements/dev.txt
index bd2bad766..66302c94c 100644
--- a/requirements/dev.txt
+++ b/requirements/dev.txt
@@ -11,5 +11,7 @@ yapf
isort
numpy
scipy
+opencv-python
+kornia_rs==0.0.2; python_version>="3.7" and sys_platform=="linux"
-r ../docs/requirements.txt
-r ./x.txt # kornia[x]
diff --git a/test/io/test_load_image.py b/test/io/test_load_image.py
new file mode 100644
index 000000000..fce56fc0a
--- /dev/null
+++ b/test/io/test_load_image.py
@@ -0,0 +1,108 @@
+import os
+import sys
+import tempfile
+
+import cv2
+import numpy as np
+import pytest
+import torch
+
+from kornia.core import Tensor
+from kornia.io import ImageLoadType, load_image
+from kornia.utils._compat import torch_version_geq
+
+try:
+ import kornia_rs
+except ImportError:
+ kornia_rs = None
+
+
+def available_package() -> bool:
+ return (
+ sys.version_info >= (3, 7, 0) and sys.platform == "linux" and torch_version_geq(1, 10) and kornia_rs is not None
+ )
+
+
+def create_random_img8(height: int, width: int, channels: int) -> np.ndarray:
+ return (np.random.rand(height, width, channels) * 255).astype(np.uint8)
+
+
[email protected](not available_package(), reason="kornia_rs only supports python >=3.7 and pt >= 1.10.0")
+class TestLoadImage:
+ def test_smoke(self):
+ height, width = 4, 5
+ img_np: np.ndarray = create_random_img8(height, width, 3)
+ with tempfile.NamedTemporaryFile() as tmp:
+
+ file_path: str = tmp.name + ".png"
+ cv2.imwrite(file_path, img_np)
+ assert os.path.isfile(file_path)
+
+ img_cv: np.ndarray = cv2.imread(file_path)
+ img_th: Tensor = load_image(file_path, ImageLoadType.UNCHANGED)
+
+ assert img_cv.shape[:2] == img_th.shape[1:]
+ assert img_th.shape[1:] == (height, width)
+ assert str(img_th.device) == "cpu"
+
+ def test_device(self, device):
+ height, width = 4, 5
+ img_np: np.ndarray = create_random_img8(height, width, 3)
+ with tempfile.NamedTemporaryFile() as tmp:
+
+ file_path: str = tmp.name + ".png"
+ cv2.imwrite(file_path, img_np)
+ assert os.path.isfile(file_path)
+
+ img_th: Tensor = load_image(file_path, ImageLoadType.UNCHANGED, str(device))
+ assert str(img_th.device) == str(device)
+
+ @pytest.mark.parametrize("ext", ["png", "jpg"])
+ def test_types_color(self, ext):
+ height, width = 4, 5
+ img_np: np.ndarray = create_random_img8(height, width, 3)
+ with tempfile.NamedTemporaryFile() as tmp:
+
+ file_path: str = tmp.name + f".{ext}"
+ cv2.imwrite(file_path, img_np)
+ assert os.path.isfile(file_path)
+
+ img = load_image(file_path, ImageLoadType.GRAY8)
+ assert img.shape[0] == 1 and img.dtype == torch.uint8
+
+ img = load_image(file_path, ImageLoadType.GRAY32)
+ assert img.shape[0] == 1 and img.dtype == torch.float32
+
+ img = load_image(file_path, ImageLoadType.RGB8)
+ assert img.shape[0] == 3 and img.dtype == torch.uint8
+
+ img = load_image(file_path, ImageLoadType.RGB32)
+ assert img.shape[0] == 3 and img.dtype == torch.float32
+
+ img = load_image(file_path, ImageLoadType.RGBA8)
+ assert img.shape[0] == 4 and img.dtype == torch.uint8
+
+ @pytest.mark.parametrize("ext", ["png", "jpg"])
+ def test_types_gray(self, ext):
+ height, width = 4, 5
+ img_np: np.ndarray = create_random_img8(height, width, 1)
+ with tempfile.NamedTemporaryFile() as tmp:
+
+ file_path: str = tmp.name + f".{ext}"
+ cv2.imwrite(file_path, img_np)
+ assert os.path.isfile(file_path)
+
+ img = load_image(file_path, ImageLoadType.GRAY8)
+ assert img.shape[0] == 1 and img.dtype == torch.uint8
+
+ img = load_image(file_path, ImageLoadType.GRAY32)
+ assert img.shape[0] == 1 and img.dtype == torch.float32
+
+ img = load_image(file_path, ImageLoadType.RGB8)
+ assert img.shape[0] == 3 and img.dtype == torch.uint8
+
+ img = load_image(file_path, ImageLoadType.RGB32)
+ assert img.shape[0] == 3 and img.dtype == torch.float32
+
+ img = load_image(file_path, ImageLoadType.RGBA8)
+ assert img.shape[0] == 4 and img.dtype == torch.uint8