Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

Add Image API (#1562)

Edgar Ribaac6b4e1f611a
diff --git a/docs/source/core.rst b/docs/source/core.rst
new file mode 100644
index 000000000..5b63af38d
--- /dev/null
+++ b/docs/source/core.rst
@@ -0,0 +1,8 @@
+kornia.core
+===========
+
+.. currentmodule:: kornia.core
+
+.. autoclass:: TensorWrapper
+ :members:
+ :undoc-members:
diff --git a/docs/source/image.rst b/docs/source/image.rst
new file mode 100644
index 000000000..b7e5e18aa
--- /dev/null
+++ b/docs/source/image.rst
@@ -0,0 +1,26 @@
+kornia.image
+============
+
+Module to provide a high level API to process images.
+
+.. currentmodule:: kornia.image
+
+.. autoclass:: ImageSize
+ :members:
+ :undoc-members:
+
+.. autoclass:: PixelFormat
+ :members:
+ :undoc-members:
+
+.. autoclass:: ChannelsOrder
+ :members:
+ :undoc-members:
+
+.. autoclass:: ImageLayout
+ :members:
+ :undoc-members:
+
+.. autoclass:: Image
+ :members:
+ :undoc-members:
diff --git a/docs/source/index.rst b/docs/source/index.rst
index 72a8895aa..da9bd89b4 100644
--- a/docs/source/index.rst
+++ b/docs/source/index.rst
@@ -57,12 +57,14 @@ Join the community
augmentation
color
contrib
+ core
enhance
feature
filters
geometry
sensors
io
+ image
losses
metrics
morphology
diff --git a/docs/source/io.rst b/docs/source/io.rst
index 12955d839..52af2fab9 100644
--- a/docs/source/io.rst
+++ b/docs/source/io.rst
@@ -39,6 +39,7 @@ natively in Rust to reduce the memory footprint during the decoding and types co
# will load 3xHxW / in torch.float32 in range [0,1] in "cuda"
.. autofunction:: load_image
+.. autofunction:: write_image
.. autoclass:: ImageLoadType
:members:
diff --git a/kornia/color/gray.py b/kornia/color/gray.py
index 578180fb0..47ec98bfe 100644
--- a/kornia/color/gray.py
+++ b/kornia/color/gray.py
@@ -1,4 +1,4 @@
-from typing import Optional
+from __future__ import annotations
import torch
@@ -15,7 +15,7 @@ def grayscale_to_rgb(image: Tensor) -> Tensor:
The image data is assumed to be in the range of (0, 1).
Args:
- image: grayscale image to be converted to RGB with shape :math:`(*,1,H,W)`.
+ image: grayscale image tensor to be converted to RGB with shape :math:`(*,1,H,W)`.
Returns:
RGB version of the image with shape :math:`(*,3,H,W)`.
@@ -26,13 +26,13 @@ def grayscale_to_rgb(image: Tensor) -> Tensor:
"""
KORNIA_CHECK_IS_TENSOR(image)
- if image.dim() < 3 or image.size(-3) != 1:
+ if len(image.shape) < 3 or image.shape[-3] != 1:
raise ValueError(f"Input size must have a shape of (*, 1, H, W). " f"Got {image.shape}.")
return concatenate([image, image, image], -3)
-def rgb_to_grayscale(image: Tensor, rgb_weights: Optional[Tensor] = None) -> Tensor:
+def rgb_to_grayscale(image: Tensor, rgb_weights: Tensor | None = None) -> Tensor:
r"""Convert a RGB image to grayscale version of image.
.. image:: _static/img/rgb_to_grayscale.png
@@ -81,7 +81,7 @@ def rgb_to_grayscale(image: Tensor, rgb_weights: Optional[Tensor] = None) -> Ten
return w_r * r + w_g * g + w_b * b
-def bgr_to_grayscale(image: torch.Tensor) -> torch.Tensor:
+def bgr_to_grayscale(image: Tensor) -> Tensor:
r"""Convert a BGR image to grayscale.
The image data is assumed to be in the range of (0, 1). First flips to RGB, then converts.
@@ -145,8 +145,10 @@ class RgbToGrayscale(Module):
>>> output = gray(input) # 2x1x4x5
"""
- def __init__(self, rgb_weights: Optional[Tensor] = None) -> None:
+ def __init__(self, rgb_weights: Tensor | None = None) -> None:
super().__init__()
+ if rgb_weights is None:
+ rgb_weights = Tensor([0.299, 0.587, 0.114])
self.rgb_weights = rgb_weights
def forward(self, image: Tensor) -> Tensor:
diff --git a/kornia/core/__init__.py b/kornia/core/__init__.py
index c6f079935..424fab722 100644
--- a/kornia/core/__init__.py
+++ b/kornia/core/__init__.py
@@ -25,6 +25,7 @@ from ._backend import (
zeros,
zeros_like,
)
+from .tensor_wrapper import TensorWrapper # type: ignore
__all__ = [
"arange",
@@ -52,4 +53,5 @@ __all__ = [
"zeros_like",
"linspace",
"diag",
+ "TensorWrapper",
]
diff --git a/kornia/core/_backend.py b/kornia/core/_backend.py
index 13df081d9..df8f4c366 100644
--- a/kornia/core/_backend.py
+++ b/kornia/core/_backend.py
@@ -1,8 +1,8 @@
+from __future__ import annotations
+
from typing import Union
import torch
-import torch.nn.functional as F
-from torch import device
# classes
Tensor = torch.Tensor
@@ -17,8 +17,8 @@ arange = torch.arange
concatenate = torch.cat
stack = torch.stack
linspace = torch.linspace
-normalize = F.normalize
-pad = F.pad
+normalize = torch.nn.functional.normalize
+pad = torch.nn.functional.pad
eye = torch.eye
einsum = torch.einsum
zeros = torch.zeros
@@ -28,7 +28,7 @@ ones_like = torch.ones_like
where = torch.where
complex = torch.complex
diag = torch.diag
-softmax = F.softmax
+softmax = torch.nn.functional.softmax
# constructors
@@ -38,5 +38,5 @@ as_tensor = torch.as_tensor
rand = torch.rand
# type alias
-Device = Union[str, device, None]
+Device = Union[str, torch.device, None]
Dtype = Union[torch.dtype, None]
diff --git a/kornia/image/__init__.py b/kornia/image/__init__.py
index 4fc36518e..e7a1d1c52 100644
--- a/kornia/image/__init__.py
+++ b/kornia/image/__init__.py
@@ -1 +1,4 @@
-from .base import ImageSize
+from .base import ChannelsOrder, ImageLayout, ImageSize, PixelFormat
+from .image import Image
+
+__all__ = ["ImageSize", "PixelFormat", "ChannelsOrder", "ImageLayout", "Image"]
diff --git a/kornia/image/base.py b/kornia/image/base.py
index f2c08ed4d..a351c415c 100644
--- a/kornia/image/base.py
+++ b/kornia/image/base.py
@@ -1,17 +1,19 @@
from __future__ import annotations
from dataclasses import dataclass
+from enum import Enum
from kornia.core import Tensor
-@dataclass
+@dataclass(frozen=True)
class ImageSize:
r"""Data class to represent image shape.
Args:
height: image height.
- width: image width
+ width: image width.
+
Example:
>>> size = ImageSize(3, 4)
>>> size.height
@@ -21,3 +23,64 @@ class ImageSize:
"""
height: int | Tensor
width: int | Tensor
+
+
+class ColorSpace(Enum):
+ r"""Enum that represents the color space of an image."""
+ UNKNOWN = 0 # for now, in case of multi band images
+ GRAY = 1
+ RGB = 2
+ BGR = 3
+
+
+@dataclass(frozen=True)
+class PixelFormat:
+ r"""Data class to represent the pixel format of an image.
+
+ Args:
+ color_space: color space.
+ bit_depth: the number of bits per channel.
+
+ Example:
+ >>> pixel_format = PixelFormat(ColorSpace.RGB, 8)
+ >>> pixel_format.color_space
+ <ColorSpace.RGB: 2>
+ >>> pixel_format.bit_depth
+ 8
+ """
+
+ color_space: ColorSpace
+ bit_depth: int
+
+
+class ChannelsOrder(Enum):
+ r"""Enum that represents the channels order of an image."""
+ CHANNELS_FIRST = 0
+ CHANNELS_LAST = 1
+
+
+@dataclass(frozen=True)
+class ImageLayout:
+ """Data class to represent the layout of an image.
+
+ Args:
+ image_size: image size.
+ channels: number of channels.
+ channels_order: channels order.
+
+ Example:
+ >>> layout = ImageLayout(ImageSize(3, 4), 3, ChannelsOrder.CHANNELS_LAST)
+ >>> layout.image_size
+ ImageSize(height=3, width=4)
+ >>> layout.channels
+ 3
+ >>> layout.channels_order
+ <ChannelsOrder.CHANNELS_LAST: 1>
+ """
+
+ image_size: ImageSize
+ channels: int
+ channels_order: ChannelsOrder
+
+
+# TODO: define CompressedImage
diff --git a/kornia/image/image.py b/kornia/image/image.py
new file mode 100644
index 000000000..90f92dcbb
--- /dev/null
+++ b/kornia/image/image.py
@@ -0,0 +1,269 @@
+from __future__ import annotations
+
+from pathlib import Path
+from typing import Any
+
+import torch
+from torch.utils.dlpack import from_dlpack, to_dlpack
+
+from kornia.core import Device, Dtype, Tensor
+from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_SHAPE
+from kornia.image.base import ChannelsOrder, ColorSpace, ImageLayout, ImageSize, PixelFormat
+from kornia.io.io import ImageLoadType, load_image, write_image
+
+# placeholder for numpy
+np_ndarray = Any
+DLPack = Any
+
+
+class Image:
+ r"""Class that holds an Image Tensor representation.
+
+ .. note::
+
+ Disclaimer: This class provides the minimum functionality for image manipulation. However, as soon
+ as you start to experiment with advanced tensor manipulation, you might expect fancy
+ polymorphic behaviours.
+
+ .. warning::
+
+ This API is experimental and might suffer changes in the future.
+
+ Args:
+ data: a torch tensor containing the image data.
+ layout: a dataclass containing the image layout information.
+
+ Examples:
+ >>> # from a torch.tensor
+ >>> data = torch.randint(0, 255, (3, 4, 5), dtype=torch.uint8) # CxHxW
+ >>> pixel_format = PixelFormat(
+ ... color_space=ColorSpace.RGB,
+ ... bit_depth=8,
+ ... )
+ >>> layout = ImageLayout(
+ ... image_size=ImageSize(4, 5),
+ ... channels=3,
+ ... channels_order=ChannelsOrder.CHANNELS_FIRST,
+ ... )
+ >>> img = Image(data, pixel_format, layout)
+ >>> assert img.channels == 3
+
+ >>> # from a numpy array (like opencv)
+ >>> data = np.ones((4, 5, 3), dtype=np.uint8) # HxWxC
+ >>> img = Image.from_numpy(data, color_space=ColorSpace.RGB)
+ >>> assert img.channels == 3
+ >>> assert img.width == 5
+ >>> assert img.height == 4
+ """
+
+ def __init__(self, data: Tensor, pixel_format: PixelFormat, layout: ImageLayout) -> None:
+ """Image constructor.
+
+ Args:
+ data: a torch tensor containing the image data.
+ pixel_format: the pixel format of the image.
+ layout: a dataclass containing the image layout information.
+ """
+ # TODO: move this to a function KORNIA_CHECK_IMAGE_LAYOUT
+ if layout.channels_order == ChannelsOrder.CHANNELS_FIRST:
+ shape = [str(layout.channels), str(layout.image_size.height), str(layout.image_size.width)]
+ elif layout.channels_order == ChannelsOrder.CHANNELS_LAST:
+ shape = [str(layout.image_size.height), str(layout.image_size.width), str(layout.channels)]
+ else:
+ raise NotImplementedError(f"Layout {layout.channels_order} not implemented.")
+
+ KORNIA_CHECK_SHAPE(data, shape)
+ KORNIA_CHECK(data.element_size() == pixel_format.bit_depth // 8, "Invalid bit depth.")
+
+ self._data = data
+ self._pixel_format = pixel_format
+ self._layout = layout
+
+ def __repr__(self) -> str:
+ return f"Image data: {self.data}\nPixel Format: {self.pixel_format}\n Layout: {self.layout}"
+
+ # TODO: explore use TensorWrapper
+ def to(self, device: Device = None, dtype: Dtype = None) -> Image:
+ if device is not None and isinstance(device, torch.dtype):
+ dtype, device = device, None
+ # put the data to the device and dtype
+ self._data = self.data.to(device, dtype)
+ return self
+
+ # TODO: explore use TensorWrapper
+ def clone(self) -> Image:
+ return Image(self.data.clone(), self.pixel_format, self.layout)
+
+ @property
+ def data(self) -> Tensor:
+ """Return the underlying tensor data."""
+ return self._data
+
+ @property
+ def shape(self) -> tuple[int, ...]:
+ """Return the image shape."""
+ return self.data.shape
+
+ @property
+ def dtype(self) -> torch.dtype:
+ """Return the image data type."""
+ return self.data.dtype
+
+ @property
+ def device(self) -> torch.device:
+ """Return the image device."""
+ return self.data.device
+
+ @property
+ def pixel_format(self) -> PixelFormat:
+ """Return the pixel format."""
+ return self._pixel_format
+
+ @property
+ def layout(self) -> ImageLayout:
+ """Return the image layout."""
+ return self._layout
+
+ @property
+ def channels(self) -> int:
+ """Return the number channels of the image."""
+ return self.layout.channels
+
+ @property
+ def image_size(self) -> ImageSize:
+ """Return the image size."""
+ return self.layout.image_size
+
+ @property
+ def height(self) -> int:
+ """Return the image height (columns)."""
+ return int(self.layout.image_size.height)
+
+ @property
+ def width(self) -> int:
+ """Return the image width (rows)."""
+ return int(self.layout.image_size.width)
+
+ @property
+ def channels_order(self) -> ChannelsOrder:
+ """Return the channels order."""
+ return self.layout.channels_order
+
+ # TODO: figure out a better way map this function
+ def float(self) -> Image:
+ """Return the image as float."""
+ self._data = self.data.float()
+ return self
+
+ # TODO implement this
+ def to_color_space(self, color_space: ColorSpace) -> Image:
+ """Convert the image to a different color space."""
+ raise NotImplementedError
+
+ @classmethod
+ def from_numpy(
+ cls,
+ data: np_ndarray,
+ color_space: ColorSpace = ColorSpace.RGB,
+ channels_order: ChannelsOrder = ChannelsOrder.CHANNELS_LAST,
+ ) -> Image:
+ """Construct an image tensor from a numpy array.
+
+ Args:
+ data: a numpy array containing the image data.
+ color_space: the color space of the image.
+ pixel_format: the pixel format of the image.
+
+ Example:
+ >>> data = np.ones((4, 5, 3), dtype=np.uint8) # HxWxC
+ >>> img = Image.from_numpy(data, color_space=ColorSpace.RGB)
+ >>> assert img.channels == 3
+ >>> assert img.width == 5
+ >>> assert img.height == 4
+ """
+ if channels_order == ChannelsOrder.CHANNELS_LAST:
+ image_size = ImageSize(height=data.shape[0], width=data.shape[1])
+ channels = data.shape[2]
+ elif channels_order == ChannelsOrder.CHANNELS_FIRST:
+ image_size = ImageSize(height=data.shape[1], width=data.shape[2])
+ channels = data.shape[0]
+ else:
+ raise ValueError("channels_order must be either `CHANNELS_LAST` or `CHANNELS_FIRST`")
+
+ # create the pixel format based on the input data
+ pixel_format = PixelFormat(color_space=color_space, bit_depth=data.itemsize * 8)
+
+ # create the image layout based on the input data
+ layout = ImageLayout(image_size=image_size, channels=channels, channels_order=channels_order)
+
+ # create the image tensor
+ return cls(torch.from_numpy(data), pixel_format, layout)
+
+ def to_numpy(self) -> np_ndarray:
+ """Return a numpy array in cpu from the image tensor."""
+ return self.data.cpu().detach().numpy()
+
+ @classmethod
+ def from_dlpack(cls, data: DLPack) -> Image:
+ """Construct an image tensor from a DLPack capsule.
+
+ Args:
+ data: a DLPack capsule from numpy, tvm or jax.
+
+ Example:
+ >>> x = np.ones((4, 5, 3))
+ >>> img = Image.from_dlpack(x.__dlpack__())
+ """
+ _data: Tensor = from_dlpack(data)
+
+ pixel_format = PixelFormat(color_space=ColorSpace.RGB, bit_depth=_data.element_size() * 8)
+
+ # create the image layout based on the input data
+ layout = ImageLayout(
+ image_size=ImageSize(height=_data.shape[1], width=_data.shape[2]),
+ channels=_data.shape[0],
+ channels_order=ChannelsOrder.CHANNELS_FIRST,
+ )
+
+ return cls(_data, pixel_format, layout)
+
+ def to_dlpack(self) -> DLPack:
+ """Return a DLPack capsule from the image tensor."""
+ return to_dlpack(self.data)
+
+ @classmethod
+ def from_file(cls, file_path: str | Path) -> Image:
+ """Construct an image tensor from a file.
+
+ Args:
+ file_path: the path to the file to read the image from.
+ """
+ # TODO: allow user to specify the desired type and device
+ data: Tensor = load_image(file_path, desired_type=ImageLoadType.RGB8, device="cpu")
+
+ pixel_format = PixelFormat(color_space=ColorSpace.RGB, bit_depth=data.element_size() * 8)
+
+ layout = ImageLayout(
+ image_size=ImageSize(height=data.shape[1], width=data.shape[2]),
+ channels=data.shape[0],
+ channels_order=ChannelsOrder.CHANNELS_FIRST,
+ )
+ return cls(data, pixel_format, layout)
+
+ def write(self, file_path: str | Path) -> None:
+ """Write the image to a file.
+
+ For now, only support writing to JPEG format.
+
+ Args:
+ file_path: the path to the file to write the image to.
+
+ Example:
+ >>> data = np.ones((4, 5, 3), dtype=np.uint8) # HxWxC
+ >>> img = Image.from_numpy(data)
+ >>> img.write("test.jpg")
+ """
+ data = self.data
+ if self.channels_order == ChannelsOrder.CHANNELS_LAST:
+ data = data.permute(2, 0, 1)
+ write_image(file_path, data)
diff --git a/kornia/io/__init__.py b/kornia/io/__init__.py
index df214dc0f..9832888a5 100644
--- a/kornia/io/__init__.py
+++ b/kornia/io/__init__.py
@@ -1 +1,3 @@
-from .io import ImageLoadType, load_image
+from .io import ImageLoadType, load_image, write_image
+
+__all__ = ["ImageLoadType", "load_image", "write_image"]
diff --git a/kornia/io/io.py b/kornia/io/io.py
index 7c0534813..207e50f01 100644
--- a/kornia/io/io.py
+++ b/kornia/io/io.py
@@ -1,3 +1,5 @@
+from __future__ import annotations
+
try:
import kornia_rs
except ImportError:
@@ -5,9 +7,10 @@ except ImportError:
import os
from enum import Enum
+from pathlib import Path
import torch
-from torch.utils import dlpack # TODO: remove this if kornia relies on torch>=1.10
+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
@@ -52,7 +55,7 @@ def to_uint8(image: Tensor) -> Tensor:
return image.mul(255.0).byte()
-def load_image(path_file: str, desired_type: ImageLoadType, device: Device = "cpu") -> Tensor:
+def load_image(path_file: str | Path, desired_type: ImageLoadType, device: Device = "cpu") -> Tensor:
"""Read an image file and decode using the Kornia Rust backend.
Args:
@@ -66,6 +69,9 @@ def load_image(path_file: str, desired_type: ImageLoadType, device: Device = "cp
if kornia_rs is None:
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)
+
KORNIA_CHECK(os.path.isfile(path_file), f"Invalid file: {path_file}")
image: Tensor = load_image_to_tensor(path_file, device) # CxHxW
@@ -108,3 +114,42 @@ def load_image(path_file: str, desired_type: ImageLoadType, device: Device = "cp
else:
raise NotImplementedError(f"Unknown type: {desired_type}")
return Tensor([])
+
+
+def write_image(path_file: str | Path, image: Tensor) -> None:
+ """Save an image file using the Kornia Rust backend.
+
+ For now, we only support the writing of JPEG of the following types: RGB8.
+
+ Args:
+ path_file: Path to a valid image file.
+ image: Image tensor with shape :math:`(3,H,W)`.
+
+ Return:
+ None.
+ """
+ if kornia_rs is None:
+ 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)
+
+ KORNIA_CHECK("jpg" in path_file[-3:], 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)
+
+ # save the image using the
+ kornia_rs.write_image_jpeg(path_file, image_encoded)
diff --git a/test/image/test_image.py b/test/image/test_image.py
new file mode 100644
index 000000000..67fd3efe6
--- /dev/null
+++ b/test/image/test_image.py
@@ -0,0 +1,81 @@
+from pathlib import Path
+
+import numpy as np
+import pytest
+import torch
+
+from kornia.image.base import ChannelsOrder, ColorSpace, ImageLayout, ImageSize, PixelFormat
+from kornia.image.image import Image
+from kornia.testing import assert_close
+from kornia.utils._compat import torch_version_le
+
+
+class TestImage:
+ def test_smoke(self, device):
+ data = torch.randint(0, 255, (3, 4, 5), device=device, dtype=torch.uint8)
+ pixel_format = PixelFormat(color_space=ColorSpace.RGB, bit_depth=8)
+ layout = ImageLayout(image_size=ImageSize(4, 5), channels=3, channels_order=ChannelsOrder.CHANNELS_FIRST)
+
+ img = Image(data, pixel_format, layout)
+ assert isinstance(img, Image)
+ assert img.channels == 3
+ assert img.height == 4
+ assert img.width == 5
+ assert img.shape == (3, 4, 5)
+ assert img.device == device
+ assert img.dtype == torch.uint8
+ assert img.layout == layout
+ assert img.pixel_format.color_space == ColorSpace.RGB
+ assert img.pixel_format.bit_depth == 8
+ assert img.channels_order == ChannelsOrder.CHANNELS_FIRST
+
+ def test_numpy(self, device):
+ # as it was from cv2.imread
+ data = np.ones((4, 5, 3), dtype=np.uint8)
+ img = Image.from_numpy(data, color_space=ColorSpace.RGB)
+ img = img.to(device)
+ assert isinstance(img, Image)
+ assert img.channels == 3
+ assert img.height == 4
+ assert img.width == 5
+ assert img.pixel_format.color_space == ColorSpace.RGB
+ assert img.shape == (4, 5, 3)
+ assert img.device == device
+ assert img.dtype == torch.uint8
+ assert_close(data, img.to_numpy())
+
+ # check clone
+ img2 = img.clone()
+ assert isinstance(img2, Image)
+ img2 = img2.to(device)
+ assert img2.dtype == torch.uint8
+ assert img2.device == device
+ img3 = img2.to(torch.uint8)
+ assert isinstance(img3, Image)
+ assert img3.dtype == torch.uint8
+ assert img3.device == device
+
+ def test_dlpack(self, device, dtype):
+ data = torch.rand((3, 4, 5), device=device, dtype=dtype)
+ pixel_format = PixelFormat(color_space=ColorSpace.RGB, bit_depth=data.element_size() * 8)
+ layout = ImageLayout(image_size=ImageSize(4, 5), channels=3, channels_order=ChannelsOrder.CHANNELS_FIRST)
+ img = Image(data, pixel_format=pixel_format, layout=layout)
+ assert_close(data, Image.from_dlpack(img.to_dlpack()).data)
+
+ @pytest.mark.skipif(torch_version_le(1, 9, 1), reason="dlpack is broken in torch<=1.9.1")
+ def test_load_write(self, tmp_path: Path) -> None:
+ data = torch.randint(0, 255, (3, 4, 5), dtype=torch.uint8)
+ img = Image.from_numpy(data.numpy(), channels_order=ChannelsOrder.CHANNELS_FIRST)
+
+ file_name = tmp_path / "image.jpg"
+
+ img.write(file_name)
+ img2 = Image.from_file(file_name)
+
+ # NOTE: the tolerance is high due to the jpeg compression
+ assert (img.float().data - img2.float().data).pow(2).mean() <= 0.75
+
+ def test_write_first_channel(self, tmp_path: Path) -> None:
+ data = np.ones((4, 5, 3), dtype=np.uint8)
+ img = Image.from_numpy(data, color_space=ColorSpace.RGB, channels_order=ChannelsOrder.CHANNELS_LAST)
+ img.write(tmp_path / "image.jpg")
diff --git a/test/io/test_io_image.py b/test/io/test_io_image.py
new file mode 100644
index 000000000..50fa981f4
--- /dev/null
+++ b/test/io/test_io_image.py
@@ -0,0 +1,118 @@
+import sys
+from pathlib import Path
+
+import cv2
+import numpy as np
+import pytest
+import torch
+
+from kornia.core import Tensor
+from kornia.io import ImageLoadType, load_image, write_image
+from kornia.utils._compat import torch_version_ge
+
+try:
+ import kornia_rs
+except ImportError:
+ kornia_rs = None
+
+
+def available_package() -> bool:
+ return sys.version_info >= (3, 7, 0) and torch_version_ge(1, 10, 0) 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) # noqa: NPY002
+
+
+def create_random_img8_torch(height: int, width: int, channels: int) -> Tensor:
+ return (torch.rand(channels, height, width) * 255).to(torch.uint8)
+
+
[email protected](not available_package(), reason="kornia_rs only supports python >=3.7 and pt >= 1.10.0")
+class TestIoImage:
+ def test_smoke(self, tmp_path: Path) -> None:
+ height, width = 4, 5
+ img_th: Tensor = create_random_img8_torch(height, width, 3)
+
+ file_path = tmp_path / "image.jpg"
+ write_image(file_path, img_th)
+
+ assert file_path.is_file()
+
+ img_load: Tensor = load_image(file_path, ImageLoadType.UNCHANGED)
+
+ assert img_th.shape == img_load.shape
+ assert img_th.shape[1:] == (height, width)
+ assert str(img_th.device) == "cpu"
+
+ def test_device(self, device, tmp_path: Path) -> None:
+ height, width = 4, 5
+ img_np: np.ndarray = create_random_img8(height, width, 3)
+
+ file_path = tmp_path / "image.png"
+ cv2.imwrite(str(file_path), img_np)
+
+ assert file_path.is_file()
+
+ 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, tmp_path: Path, ext) -> None:
+ height, width = 4, 5
+ img_np: np.ndarray = create_random_img8(height, width, 3)
+
+ file_path = tmp_path / f"image.{ext}"
+ cv2.imwrite(str(file_path), img_np)
+
+ assert file_path.is_file()
+
+ img = load_image(file_path, ImageLoadType.GRAY8)
+ assert img.shape[0] == 1
+ assert img.dtype == torch.uint8
+
+ img = load_image(file_path, ImageLoadType.GRAY32)
+ assert img.shape[0] == 1
+ assert img.dtype == torch.float32
+
+ img = load_image(file_path, ImageLoadType.RGB8)
+ assert img.shape[0] == 3
+ assert img.dtype == torch.uint8
+
+ img = load_image(file_path, ImageLoadType.RGB32)
+ assert img.shape[0] == 3
+ assert img.dtype == torch.float32
+
+ img = load_image(file_path, ImageLoadType.RGBA8)
+ assert img.shape[0] == 4
+ assert img.dtype == torch.uint8
+
+ @pytest.mark.parametrize("ext", ["png", "jpg"])
+ def test_types_gray(self, tmp_path: Path, ext) -> None:
+ height, width = 4, 5
+ img_np: np.ndarray = create_random_img8(height, width, 1)
+
+ file_path = tmp_path / f"image.{ext}"
+ cv2.imwrite(str(file_path), img_np)
+
+ assert file_path.is_file()
+
+ img = load_image(file_path, ImageLoadType.GRAY8)
+ assert img.shape[0] == 1
+ assert img.dtype == torch.uint8
+
+ img = load_image(file_path, ImageLoadType.GRAY32)
+ assert img.shape[0] == 1
+ assert img.dtype == torch.float32
+
+ img = load_image(file_path, ImageLoadType.RGB8)
+ assert img.shape[0] == 3
+ assert img.dtype == torch.uint8
+
+ img = load_image(file_path, ImageLoadType.RGB32)
+ assert img.shape[0] == 3
+ assert img.dtype == torch.float32
+
+ img = load_image(file_path, ImageLoadType.RGBA8)
+ assert img.shape[0] == 4
+ assert img.dtype == torch.uint8
diff --git a/test/io/test_load_image.py b/test/io/test_load_image.py
deleted file mode 100644
index b2170bcdf..000000000
--- a/test/io/test_load_image.py
+++ /dev/null
@@ -1,112 +0,0 @@
-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_ge
-
-try:
- import kornia_rs
-except ImportError:
- kornia_rs = None
-
-
-def available_package() -> bool:
- return sys.version_info >= (3, 7, 0) and torch_version_ge(1, 10, 0) 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) # noqa: NPY002
-
-
[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
- assert img.dtype == torch.uint8
-
- img = load_image(file_path, ImageLoadType.GRAY32)
- assert img.shape[0] == 1
- assert img.dtype == torch.float32
-
- img = load_image(file_path, ImageLoadType.RGB8)
- assert img.shape[0] == 3
- assert img.dtype == torch.uint8
-
- img = load_image(file_path, ImageLoadType.RGB32)
- assert img.shape[0] == 3
- assert img.dtype == torch.float32
-
- img = load_image(file_path, ImageLoadType.RGBA8)
- assert img.shape[0] == 4
- assert 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
- assert img.dtype == torch.uint8
-
- img = load_image(file_path, ImageLoadType.GRAY32)
- assert img.shape[0] == 1
- assert img.dtype == torch.float32
-
- img = load_image(file_path, ImageLoadType.RGB8)
- assert img.shape[0] == 3
- assert img.dtype == torch.uint8
-
- img = load_image(file_path, ImageLoadType.RGB32)
- assert img.shape[0] == 3
- assert img.dtype == torch.float32
-
- img = load_image(file_path, ImageLoadType.RGBA8)
- assert img.shape[0] == 4
- assert img.dtype == torch.uint8
diff --git a/test/utils/test_image.py b/test/utils/test_image_utils.py
similarity index 100%
rename from test/utils/test_image.py
rename to test/utils/test_image_utils.py