Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

docs(io,image): convention blocks and pins for kornia.io and kornia.image (#5823)

Dmytro Mishkine4f13be40687
diff --git a/changelog.d/5823.added.md b/changelog.d/5823.added.md
new file mode 100644
index 000000000..12c7c8365
--- /dev/null
+++ b/changelog.d/5823.added.md
@@ -0,0 +1,9 @@
+The `kornia.io` and `kornia.image` API documentation states their conventions: the channels, dtype and range of each
+`load_image` type, the dtypes and channel counts each `write_image` format stores, when the NumPy converters share
+memory, the pixel frame, rounding and clipping of the drawing functions, the value ranges of the terminal
+printers, and the supported dtypes for `Image.to_gray()`. The conventions page gains a *Files and arrays* section,
+with the load types and a table mapping OpenCV's, Pillow's and torchvision's readers, writers and converters onto
+kornia's, and a *Drawing* section. Two known defects
+are documented: `write_image` raises a bare `Exception` and leaves an empty or truncated file for an image with zero
+height or width (#5770), and `load_image` raises a `ValueError` that does not name the file for an 8-bit palette PNG
+with an empty `tRNS` chunk, under every type except `UNCHANGED` (#5851).
diff --git a/docs/source/get-started/conventions.rst b/docs/source/get-started/conventions.rst
index 47ced7b29..b20c325bf 100644
--- a/docs/source/get-started/conventions.rst
+++ b/docs/source/get-started/conventions.rst
@@ -30,6 +30,105 @@ Image tensors
np_img = (np.random.rand(48, 64, 3) * 255).astype(np.uint8) # (H, W, C) uint8
t = kornia.image.image_to_tensor(np_img)[None].float() / 255.0 # (1, 3, 48, 64) in [0, 1]
+.. _image-io-conventions:
+
+Files and arrays
+^^^^^^^^^^^^^^^^
+
+:func:`kornia.io.load_image` returns a ``(C, H, W)`` tensor in RGB order, with alpha last. The load type fixes its
+channels, dtype and range, whatever the file holds:
+
+.. list-table::
+ :header-rows: 1
+
+ * - ``ImageLoadType``
+ - channels
+ - dtype and range
+ * - ``GRAY8``, ``RGB8``, ``RGBA8``
+ - 1, 3, 4
+ - ``uint8`` in ``[0, 255]``
+ * - ``GRAY32``, ``RGB32`` (the default)
+ - 1, 3
+ - ``float32`` in ``[0, 1]``
+ * - ``UNCHANGED``
+ - the file's
+ - the file's: ``uint8``, ``uint16`` or ``float32``
+
+- Every type except ``UNCHANGED`` loads an 8-bit palette PNG as its colours and raises for a file of more than 8 bits;
+ ``RGBA8`` keeps the alpha, and the other types composite it over white. ``UNCHANGED`` returns a palette PNG's indices,
+ keeps an alpha channel as stored and ignores a ``tRNS`` chunk.
+- The EXIF orientation is ignored: the pixels come back as stored.
+- :func:`kornia.io.write_image` writes the tensor as it is, channels first, RGB with alpha last, without scaling: JPEG
+ takes ``uint8``, PNG ``uint8`` and ``uint16``, and TIFF ``uint8``, ``uint16`` and ``float32``, each with 1 or 3
+ channels, and PNG also with 4.
+- :func:`kornia.image.image_to_tensor` and :func:`kornia.image.tensor_to_image` do not rescale the values and, by
+ default, share memory with a CPU array instead of copying it; their Convention blocks list the exceptions.
+ :func:`kornia.image.image_list_to_tensor` copies.
+
+The same tasks in OpenCV, Pillow and torchvision:
+
+.. list-table::
+ :header-rows: 1
+ :widths: 30 30 40
+
+ * - Their call
+ - kornia
+ - Difference
+ * - ``cv2.imread(p)``
+ - ``load_image(p, ImageLoadType.RGB8)``
+ - OpenCV returns ``(H, W, 3)`` BGR, turns the image by its EXIF orientation and drops alpha; kornia returns
+ ``(3, H, W)`` RGB as stored, with alpha composited over white.
+ * - ``cv2.imread(p, cv2.IMREAD_GRAYSCALE)``
+ - ``load_image(p, ImageLoadType.GRAY8)``
+ - kornia converts the decoded RGB image as ``cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)`` does; ``IMREAD_GRAYSCALE``
+ converts while decoding and can differ. OpenCV's default and ``IMREAD_GRAYSCALE`` reduce a 16-bit file to 8
+ bits, where kornia raises: load it with ``UNCHANGED`` and scale it yourself.
+ * - ``cv2.imread(p, cv2.IMREAD_UNCHANGED)``
+ - ``load_image(p, ImageLoadType.UNCHANGED)``
+ - Both keep 16-bit data and alpha, OpenCV in BGR(A) order. OpenCV expands a palette PNG into colours; kornia
+ returns its indices.
+ * - ``cv2.imwrite(p, img)``
+ - ``write_image(p, image_to_tensor(cv2.cvtColor(img, cv2.COLOR_BGR2RGB)))``
+ - OpenCV takes ``(H, W, C)`` BGR or BGRA, or ``(H, W)`` gray. Convert BGRA with ``cv2.COLOR_BGRA2RGBA`` and
+ pass gray as it is. Its JPEG quality defaults to 95, kornia's to 80.
+ * - Pillow ``Image.open(p).convert("RGB")`` or ``.convert("L")``
+ - ``load_image(p, ImageLoadType.RGB8)`` or ``ImageLoadType.GRAY8``
+ - Pillow drops alpha instead of compositing it, and its gray can differ from kornia's by one level. Neither turns
+ the image by its EXIF orientation; ``ImageOps.exif_transpose`` does.
+ * - Pillow ``Image.open(p)`` of a palette (``"P"``) PNG
+ - ``load_image(p, ImageLoadType.UNCHANGED)``
+ - Both give the palette indices of an 8-bit palette PNG; kornia raises for 1, 2 or 4 bits per pixel.
+ * - Pillow ``Image.save(p)`` as JPEG
+ - ``write_image(p, img)``
+ - Pillow's JPEG quality defaults to 75, kornia's to 80.
+ * - torchvision ``ToTensor()(img)``
+ - ``image_to_tensor(img).float() / 255`` for a ``uint8`` ``img``
+ - ``ToTensor`` copies a ``uint8`` array into ``float32`` in ``[0, 1]`` and keeps the values of any other array;
+ ``image_to_tensor`` keeps the dtype and shares the memory.
+ * - torchvision ``make_grid(t, nrow=n)``
+ - ``make_grid(t, n_row=n)``
+ - ``n`` images per row in both. torchvision defaults to 8 per row, pads the outer border too, turns one channel
+ into three and uses at most ``B`` columns; kornia defaults to :math:`\lceil \sqrt{B} \rceil` per row, pads
+ between the images only, keeps the channels and always uses ``n_row`` columns.
+
+.. _drawing-conventions:
+
+Drawing
+^^^^^^^
+
+The :doc:`drawing functions </image.drawing>` take points as ``(x, y)`` in the pixel frame of `Coordinates and
+sizes`_, draw into the image they are given and return it, and cast the colour to the image's dtype without
+rescaling it, so a ``[0, 1]`` colour on a ``uint8`` image draws black or almost black. Clone the image first to keep
+the original; a leaf tensor that requires grad cannot be drawn on.
+
+- :func:`~kornia.image.draw_point2d`, :func:`~kornia.image.draw_line` and :func:`~kornia.image.draw_rectangle` put a
+ fractional coordinate on the pixel whose centre is nearest, halfway rounding up, as OpenCV's fixed-point ``shift``
+ argument does; Pillow and torchvision truncate, so their shapes can sit one pixel up or to the left of kornia's.
+ :func:`~kornia.image.draw_convex_polygon` does not round its vertices.
+- A point or a line endpoint outside the image raises ``ValueError``, where OpenCV and Pillow clip the line;
+ rectangles and polygons are clipped to the image.
+- A single-value colour is written to every channel, where OpenCV's and Pillow's scalar colours fill only the first.
+
.. _coordinate-conventions:
Coordinates and sizes
diff --git a/docs/source/io.rst b/docs/source/io.rst
index ce1f4734b..456ff1507 100644
--- a/docs/source/io.rst
+++ b/docs/source/io.rst
@@ -2,7 +2,7 @@ kornia.io
=========
.. meta::
- :description: The kornia.io package loads and saves images directly as PyTorch tensors. It is backed by kornia-rs, a low-level Rust computer vision library, and uses the DLPack protocol to decode images with a minimal memory footprint on Linux, macOS and Windows.
+ :description: The kornia.io package loads and saves images directly as PyTorch tensors. It is backed by kornia-rs, a low-level Rust computer vision library with wheels for Linux, macOS and Windows.
.. currentmodule:: kornia.io
@@ -10,8 +10,8 @@ Package to load and save image data directly as tensors.
The package is backed by `kornia-rs <https://github.com/kornia/kornia-rs>`_, a low-level computer vision
library written in `Rust <https://www.rust-lang.org/>`_ that is installed automatically as a dependency of
-Kornia (wheels are available for Linux, macOS and Windows). Decoded images are handed to PyTorch through the
-`DLPack <https://github.com/dmlc/dlpack>`_ protocol, which avoids extra copies and keeps the memory footprint low.
+Kornia (wheels are available for Linux, macOS and Windows). kornia-rs decodes into a NumPy array that the tensor
+can reuse: ``RGB8`` of an RGB PNG or JPEG loaded on the CPU, for example, is a view of that array, not a copy.
.. code-block:: python
@@ -36,12 +36,15 @@ Kornia (wheels are available for Linux, macOS and Windows). Decoded images are h
img = K.io.load_image(file_path, ImageLoadType.RGB32, device="cuda")
# (3, H, W) torch.float32 in [0, 1], on "cuda"
- K.io.write_image("copy.jpg", (img * 255).to(torch.uint8).cpu()) # expects (3, H, W) uint8
+ K.io.write_image("copy.jpg", (img * 255).round().to(torch.uint8).cpu()) # JPEG takes uint8 (C, H, W)
.. tip::
Most Kornia operators expect a batched ``(B, C, H, W)`` float tensor in ``[0, 1]``; load with
``ImageLoadType.RGB32`` and add the batch dimension with ``img[None]``.
+:ref:`Files and arrays <image-io-conventions>` tabulates the load types and the formats :func:`write_image` takes,
+and maps OpenCV's and Pillow's readers and writers onto them.
+
.. autofunction:: load_image
.. autofunction:: write_image
.. autofunction:: get_sample_images
diff --git a/kornia/image/base.py b/kornia/image/base.py
index 413abfa50..2a7d6e1ba 100644
--- a/kornia/image/base.py
+++ b/kornia/image/base.py
@@ -27,7 +27,11 @@ from kornia.core.check import KORNIA_CHECK_SHAPE
@dataclass(frozen=True)
class ImageSize:
- r"""Data class to represent image shape.
+ r"""Data class to represent the size of an image, without its channels.
+
+ Convention:
+ See the Convention block of :class:`~kornia.image.Image`. The positional order is ``(height, width)``,
+ kornia's order for sizes and the reverse of :math:`(x, y)` points.
Args:
height: image height.
@@ -47,7 +51,12 @@ class ImageSize:
class ColorSpace(Enum):
- r"""Enum that represents the color space of an image."""
+ r"""Enum that represents the color space of an image.
+
+ Convention:
+ See the Convention block of :class:`~kornia.image.Image`, which checks the color space against the channel
+ count. There is no color space with alpha: a 4-channel image is ``UNKNOWN``.
+ """
UNKNOWN = 0 # for now, in case of multi band images
GRAY = 1
@@ -59,9 +68,14 @@ class ColorSpace(Enum):
class PixelFormat:
r"""Data class to represent the pixel format of an image.
+ Convention:
+ See the Convention block of :class:`~kornia.image.Image`, which checks a pixel format against the data; the
+ data class itself checks nothing.
+
Args:
color_space: color space.
- bit_depth: the number of bits per channel.
+ bit_depth: the storage size of one channel value in bits, ``8 * element_size()`` of the data: 8 for
+ ``uint8``, 32 for ``float32``.
Example:
>>> pixel_format = PixelFormat(ColorSpace.RGB, 8)
@@ -77,7 +91,12 @@ class PixelFormat:
class ChannelsOrder(Enum):
- r"""Enum that represents the channels order of an image."""
+ r"""Enum that represents the channels order of an image.
+
+ Convention:
+ See the Convention block of :class:`~kornia.image.Image`. ``CHANNELS_FIRST`` stores :math:`(C, H, W)` and
+ ``CHANNELS_LAST`` stores :math:`(H, W, C)`.
+ """
CHANNELS_FIRST = 0
CHANNELS_LAST = 1
@@ -87,6 +106,10 @@ class ChannelsOrder(Enum):
class ImageLayout:
"""Data class to represent the layout of an image.
+ Convention:
+ See the Convention block of :class:`~kornia.image.Image`, which checks a layout against the data; the data
+ class itself checks nothing.
+
Args:
image_size: image size.
channels: number of channels.
diff --git a/kornia/image/draw.py b/kornia/image/draw.py
index cf181b338..cfe871cc7 100644
--- a/kornia/image/draw.py
+++ b/kornia/image/draw.py
@@ -74,12 +74,16 @@ def _rectangle_bands(
def draw_point2d(image: Tensor, points: Tensor, color: Tensor) -> Tensor:
r"""Set one or more coordinates in a Tensor to a color.
+ Convention:
+ See the Convention block of :func:`~kornia.image.draw_line` for the coordinates, the rounding, the colour
+ and the in-place drawing. The image is :math:`(C, H, W)` or :math:`(H, W)`.
+
Args:
- image: the input image on which to draw the points with shape :math`(C,H,W)` or :math`(H,W)`.
- points: the [x, y] points to be drawn on the image with shape :math`(N, 2)`, a single
- point with shape :math`(2,)`, or an empty tensor with shape :math`(0, 2)`.
- color: the color of the pixel with :math`(C)` where :math`C` is the number of channels of the image.
- A single value, with shape :math`(1)` or 0-d, is written to every channel.
+ image: the input image on which to draw the points with shape :math:`(C,H,W)` or :math:`(H,W)`.
+ points: the [x, y] points to be drawn on the image with shape :math:`(N, 2)`, a single
+ point with shape :math:`(2,)`, or an empty tensor with shape :math:`(0, 2)`.
+ color: the color of the pixel with :math:`(C)` where :math:`C` is the number of channels of the image,
+ or a single value with shape :math:`(1)` or 0-d.
Return:
The image with points set to the color. This operation modifies image inplace but also
@@ -89,9 +93,6 @@ def draw_point2d(image: Tensor, points: Tensor, color: Tensor) -> Tensor:
ValueError: if the image is not ``(C, H, W)`` or ``(H, W)``, or a point lies outside the image after rounding.
BaseError: if ``color`` has neither 1 nor ``C`` values, or ``points`` is not ``(2,)`` or ``(N, 2)``.
- Fractional coordinates go to the pixel whose centre is nearest; a coordinate exactly halfway rounds up.
- A point outside the image raises `ValueError`.
-
"""
if image.dim() not in (2, 3):
raise ValueError("image must have shape (C, H, W) or (H, W).")
@@ -134,10 +135,10 @@ def _draw_pixel(image: torch.Tensor, x: int, y: int, color: torch.Tensor) -> Non
r"""Draw a pixel into an image.
Args:
- image: the input image to where to draw the lines with shape :math`(C,H,W)`.
+ image: the input image to where to draw the lines with shape :math:`(C,H,W)`.
x: the x coordinate of the pixel.
y: the y coordinate of the pixel.
- color: the color of the pixel with :math`(C)` where :math`C` is the number of channels of the image.
+ color: the color of the pixel with :math:`(C)` where :math:`C` is the number of channels of the image.
Return:
Nothing is returned.
@@ -147,25 +148,31 @@ def _draw_pixel(image: torch.Tensor, x: int, y: int, color: torch.Tensor) -> Non
def draw_line(image: torch.Tensor, p1: torch.Tensor, p2: torch.Tensor, color: torch.Tensor) -> torch.Tensor:
- r"""Draw a single line into an image.
-
- Each line is rasterized one pixel per step along its major axis, the one with the larger extent:
- at step ``t = 0 .. major`` the pixel is the one whose centre is nearest to the ideal segment, a tie
- rounding up in absolute coordinates, computed in integers. The line is therefore the same for ``p1 -> p2`` and
- ``p2 -> p1``, and both ``p1`` and ``p2`` are always drawn. Fractional endpoints go to the pixel whose centre is
- nearest; a coordinate exactly halfway rounds up.
+ r"""Draw a line, or one line per row of ``(B, 2)`` endpoints, into an image.
+
+ Convention:
+ - Points are :math:`(x, y)`, x the column and y the row, with pixel centres at integer coordinates, as in
+ :ref:`Coordinates and sizes <coordinate-conventions>`. A fractional endpoint goes to the pixel whose centre
+ is nearest, a coordinate exactly halfway rounding up.
+ - A line has one pixel per step along its longer axis: the pixel whose centre is nearest to the segment
+ between the two endpoint pixels, a tie going to the larger coordinate. The line is therefore the same from
+ ``p1`` to ``p2`` as from ``p2`` to ``p1``, and both endpoints are drawn.
+ - The image is one :math:`(C, H, W)` tensor, and ``(B, 2)`` endpoints draw ``B`` lines into it. An endpoint
+ outside the image raises ``ValueError``; nothing is clipped.
+ - The colour is cast to the image's dtype without rescaling or a range check, and a single value is written
+ to every channel.
+ - The image is drawn in place and returned.
+ - :ref:`Drawing <drawing-conventions>` compares these rules with OpenCV, Pillow and torchvision.
Args:
- image: the input image to where to draw the lines with shape :math`(C,H,W)`.
+ image: the input image to where to draw the lines with shape :math:`(C,H,W)`.
p1: the start point [x y] of the line with shape (2, ) or (B, 2).
p2: the end point [x y] of the line, with the same shape as ``p1``.
- color: the color of the line with shape :math`(C)` where :math`C` is the number of channels
- of the image. A single value, with shape :math`(1)` or 0-d, is written to every channel.
- Porting note: OpenCV's and Pillow's scalar colours fill only the first channel.
+ color: the color of the line with shape :math:`(C)` where :math:`C` is the number of channels
+ of the image, or a single value with shape :math:`(1)` or 0-d.
Return:
- The image containing the line. This operation modifies image inplace but also returns
- the drawn tensor for convenience.
+ The image containing the line.
Raises:
ValueError: if ``p1`` and ``p2`` differ in shape, or their last dimension is not 2.
@@ -254,18 +261,21 @@ def draw_rectangle(
) -> torch.Tensor:
r"""Draw N rectangles on a batch of image tensors.
+ Convention:
+ - A rectangle is ``[x1, y1, x2, y2]``, its two corners in either order and both included, with the
+ coordinates rounded as in :func:`~kornia.image.draw_line`. A side that lies outside the image is not drawn
+ and a fill is clipped to the image; neither raises.
+ - The corners are rounded and the vertices of :func:`~kornia.image.draw_convex_polygon` are not, so a filled
+ rectangle and the same polygon always agree for integer corners; for fractional ones each side can be one
+ row or column apart, so a polygon thinner than a pixel can fill nothing.
+ - The colour and the in-place drawing follow :func:`~kornia.image.draw_line`.
+
Args:
- image: is tensor of BxCxHxW.
- rectangle: represents number of rectangles to draw in BxNx4
- N is the number of boxes to draw per batch index[x1, y1, x2, y2]
- 4 is in (top_left.x, top_left.y, bot_right.x, bot_right.y).
- color: a 0-d, size 1, size 3, BxNx1, or BxNx3 tensor.
- If C is 3, and color is 1 channel it will be broadcasted.
- fill: is a flag used to fill the boxes with color if True.
-
- Corners may come in either order. Coordinates are rounded to the nearest pixel centre (a coordinate exactly
- halfway rounds up), and the rectangle includes both corners. A side outside the image is not drawn and a fill is
- clipped to the image.
+ image: the images, :math:`(B, C, H, W)`.
+ rectangle: the rectangles, :math:`(B, N, 4)`: ``N`` per image, each ``[x1, y1, x2, y2]``.
+ color: the colour, :math:`(C)` or :math:`(B, N, C)`, or a single value (0-d, :math:`(1)` or
+ :math:`(B, N, 1)`). Black by default.
+ fill: whether to fill the rectangles instead of drawing their outlines.
Raises:
ShapeError: if the image is not ``(B, C, H, W)``. It is also a ``ValueError``.
@@ -273,11 +283,11 @@ def draw_rectangle(
Returns:
This operation modifies image inplace but also returns the drawn tensor for
- convenience with same shape the of the input BxCxHxW.
+ convenience, with the shape of the input :math:`(B, C, H, W)`.
Example:
>>> img = torch.rand(2, 3, 10, 12)
- >>> rect = torch.tensor([[[0, 0, 4, 4]], [[4, 4, 10, 10]]])
+ >>> rect = torch.tensor([[[0, 0, 4, 4]], [[4, 4, 11, 9]]])
>>> out = draw_rectangle(img, rect)
"""
@@ -406,16 +416,26 @@ def _batch_polygons(polygons: List[Tensor]) -> Tensor:
def draw_convex_polygon(images: Tensor, polygons: Union[Tensor, List[Tensor]], colors: Tensor) -> Tensor:
r"""Draws convex polygons on a batch of image tensors.
+ Convention:
+ - Vertices are :math:`(x, y)` in the pixel frame of :func:`~kornia.image.draw_line`, used as given, without
+ rounding. A pixel is filled when its centre lies inside the polygon or on its boundary, as
+ ``skimage.draw.polygon`` fills; ``cv2.fillConvexPoly`` fills more. The part outside the image is clipped.
+ - The polygon is taken to be convex: each row is filled from its leftmost to its rightmost edge crossing, so
+ in a concave polygon a gap between two edges within a row is filled too.
+ - The polygons and the colours must already be on the images' device; the other draw functions move theirs.
+ - The colour and the in-place drawing follow :func:`~kornia.image.draw_line`.
+
Args:
images: is tensor of BxCxHxW.
polygons: represents polygons as points, either BxNx2 or List of variable length polygons.
N is the number of points.
2 is (x, y).
- colors: a ``B x C`` tensor, a ``C`` tensor, or a 0-d scalar with the fill colour.
+ colors: the fill colours, :math:`(B, C)` or :math:`(C)`, or a single value (0-d, :math:`(1)` or
+ :math:`(B, 1)`).
Returns:
This operation modifies image inplace but also returns the drawn tensor for
- convenience with same shape the of the input BxCxHxW.
+ convenience, with the shape of the input :math:`(B, C, H, W)`.
Raises:
ShapeError: if the images are not ``(B, C, H, W)``. It is also a ``ValueError``.
@@ -423,10 +443,6 @@ def draw_convex_polygon(images: Tensor, polygons: Union[Tensor, List[Tensor]], c
BaseError: if the vertices are not ``(x, y)`` points.
BaseError: if the images, polygons and colors differ in batch size or device.
- Note:
- This function assumes a coordinate system (0, h - 1), (0, w - 1) in the image, with (0, 0) being the center
- of the top-left pixel and (w - 1, h - 1) being the center of the bottom-right coordinate.
-
Example:
>>> img = torch.rand(1, 3, 12, 16)
>>> poly = torch.tensor([[[4, 4], [12, 4], [12, 8], [4, 8]]])
diff --git a/kornia/image/image.py b/kornia/image/image.py
index d01ce5272..45445e3fb 100644
--- a/kornia/image/image.py
+++ b/kornia/image/image.py
@@ -54,21 +54,28 @@ def _default_color_space(channels: int) -> ColorSpace:
class Image:
r"""Class that holds an Image torch.Tensor representation.
- .. note::
-
- Disclaimer: This class provides the minimum functionality for image manipulation. However, as soon
- as you start to experiment with advanced torch.Tensor manipulation, you might expect fancy
- polymorphic behaviours.
-
.. warning::
This API is experimental and might suffer changes in the future.
+ Convention:
+ - An ``Image`` holds one image, :math:`(C, H, W)` or :math:`(H, W, C)` as ``layout.channels_order`` says,
+ never a batch: a 4-D tensor raises ``ShapeError``. The layout and the pixel format are checked against the
+ data: ``bit_depth`` is the storage size, ``8 * data.element_size()``, and the color space must fit the
+ channel count, 1 for ``GRAY``, 3 for ``RGB`` and ``BGR``, any for ``UNKNOWN``.
+ - :meth:`from_numpy`, :meth:`to_numpy`, :meth:`from_dlpack` and :meth:`to_dlpack` share memory with the
+ array or capsule of a CPU image. :meth:`to_numpy` returns the stored layout, so an image from
+ :meth:`from_file` gives :math:`(C, H, W)`.
+ - :meth:`to_gray`, :meth:`to_rgb` and :meth:`to_bgr` return the image itself when it is already in that color
+ space, an image with new data when it is in another of the three, and raise ``ValueError`` for
+ ``UNKNOWN``. Converting RGB or BGR to gray requires ``uint8`` or a floating dtype supported by
+ :func:`~kornia.color.rgb_to_grayscale`; other integer dtypes, such as ``uint16``, are unsupported even
+ though ``Image`` can hold them. An already-gray image is returned unchanged regardless of dtype.
+ :meth:`to`, :meth:`float` and :meth:`clone` return a new ``Image`` and leave this one unchanged.
+
Args:
- data: a torch torch.Tensor containing the image data.
- pixel_format: the pixel format. ``bit_depth`` is the storage size, ``8 * data.element_size()``, and the color
- space must match the channel count: ``GRAY`` has 1 channel, ``RGB`` and ``BGR`` have 3, ``UNKNOWN``
- accepts any count.
+ data: a torch.Tensor containing the image data.
+ pixel_format: the pixel format of the image.
layout: a dataclass containing the image layout information.
Examples:
@@ -101,7 +108,7 @@ class Image:
Like the other kornia checks, the pixel-format checks are skipped after ``kornia.core.check.disable_checks()``.
Args:
- data: a torch torch.Tensor containing the image data.
+ data: a torch.Tensor containing the image data.
pixel_format: the pixel format of the image.
layout: a dataclass containing the image layout information.
@@ -318,7 +325,7 @@ class Image:
color_space: Optional[ColorSpace] = None,
channels_order: ChannelsOrder = ChannelsOrder.CHANNELS_LAST,
) -> Image:
- """Construct an image torch.Tensor from a numpy array.
+ """Construct an ``Image`` from a numpy array, sharing its memory.
Args:
data: a numpy array containing the image data.
@@ -365,12 +372,12 @@ class Image:
return cls(torch.from_numpy(data), pixel_format, layout)
def to_numpy(self) -> np_ndarray:
- """Return a numpy array in cpu from the image torch.Tensor."""
+ """Return the image data as a numpy array on the CPU, in the stored layout."""
return self.data.cpu().detach().numpy()
@classmethod
def from_dlpack(cls, data: DLPack) -> Image:
- """Construct an image torch.Tensor from a DLPack capsule.
+ """Construct an ``Image`` from a DLPack capsule, sharing its memory.
Args:
data: a DLPack capsule from numpy, tvm or jax. The capsule must hold a ``(C, H, W)`` image; it is
@@ -406,7 +413,10 @@ class Image:
@classmethod
def from_file(cls, file_path: str | Path) -> Image:
- """Construct an image torch.Tensor from a file.
+ """Construct an ``Image`` from a file.
+
+ The file is loaded with :func:`~kornia.io.load_image` as ``ImageLoadType.RGB8``: the image is
+ :math:`(3, H, W)` ``uint8``, ``RGB`` and ``CHANNELS_FIRST``, on the CPU.
Args:
file_path: the path to the file to read the image from.
@@ -450,7 +460,8 @@ class Image:
"""Print the image torch.Tensor to the console.
Args:
- max_width: the maximum width of the image to print.
+ max_width: the widest image, in pixels, that is printed without resizing; see
+ :func:`~kornia.image.image_to_string`.
A ``BGR`` image is converted to RGB first, so the terminal shows the true colours.
diff --git a/kornia/image/image_print.py b/kornia/image/image_print.py
index 85a69c29b..5aea67099 100644
--- a/kornia/image/image_print.py
+++ b/kornia/image/image_print.py
@@ -375,13 +375,25 @@ def rgb2short(rgb: str) -> Tuple[str, str]:
def image_to_string(image: torch.Tensor, max_width: int = 256) -> str:
"""Obtain the closest xterm-256 approximation string from an image torch.Tensor.
- The torch.Tensor shall be either 0~1 float type or 0~255 long type. Each pixel is shown with the nearest of the
- 240 fixed xterm-256 colours (codes 16-255, the 6x6x6 cube and the gray ramp) by RGB distance, measured from its
- unrounded 0-255 value; codes 0-15 are defined by the terminal and are not used.
+ Each pixel is shown with the nearest of the 240 fixed xterm-256 colours (codes 16-255, the 6x6x6 cube and the gray
+ ramp) by RGB distance, measured from its unrounded 0-255 value; codes 0-15 are defined by the terminal and are not
+ used.
+
+ Convention:
+ - The image is :math:`(C, H, W)` with 1 or 3 channels. A float image is read in [0, 1] and an integer one in
+ [0, 255], so integer 255 and float 1.0 print alike; a value outside the range raises.
+ - Each pixel prints as two spaces on its background colour, one text line per image row. An image wider than
+ ``max_width`` pixels is first resized to ``max_width`` pixels wide, keeping its aspect ratio, so a line is at
+ most ``2 * max_width`` terminal columns wide.
Args:
image: an RGB image with shape :math:`3HW` or a grayscale image with shape :math:`1HW`.
- max_width: maximum width of the input image.
+ max_width: the widest image, in pixels, that is printed without resizing.
+
+ Raises:
+ ImageError: if the tensor is not an image with 1 or 3 channels, such as ``(H, W)`` (also a ``ValueError``).
+ ShapeError: if a tensor with 1 or 3 channels is not ``(C, H, W)``, such as a batch (also a ``ValueError``).
+ ValueCheckError: if a float tensor has values outside [0, 1], or an integer one outside [0, 255].
"""
KORNIA_CHECK_IS_IMAGE(image, None, raises=True)
KORNIA_CHECK_SHAPE(image, ["C", "H", "W"])
@@ -424,20 +436,22 @@ def print_image(image: Union[str, os.PathLike, torch.Tensor], max_width: int = 9
.. image:: https://github.com/kornia/data/blob/main/print_image.png?raw=true
+ Convention:
+ See the Convention block of :func:`~kornia.image.image_to_string`, which renders the image; ``max_width``
+ defaults to 96 here and to 256 there. A path is loaded with :func:`~kornia.io.load_image` as
+ ``ImageLoadType.RGB8``.
+
Args:
image: path (``str`` or ``os.PathLike``) to a valid image file, or a torch.Tensor.
- max_width: maximum width to print to terminal.
+ max_width: the widest image, in pixels, that is printed without resizing.
Raises:
TypeError: if ``image`` is neither a path nor a tensor.
- ShapeError: if the tensor is not ``(C, H, W)``. It is also a ``ValueError``.
- ImageError: if the tensor has neither 1 nor 3 channels. It is also a ``ValueError``.
+ ImageError: if the tensor is not an image with 1 or 3 channels, such as ``(H, W)`` (also a ``ValueError``).
+ ShapeError: if a tensor with 1 or 3 channels is not ``(C, H, W)``, such as a batch (also a ``ValueError``).
ValueCheckError: if a float tensor has values outside [0, 1], or an integer one outside [0, 255].
FileNotFoundError: if the path does not exist. Other errors of :func:`kornia.io.load_image` pass through.
- Note:
- Need to use `print_image(...)`.
-
"""
if isinstance(image, (str, os.PathLike)):
from kornia.io import ImageLoadType # pylint: disable=C0415
diff --git a/kornia/image/utils.py b/kornia/image/utils.py
index 1b6118fbd..e9a3312fc 100644
--- a/kornia/image/utils.py
+++ b/kornia/image/utils.py
@@ -28,6 +28,16 @@ from torch.nn import functional as F
def image_to_tensor(image: Any, keepdim: bool = True) -> torch.Tensor:
"""Convert a NumPy image to a PyTorch tensor image.
+ Convention:
+ - The last axis of a 3-D or 4-D array is always the channels: :math:`(H, W, C)` becomes :math:`(C, H, W)` and
+ :math:`(B, H, W, C)` becomes :math:`(B, C, H, W)`. A channels-first :math:`(C, H, W)` array is not detected:
+ it is read as :math:`(H, W, C)`.
+ - The dtype and the values are kept, so ``uint8`` stays in [0, 255], and the tensor is a view of the array
+ that shares its memory. An array with a negative stride, such as OpenCV's ``img[..., ::-1]``, raises
+ ``ValueError``; pass ``img[..., ::-1].copy()``.
+ - ``keepdim`` defaults to ``True`` here and to ``False`` in :class:`~kornia.image.ImageToTensor`.
+ - :ref:`Files and arrays <image-io-conventions>` relates it to torchvision's ``ToTensor``.
+
Args:
image: image of the form :math:`(H, W, C)`, :math:`(H, W)` or
:math:`(B, H, W, C)`.
@@ -84,9 +94,12 @@ def image_to_tensor(image: Any, keepdim: bool = True) -> torch.Tensor:
def image_list_to_tensor(images: List[Any]) -> torch.Tensor:
"""Convert a list of numpy images to a PyTorch 4d tensor image.
+ Convention:
+ See the Convention block of :func:`~kornia.image.image_to_tensor`. Unlike it, this function copies the images
+ into a new tensor and takes :math:`(H, W, C)` images only.
+
Args:
- images: list of images, each of the form :math:`(H, W, C)`.
- Image shapes must be consistent
+ images: list of images, each of the form :math:`(H, W, C)`, all of the same shape.
Returns:
tensor of the form :math:`(B, C, H, W)`.
@@ -175,18 +188,24 @@ def _to_bcdhw(tensor: torch.Tensor) -> torch.Tensor:
def tensor_to_image(tensor: torch.Tensor, keepdim: bool = False, force_contiguous: bool = False) -> Any:
"""Convert a PyTorch tensor image to a numpy image.
- In case the tensor is in the GPU, it will be copied back to CPU.
+ Convention:
+ - The channels move last, and a single channel is always dropped: :math:`(1, H, W)` gives :math:`(H, W)` and
+ :math:`(B, 1, H, W)` gives :math:`(B, H, W)`. ``keepdim`` keeps only the batch axis of a
+ :math:`(1, C, H, W)` input.
+ - The array shares memory with a CPU tensor whose dtype NumPy supports. A ``bfloat16`` tensor is returned as a
+ ``float32`` copy, a dtype NumPy cannot represent, such as ``float8_e4m3fn``, raises ``TypeError``, a tensor
+ on another device is copied, and ``force_contiguous=True`` copies a result that is not contiguous, such as
+ the channels-last view of a contiguous tensor with more than one channel.
+ - The dtype is kept, except ``bfloat16``, which NumPy lacks: it becomes ``float32``.
Args:
tensor: image of the form :math:`(H, W)`, :math:`(C, H, W)` or
:math:`(B, C, H, W)`.
- keepdim: If ``False`` squeeze the input image to match the shape
- :math:`(H, W, C)` or :math:`(H, W)`.
+ keepdim: If ``True``, keep the batch axis of a :math:`(1, C, H, W)` input.
force_contiguous: If ``True``, call ``contiguous`` on the result before converting it to NumPy.
Returns:
- image of the form :math:`(H, W)`, :math:`(H, W, C)` or :math:`(B, H, W, C)`. A ``bfloat16`` tensor is
- returned as ``float32``.
+ image of the form :math:`(H, W)`, :math:`(H, W, C)`, :math:`(B, H, W)` or :math:`(B, H, W, C)`.
Raises:
TypeError: if ``tensor`` is not a ``torch.Tensor``.
@@ -241,6 +260,10 @@ def tensor_to_image(tensor: torch.Tensor, keepdim: bool = False, force_contiguou
class ImageToTensor(nn.Module):
"""Convert a NumPy image to a PyTorch tensor image with :func:`image_to_tensor`.
+ Convention:
+ See the Convention block of :func:`~kornia.image.image_to_tensor`. Unlike it, ``keepdim`` defaults to
+ ``False``, so an :math:`(H, W, C)` array becomes :math:`(1, C, H, W)`.
+
Args:
keepdim: If ``False``, a 2-D or 3-D input gets a leading batch axis, :math:`(1, C, H, W)`. A 4-D input is
always :math:`(B, C, H, W)`.
@@ -252,24 +275,31 @@ class ImageToTensor(nn.Module):
self.keepdim = keepdim
def forward(self, x: Any) -> torch.Tensor:
- """Convert a NumPy-style image object into a PyTorch image tensor.
+ """Convert a NumPy image array into a PyTorch image tensor.
Args:
- x: Input image array accepted by :func:`image_to_tensor`. Common
- layouts are ``(H, W)``, ``(H, W, C)``, or ``(B, H, W, C)``,
+ x: Input image array accepted by :func:`image_to_tensor`, of
+ layout ``(H, W)``, ``(H, W, C)`` or ``(B, H, W, C)``,
where :math:`B` is batch size, :math:`H` is height,
:math:`W` is width, and :math:`C` is channel count.
Returns:
- Tensor returned by :func:`image_to_tensor`. When ``self.keepdim`` is
- ``False``, a batch dimension is added so image data follows
- PyTorch's channel-first convention.
+ Tensor returned by :func:`image_to_tensor` with ``keepdim=self.keepdim``.
"""
return image_to_tensor(x, keepdim=self.keepdim)
def make_grid(tensor: torch.Tensor, n_row: Optional[int] = None, padding: int = 2) -> torch.Tensor:
- """Convert a batched tensor to one image with padding in between.
+ r"""Convert a batched tensor to one image with padding in between.
+
+ Convention:
+ - ``n_row`` is the number of images in each row, that is the number of columns, as torchvision's ``nrow``;
+ it defaults to :math:`\lceil \sqrt{B} \rceil`. The images fill each row in batch order, zero images complete
+ the last row, and ``n_row > B`` still gives ``n_row`` columns.
+ - ``padding`` zeros go between the images only, with no outer border, and the channels are kept: ``R`` rows
+ of ``n_row`` images give :math:`(C, R (H + p) - p, n_{row} (W + p) - p)` for :math:`p` = ``padding``.
+ - The grid is a new tensor in the input's dtype and on its device; :math:`B = 0` gives a zero-height grid.
+ - :ref:`Files and arrays <image-io-conventions>` compares it with torchvision's ``make_grid``.
Args:
tensor: A batched tensor of shape (B, C, H, W).
@@ -327,10 +357,14 @@ def make_grid(tensor: torch.Tensor, n_row: Optional[int] = None, padding: int =
def perform_keep_shape_image(f: Callable[..., torch.Tensor]) -> Callable[..., torch.Tensor]:
- """Apply `f` to an image of arbitrary leading dimensions `(*, C, H, W)`.
-
- The input is reshaped to `(B, C, H, W)`, the function is applied, and the output is reshaped back to the original
- shape.
+ """Apply ``f`` to an image of arbitrary leading dimensions ``(*, C, H, W)``.
+
+ Convention:
+ - ``f`` always receives a ``(B, C, H, W)`` tensor: an ``(H, W)`` input becomes ``(1, 1, H, W)``, a
+ ``(C, H, W)`` input ``(1, C, H, W)``, and the leading dimensions of a longer input are flattened into ``B``.
+ The output gets the input's leading dimensions back around ``f``'s own ``C``, ``H`` and ``W``, except that an
+ ``(H, W)`` input gets ``f``'s first channel only; ``f`` must keep the batch size.
+ - An empty input raises ``ValueError`` before ``f`` is called.
"""
@wraps(f)
@@ -359,10 +393,12 @@ def perform_keep_shape_image(f: Callable[..., torch.Tensor]) -> Callable[..., to
def perform_keep_shape_video(f: Callable[..., torch.Tensor]) -> Callable[..., torch.Tensor]:
- """Apply `f` to an image of arbitrary leading dimensions `(*, C, D, H, W)`.
+ """Apply ``f`` to an image of arbitrary leading dimensions ``(*, C, D, H, W)``.
- The input is reshaped to `(B, C, D, H, W)`, the function is applied, and the output is reshaped back to the original
- shape.
+ Convention:
+ See the Convention block of :func:`~kornia.image.perform_keep_shape_image`, with ``f`` receiving
+ ``(B, C, D, H, W)``: a ``(D, H, W)`` input becomes ``(1, 1, D, H, W)`` and a ``(C, D, H, W)`` input
+ ``(1, C, D, H, W)``.
"""
@wraps(f)
diff --git a/kornia/io/io.py b/kornia/io/io.py
index a02d1f8d1..8b86a9ca2 100644
--- a/kornia/io/io.py
+++ b/kornia/io/io.py
@@ -43,7 +43,11 @@ def _color_mode(img_np: Any) -> str:
class ImageLoadType(Enum):
- r"""Enum to specify the desired image type."""
+ r"""Enum to specify the desired image type.
+
+ Convention:
+ See the Convention block of :func:`~kornia.io.load_image` for the channels, dtype and range of each member.
+ """
UNCHANGED = 0
GRAY8 = 1
@@ -316,6 +320,27 @@ def load_image(
) -> torch.Tensor:
"""Read an image file and decode using the Kornia Rust backend.
+ Convention:
+ - ``desired_type`` fixes the channels, the dtype and the range, whatever the file holds: ``GRAY8``, ``RGB8``
+ and ``RGBA8`` give 1, 3 and 4 ``uint8`` channels in [0, 255], and ``GRAY32`` and ``RGB32`` (the default)
+ 1 and 3 ``float32`` channels in [0, 1]. ``UNCHANGED`` keeps the file's channels and dtype, so a 16-bit PNG
+ or TIFF loads as ``uint16`` and a float TIFF as ``float32``; the other types raise for such a file.
+ - Channels are in RGB order, with alpha last. Under every type except ``UNCHANGED``, an 8-bit palette PNG
+ loads as its colours and a PNG ``tRNS`` chunk counts as alpha; ``RGBA8`` keeps the alpha (255 for an
+ opaque file), and the other types composite it over white, rounded to the nearest level. ``UNCHANGED``
+ returns a palette PNG's indices and keeps an alpha channel as stored.
+ - ``GRAY8`` and ``GRAY32`` convert a colour file with :func:`~kornia.color.rgb_to_grayscale`.
+ - The pixels come back as stored: the EXIF orientation is ignored.
+ - The extension, in any letter case, chooses the decoder; the file content does not. The file is decoded on
+ the CPU and the tensor is then moved to ``device``.
+ - kornia-rs cannot decode a PNG with 1, 2 or 4 bits per sample, a gray+alpha PNG, a 4-channel TIFF or a CMYK
+ JPEG; these, a truncated file and, under every type except ``UNCHANGED``, a malformed palette or
+ ``PLTE``/``tRNS`` chunk raise ``ValueError``.
+ - :ref:`Files and arrays <image-io-conventions>` maps OpenCV's and Pillow's loaders onto the load types.
+ - Known defect: under every type except ``UNCHANGED``, an 8-bit palette PNG with an empty ``tRNS`` chunk
+ raises the ``ValueError`` of ``torch.frombuffer``, whose message does not name the file, instead of loading
+ as its colours (`#5851 <https://github.com/kornia/kornia/issues/5851>`_).
+
Args:
path_file: Path to an image file in a format kornia-rs decodes, such as JPEG, PNG, TIFF or WebP; the
extension may be in any letter case.
@@ -323,21 +348,13 @@ def load_image(
device: the device where you want to get your image placed.
Return:
- Image torch.Tensor with shape :math:`(C, H, W)`: ``C`` is 1 for ``GRAY8`` and ``GRAY32``, 3 for ``RGB8`` and
- ``RGB32``, 4 for ``RGBA8``, and the file's channel count for ``UNCHANGED``. An 8-bit palette PNG loads as its
- palette indices under ``UNCHANGED`` and as its colours under every other type. An 8-bit gray or RGB PNG with
- a tRNS colour key loads its key colour as transparent under every other type.
+ Image torch.Tensor with shape :math:`(C, H, W)`.
Raises:
- TypeCheckError: if ``desired_type`` is not an :class:`ImageLoadType`. It is also a ``TypeError``.
+ TypeCheckError: if ``desired_type`` is not an :class:`ImageLoadType` (also a ``TypeError``).
OSError: if the file cannot be read, for example ``FileNotFoundError`` when it does not exist.
- ValueError: if the file cannot be decoded: a truncated or corrupt image, an unsupported format, a PNG with 1,
- 2 or 4 bits per sample (palette PNGs included), a gray+alpha PNG, a palette PNG whose palette is malformed
- or too short for its pixels, or, under every type except ``UNCHANGED``, a PNG whose PLTE or tRNS chunk is
- truncated or fails its CRC check. The message names the file; when the decoder fails, its exception is the
- ``__cause__``.
- NotImplementedError: if a type other than ``UNCHANGED`` is requested for a file that decodes to more than 8
- bits, such as a 16-bit PNG or TIFF or a float TIFF.
+ ValueError: if the file cannot be decoded; the message names the file.
+ NotImplementedError: if a type other than ``UNCHANGED`` is requested for a file wider than 8 bits.
"""
if not isinstance(desired_type, ImageLoadType):
@@ -394,29 +411,35 @@ def _write_float32_image(path_file: Path, img_np: Any) -> None:
def write_image(path_file: str | Path, image: torch.Tensor, quality: int = 80) -> None:
"""Save an image file using the Kornia Rust backend.
+ Convention:
+ - The extension chooses the format, and the format limits the dtype and the channels: JPEG stores ``uint8``,
+ PNG ``uint8`` and ``uint16``, and TIFF ``uint8``, ``uint16`` and ``float32``; each stores 1 or 3 channels,
+ and PNG also 4. Any other dtype or channel count raises.
+ - The tensor is written as it is, in RGB order with alpha last, without conversion, scaling or clamping: a
+ ``float32`` TIFF keeps values outside [0, 1].
+ - ``image`` is channels first. A channels-last :math:`(H, W, C)` tensor is not detected: its first axis is
+ read as the channels.
+ - :ref:`Files and arrays <image-io-conventions>` maps ``cv2.imwrite`` onto these arguments.
+ - Known defect: an image with zero height or width reaches kornia-rs, which raises a bare ``Exception`` and
+ leaves an empty or truncated file behind (`#5770 <https://github.com/kornia/kornia/issues/5770>`_).
+
Args:
path_file: Path with a .jpg, .jpeg, .png, .tif or .tiff extension, in any letter case.
- image: Image torch.Tensor with shape :math:`(C, H, W)` or :math:`(H, W)`; ``C`` is 1 or 3, or 4 for PNG.
- quality: The quality of the JPEG encoding, an integer in [0, 100]. It is validated for every format and used
- only for JPEG.
+ image: Image torch.Tensor with shape :math:`(C, H, W)` or :math:`(H, W)`.
+ quality: The quality of the JPEG encoding, an integer in [0, 100] and not a ``bool``. It is validated for
+ every format and used only for JPEG.
Return:
None.
Raises:
- TypeCheckError: if ``image`` is not a tensor, or ``quality`` is not an integer (a ``bool`` is not accepted).
- It is also a ``TypeError``.
- ValueCheckError: if ``quality`` is outside [0, 100]. It is also a ``ValueError``.
+ TypeCheckError: if ``image`` is not a tensor or ``quality`` is not an integer (also a ``TypeError``).
+ ValueCheckError: if ``quality`` is outside [0, 100] (also a ``ValueError``).
BaseError: if the extension is not one of the five above.
- ShapeError: if ``image`` is not :math:`(C, H, W)` or :math:`(H, W)`, or has a channel count the format cannot
- store. It is also a ``ValueError``.
- FileNotFoundError: if the directory to write into does not exist; ``NotADirectoryError`` if that path is a
- file.
- NotImplementedError: if the format cannot store the dtype: JPEG takes ``uint8``; PNG ``uint8`` and
- ``uint16``; TIFF ``uint8``, ``uint16`` and ``float32``.
- Exception: kornia-rs's error, a bare ``Exception``, when the file cannot be created (for example without
- write permission) or the image cannot be encoded, such as one with zero height or width
- (`#5770 <https://github.com/kornia/kornia/issues/5770>`_).
+ ShapeError: if ``image`` is not 2-D or 3-D, or the format cannot store its channels (also a ``ValueError``).
+ FileNotFoundError: if the directory to write into does not exist (``NotADirectoryError`` if it is a file).
+ NotImplementedError: if the format cannot store the dtype.
+ Exception: kornia-rs's bare ``Exception`` when the file cannot be created or the image cannot be encoded.
"""
if not isinstance(path_file, Path):
path_file = Path(path_file)
diff --git a/kornia/io/sample.py b/kornia/io/sample.py
index ab5881fa4..bb232faa3 100644
--- a/kornia/io/sample.py
+++ b/kornia/io/sample.py
@@ -111,34 +111,40 @@ def get_sample_images(
divisible_factor: Optional[int] = None,
**kwargs: Any,
) -> Union[torch.Tensor, List[torch.Tensor]]:
- """Load multiple images from the given URLs.
+ """Load multiple images from the given paths or URLs.
Optionally download them, resize them if specified, and return them as a batch of tensors or a list of tensors.
- Removed from ``kornia.utils.sample`` in 0.8.3 and restored here as public API β€” the docs and downstream
- demos rely on it.
+ Convention:
+ - Each image loads with :func:`~kornia.io.load_image`'s default type, ``RGB32``: :math:`(3, H, W)`
+ ``float32`` in [0, 1].
+ - A path is a URL only when its scheme is ``http`` or ``https``. A URL is cached under ``cache_dir`` with the
+ file name of its path, byte for byte as downloaded, and a cached file is loaded without downloading it
+ again. With ``download=False``, a URL that is not cached logs an error and raises ``FileNotFoundError``.
+ - ``resize`` is ``(height, width)`` and goes to :func:`~kornia.geometry.transform.resize`; ``divisible_factor``
+ is applied after it by :func:`~kornia.geometry.transform.resize_to_be_divisible`, so the final size can
+ differ from ``resize``. ``**kwargs`` reach both.
+ - The result is one :math:`(B, 3, H, W)` tensor when ``resize`` is given and ``as_list`` is not ``True``, and a
+ list of :math:`(3, H, W)` tensors otherwise; ``as_list=False`` without ``resize`` still gives a list.
Args:
paths: A list of path or URL from which to load or download images.
Defaults to the pre-defined sample image URLs if not provided.
- resize: Optional target size for resizing all images as a tuple (height, width).
- If not provided, the images will not be resized, and their original sizes will be retained.
+ resize: Optional target size ``(height, width)`` for every image. If not provided, the images keep their
+ sizes unless ``divisible_factor`` is given.
download: Whether to download the images if they are not already cached. Defaults to True.
cache_dir: The directory where the downloaded images will be cached.
Defaults to ``<kornia_config.hub_cache_dir>/images``, relative to the working directory unless configured
otherwise. Created when an image has to be downloaded. A download is loaded from a temporary file of its
own before it is renamed into the cache, so a download that does not load as an image never reaches the
cache: its temporary file is removed and the error propagates.
- as_list: if to keep the output as a list. If None and `resize` is None, the output will be a list.
- If None and `resize` is not None, the output will be a single tensor.
+ as_list: ``True`` to return a list even when ``resize`` is given.
divisible_factor:
- If not None, the images will be resized to the nearest multiple of `divisible_factor`.
- **kwargs: Additional keyword arguments to pass to `kornia.geometry.resize`.
+ If not None, each side of every image is resized to a multiple of ``divisible_factor``.
+ **kwargs: Additional keyword arguments for both resizes.
Returns:
- torch.Tensor | list[torch.Tensor]:
- If `resize` is provided, returns a single stacked tensor with shape (B, C, H, W).
- Otherwise, returns a list of tensors, each with its original shape (C, H, W).
+ torch.Tensor | list[torch.Tensor]: the images, stacked or as a list.
"""
import kornia.geometry # local import to avoid a circular dependency at import time
diff --git a/tests/core/test_module.py b/tests/core/test_module.py
index e16e3b692..c0e3f28f2 100644
--- a/tests/core/test_module.py
+++ b/tests/core/test_module.py
@@ -17,7 +17,9 @@
import io
import os
+import struct
import sys
+import zlib
from typing import NamedTuple
from unittest.mock import MagicMock
@@ -705,6 +707,34 @@ class TestImageModuleConversions(BaseTester):
out = _Identity().to_tensor(str(path))
self.assert_close(out, torch.tensor([1.0, 0.2, 0.0]).view(3, 1, 1).expand(3, 4, 6))
+ def test_convention_to_tensor_reads_a_palette_png_path_as_its_colours(self, tmp_path, device, dtype):
+ # An 8-bit palette PNG path converts to its colours, as a PIL image of the same file does, not to one channel
+ # of index / 255. The file is written byte by byte, so no decoder is the oracle. Palette yellow, green, red,
+ # blue; the indices are not in raster order and repeat, so each pixel must be looked up by its index. The
+ # expected planes are the R, G and B of [[red, green, yellow], [blue, yellow, green]].
+ def chunk(kind, body):
+ return struct.pack(">I", len(body)) + kind + body + struct.pack(">I", zlib.crc32(kind + body))
+
+ indices = [[2, 1, 0], [3, 0, 1]] # H = 2, W = 3
+ path = tmp_path / "palette.png"
+ path.write_bytes(
+ b"\x89PNG\r\n\x1a\n"
+ + chunk(b"IHDR", struct.pack(">IIBBBBB", 3, 2, 8, 3, 0, 0, 0)) # width, height, 8 bits, colour type 3
+ + chunk(b"PLTE", bytes([255, 255, 0, 0, 255, 0, 255, 0, 0, 0, 0, 255]))
+ + chunk(b"IDAT", zlib.compress(b"".join(b"\x00" + bytes(row) for row in indices)))
+ + chunk(b"IEND", b"")
+ )
+ module = _Identity()
+ module.register_buffer("reference", torch.empty((), device=device, dtype=dtype)) # output device and dtype
+ out = module.to_tensor(str(path))
+ expected = [
+ [[255, 0, 255], [0, 255, 0]], # R
+ [[0, 255, 255], [0, 255, 255]], # G
+ [[0, 0, 0], [255, 0, 0]], # B
+ ]
+ assert out.shape == (3, 2, 3)
+ self.assert_close(out, torch.tensor(expected, device=device, dtype=dtype) / 255)
+
def test_numpy_output_round_trips_through_numpy_input_5207(self):
module = _Identity()
image = np.random.default_rng(0).integers(0, 256, (4, 6, 3), dtype=np.uint8)
diff --git a/tests/image/test_draw.py b/tests/image/test_draw.py
index 87819c05a..e0b49f95a 100644
--- a/tests/image/test_draw.py
+++ b/tests/image/test_draw.py
@@ -1042,3 +1042,105 @@ class TestFillConvexPolygon(BaseTester):
draw_convex_polygon(img, poly, torch.tensor([1.0], device=device, dtype=dtype))
assert img[0, 0, 2, 2].item() == 1.0
assert not img.isnan().any()
+
+
+class TestConventionsDraw(BaseTester):
+ """Pins for the (x, y) order, inclusive corners, polygon edge rule and in-place drawing."""
+
+ def test_convention_draw_coordinates_are_x_then_y(self, device, dtype):
+ img = torch.zeros(1, 3, 5, device=device, dtype=dtype) # H = 3, W = 5
+ draw_point2d(img, torch.tensor([[4, 1]], device=device), torch.tensor([1.0], device=device))
+ assert img[0].nonzero().tolist() == [[1, 4]] # (row y, column x)
+ transposed = torch.zeros(1, 5, 3, device=device, dtype=dtype)
+ draw_point2d(transposed, torch.tensor([[1, 4]], device=device), torch.tensor([1.0], device=device))
+ self.assert_close(transposed[0], img[0].T)
+
+ def test_convention_rectangle_includes_both_corners(self, device, dtype):
+ img = torch.zeros(1, 1, 5, 7, device=device, dtype=dtype) # H = 5, W = 7
+ rect = torch.tensor([[[1, 0, 4, 2]]], device=device) # x1, y1, x2, y2
+ out = draw_rectangle(img, rect, torch.tensor([1.0], device=device), fill=True)
+ assert out[0, 0].nonzero().min(0).values.tolist() == [0, 1]
+ assert out[0, 0].nonzero().max(0).values.tolist() == [2, 4] # (row y2, column x2) is drawn
+ assert out.sum().item() == 3 * 4 # rows 0..2 x columns 1..4: (y2 - y1 + 1) * (x2 - x1 + 1)
+ outline = draw_rectangle(torch.zeros_like(img), rect, torch.tensor([1.0], device=device))
+ assert outline[0, 0, 2, 4].item() == 1.0
+ assert outline[0, 0, 1, 2].item() == 0.0 # the interior of an outline stays untouched
+ transposed = draw_rectangle(
+ torch.zeros(1, 1, 7, 5, device=device, dtype=dtype),
+ torch.tensor([[[0, 1, 2, 4]]], device=device),
+ torch.tensor([1.0], device=device),
+ fill=True,
+ )
+ self.assert_close(transposed[0, 0], out[0, 0].T)
+
+ def test_convention_polygon_fills_centres_on_or_inside_its_edges(self, device, dtype):
+ # A pixel is filled when its centre is on or inside the polygon: edges at x = 1.5 and 3.5 fill columns 2 and
+ # 3 only; an edge exactly through x = 1 includes column 1.
+ colors = torch.tensor([1.0], device=device, dtype=dtype)
+ img = torch.zeros(1, 1, 4, 6, device=device, dtype=dtype) # H = 4, W = 6
+ poly = torch.tensor([[[1.5, 0.0], [3.5, 0.0], [3.5, 3.0], [1.5, 3.0]]], device=device, dtype=dtype)
+ out = draw_convex_polygon(img, poly, colors)
+ assert out[0, 0].nonzero()[:, 1].unique().tolist() == [2, 3]
+ assert out[0, 0].nonzero()[:, 0].unique().tolist() == [0, 1, 2, 3]
+ on_edge = torch.tensor([[[1.0, 0.0], [3.5, 0.0], [3.5, 3.0], [1.0, 3.0]]], device=device, dtype=dtype)
+ out = draw_convex_polygon(torch.zeros_like(img), on_edge, colors)
+ assert out[0, 0].nonzero()[:, 1].unique().tolist() == [1, 2, 3]
+ transposed = draw_convex_polygon(torch.zeros(1, 1, 6, 4, device=device, dtype=dtype), poly.flip(-1), colors)
+ self.assert_close(transposed[0, 0], draw_convex_polygon(torch.zeros_like(img), poly, colors)[0, 0].T)
+
+ def test_convention_concave_polygon_fills_each_scanline_span(self, device, dtype):
+ # draw_convex_polygon fills, on each scanline (row), everything from the leftmost to the rightmost edge
+ # crossing, so the notch of a concave "V" is filled. Rows 0..3 span columns 1..5. Outside the polygon are
+ # only row 0 columns 2..4 and row 1 column 3 (columns 2 and 4 of row 1 lie on the notch edges, which count as
+ # inside); they are filled anyway.
+ color = torch.tensor([1.0], device=device, dtype=dtype)
+ notched = torch.tensor(
+ [[[1.0, 0.0], [3.0, 2.0], [5.0, 0.0], [5.0, 3.0], [1.0, 3.0]]], device=device, dtype=dtype
+ ) # (x, y)
+ out = draw_convex_polygon(torch.zeros(1, 1, 5, 7, device=device, dtype=dtype), notched, color) # H = 5, W = 7
+ expected = torch.zeros(5, 7, device=device, dtype=dtype)
+ expected[0:4, 1:6] = 1.0
+ self.assert_close(out[0, 0], expected)
+
+ # The span is per row, not per column: the same polygon with x and y swapped (a ">" whose notch opens to the
+ # left) is filled exactly as the polygon, with no notch filled in (the scanlines are still rows).
+ # Snippet: rows y = 1..5 span [min x, max x] over the edges (0,1)-(2,3), (2,3)-(0,5), x = 3 and y = 1 / 5:
+ # y=1: 0..3, y=2: 1..3, y=3: 2..3, y=4: 1..3, y=5: 0..3
+ swapped = draw_convex_polygon(
+ torch.zeros(1, 1, 7, 5, device=device, dtype=dtype), notched.flip(-1), color
+ ) # H = 7, W = 5
+ expected_swapped = torch.tensor(
+ [
+ [0, 0, 0, 0, 0],
+ [1, 1, 1, 1, 0],
+ [0, 1, 1, 1, 0],
+ [0, 0, 1, 1, 0],
+ [0, 1, 1, 1, 0],
+ [1, 1, 1, 1, 0],
+ [0, 0, 0, 0, 0],
+ ],
+ device=device,
+ dtype=dtype,
+ )
+ self.assert_close(swapped[0, 0], expected_swapped)
+
+ @pytest.mark.parametrize("name", ["draw_point2d", "draw_line", "draw_rectangle", "draw_convex_polygon"])
+ def test_convention_draw_functions_draw_in_place(self, device, dtype, name):
+ # Each function writes into the tensor it is given and returns that same object.
+ color = torch.tensor([1.0], device=device, dtype=dtype)
+ batch = torch.zeros(1, 1, 5, 7, device=device, dtype=dtype) # H = 5, W = 7
+ if name == "draw_point2d":
+ target = batch[0] # (C, H, W)
+ out = draw_point2d(target, torch.tensor([[3, 1]], device=device), color)
+ elif name == "draw_line":
+ target = batch[0] # (C, H, W)
+ out = draw_line(target, torch.tensor([0, 0], device=device), torch.tensor([3, 2], device=device), color)
+ elif name == "draw_rectangle":
+ target = batch
+ out = draw_rectangle(target, torch.tensor([[[1, 1, 3, 2]]], device=device), color, fill=True)
+ else:
+ target = batch
+ poly = torch.tensor([[[1.0, 1.0], [3.0, 1.0], [3.0, 2.0]]], device=device, dtype=dtype)
+ out = draw_convex_polygon(target, poly, color)
+ assert out is target
+ assert batch.sum().item() > 0 # the caller's storage was written
diff --git a/tests/image/test_image.py b/tests/image/test_image.py
index e5f2970d9..0f3aad7e8 100644
--- a/tests/image/test_image.py
+++ b/tests/image/test_image.py
@@ -334,3 +334,46 @@ class TestCheckImageLayout(BaseTester):
data = torch.rand(3, 4, 5, device=device)
layout = ImageLayout(ImageSize(10, 10), 3, ChannelsOrder.CHANNELS_FIRST)
assert not KORNIA_CHECK_IMAGE_LAYOUT(data, layout, raises=False)
+
+
+class TestConventionsImage(BaseTester):
+ """Pins for the unbatched layout, same-space conversions and NumPy aliasing of ``Image``."""
+
+ def test_convention_image_is_unbatched(self):
+ # Image holds one (H, W, C) or (C, H, W) image; a batched 4-D tensor is rejected by its dimension count.
+ # Image.from_numpy of a 4-D array raises the same ShapeError.
+ batched = torch.zeros(2, 4, 5, 3, dtype=torch.uint8)
+ layout = ImageLayout(ImageSize(4, 5), 3, ChannelsOrder.CHANNELS_LAST)
+ with pytest.raises(ShapeError, match="expected 3 dimensions, got 4"):
+ Image(batched, PixelFormat(ColorSpace.RGB, 8), layout)
+ with pytest.raises(ShapeError, match="expected 3 dimensions, got 4"):
+ Image.from_numpy(np.zeros((2, 4, 5, 3), np.uint8))
+
+ @pytest.mark.parametrize(
+ ("color_space", "channels", "convert"),
+ [
+ (ColorSpace.GRAY, 1, "to_gray"),
+ (ColorSpace.RGB, 3, "to_rgb"),
+ (ColorSpace.BGR, 3, "to_bgr"),
+ ],
+ )
+ @pytest.mark.parametrize("array_dtype", [np.uint8, np.uint16])
+ def test_convention_color_conversion_to_the_same_space_returns_self(
+ self, color_space, channels, convert, array_dtype
+ ):
+ image = Image.from_numpy(np.zeros((4, 5, channels), dtype=array_dtype), color_space=color_space)
+ assert getattr(image, convert)() is image
+
+ def test_convention_uint16_rgb_to_gray_is_unsupported(self):
+ image = Image.from_numpy(np.ones((2, 3, 3), dtype=np.uint16))
+ with pytest.raises(TypeError, match=r"Unknown data type: torch\.uint16"):
+ image.to_gray()
+
+ def test_convention_from_numpy_shares_memory(self):
+ array = np.zeros((4, 5, 3), dtype=np.uint8) # H = 4, W = 5
+ image = Image.from_numpy(array)
+ assert (image.height, image.width, image.channels) == (4, 5, 3)
+ array[3, 4, 2] = 9
+ assert image.data[3, 4, 2].item() == 9
+ image.data[0, 1, 0] = 5
+ assert array[0, 1, 0] == 5
diff --git a/tests/image/test_image_utils.py b/tests/image/test_image_utils.py
index fc2442a55..567a9cc26 100644
--- a/tests/image/test_image_utils.py
+++ b/tests/image/test_image_utils.py
@@ -293,3 +293,71 @@ def test_image_to_tensor_rejects_a_non_ndarray(bad):
def test_make_grid_rejects_negative_padding():
with pytest.raises(ValueError, match="padding"):
kornia.image.make_grid(torch.zeros(4, 1, 3, 5), padding=-1)
+
+
+class TestConventionsConversion(BaseTester):
+ """Pins for NumPy <-> tensor conversion: dtype, aliasing, batch axis and the grid layout."""
+
+ def test_convention_image_to_tensor_keeps_dtype_and_shares_memory(self):
+ array = (np.arange(4 * 5 * 3) % 256).astype(np.uint8).reshape(4, 5, 3) # H = 4, W = 5
+ tensor = kornia.image.image_to_tensor(array)
+ assert tensor.dtype == torch.uint8 # no rescale to [0, 1], no cast to float
+ assert tensor.shape == (3, 4, 5)
+ assert tensor.data_ptr() == array.ctypes.data # a (C, H, W) view of the array, not a copy
+ array[1, 2, 0] = 200
+ assert tensor[0, 1, 2].item() == 200
+
+ def test_convention_image_to_tensor_rejects_negative_strides(self):
+ array = np.arange(4 * 5 * 3, dtype=np.uint8).reshape(4, 5, 3)
+ with pytest.raises(ValueError): # torch.from_numpy cannot view a negative stride, e.g. an OpenCV BGR flip
+ kornia.image.image_to_tensor(array[..., ::-1])
+ tensor = kornia.image.image_to_tensor(array[..., ::-1].copy())
+ assert tensor[:, 0, 0].tolist() == [2, 1, 0] # channels reversed, (C, H, W)
+
+ def test_convention_tensor_to_image_shares_memory_with_a_cpu_tensor(self):
+ tensor = torch.zeros(3, 4, 5)
+ array = kornia.image.tensor_to_image(tensor)
+ assert array.shape == (4, 5, 3)
+ assert array.__array_interface__["data"][0] == tensor.data_ptr()
+ tensor[2, 3, 4] = 7.0
+ assert array[3, 4, 2] == 7.0
+
+ def test_convention_tensor_to_image_drops_a_single_channel_keepdim_keeps_only_batch(self, device, dtype):
+ # keepdim keeps the batch axis of a (1, C, H, W) input; it never keeps a single channel axis.
+ single = torch.rand(1, 1, 4, 5, device=device, dtype=dtype)
+ assert kornia.image.tensor_to_image(single).shape == (4, 5)
+ assert kornia.image.tensor_to_image(single, keepdim=True).shape == (1, 4, 5)
+ assert kornia.image.tensor_to_image(single[0]).shape == (4, 5)
+ three = torch.rand(1, 3, 4, 5, device=device, dtype=dtype)
+ assert kornia.image.tensor_to_image(three).shape == (4, 5, 3)
+ assert kornia.image.tensor_to_image(three, keepdim=True).shape == (1, 4, 5, 3)
+
+ def test_convention_keepdim_defaults_differ(self):
+ # ImageToTensor() defaults to keepdim=False and adds a batch axis; image_to_tensor defaults to keepdim=True.
+ array = np.zeros((4, 5, 3), dtype=np.uint8)
+ assert kornia.image.ImageToTensor()(array).shape == (1, 3, 4, 5)
+ assert kornia.image.image_to_tensor(array).shape == (3, 4, 5)
+ assert kornia.image.ImageToTensor(keepdim=True)(array).shape == (3, 4, 5)
+ assert kornia.image.image_to_tensor(array, keepdim=False).shape == (1, 3, 4, 5)
+
+ def test_convention_make_grid_n_row_is_images_per_row(self, device, dtype):
+ # n_row is the number of images in each row, despite its name: B = 5, n_row = 2 gives 3 rows of 2 tiles.
+ tensor = torch.arange(1, 6, device=device, dtype=dtype).view(5, 1, 1, 1).expand(5, 1, 2, 3) # H = 2, W = 3
+ grid = kornia.image.make_grid(tensor, n_row=2, padding=0)
+ assert grid.shape == (1, 6, 6)
+ expected = torch.tensor(
+ [[1, 1, 1, 2, 2, 2], [1, 1, 1, 2, 2, 2], [3, 3, 3, 4, 4, 4], [3, 3, 3, 4, 4, 4]]
+ + [[5, 5, 5, 0, 0, 0], [5, 5, 5, 0, 0, 0]],
+ device=device,
+ dtype=dtype,
+ )
+ self.assert_close(grid[0], expected)
+
+ def test_convention_make_grid_pads_only_between_tiles(self, device, dtype):
+ # padding is a gap between tiles with no outer border: (C, rows * (H + p) - p, cols * (W + p) - p).
+ tensor = torch.ones(5, 2, 2, 3, device=device, dtype=dtype) # B = 5, H = 2, W = 3
+ grid = kornia.image.make_grid(tensor, n_row=2, padding=1)
+ assert grid.shape == (2, 3 * 2 + 2, 2 * 3 + 1)
+ assert grid[:, 0, 0].tolist() == [1.0, 1.0] # first tile starts at the corner
+ assert grid[:, 2, :].sum().item() == 0.0 # the gap row between tile rows
+ assert grid[:, :, 3].sum().item() == 0.0 # the gap column between tile columns
diff --git a/tests/image/test_print.py b/tests/image/test_print.py
index a86274e28..2ae35376f 100644
--- a/tests/image/test_print.py
+++ b/tests/image/test_print.py
@@ -16,10 +16,12 @@
#
import os
+import re
import pytest
import torch
+from kornia.core.exceptions import ValueCheckError
from kornia.image import image_print, image_to_string, print_image
from kornia.io import write_image
@@ -173,3 +175,38 @@ class TestNearestXterm:
out = capsys.readouterr().out
assert out.count("\x1b[48;5;16m") == 6 # 2 x 3 black pixels
assert out.count("\x1b[0m\n") == 2
+
+
+class TestConventionsPrint:
+ """Pins for the value ranges and the width defaults of the terminal printers."""
+
+ @pytest.mark.parametrize(
+ ("image", "expected_range"),
+ [
+ (torch.full((3, 2, 4), 1.5), "expected [0, 1]"),
+ (torch.full((3, 2, 4), -0.5), "expected [0, 1]"),
+ (torch.full((3, 2, 4), 256, dtype=torch.int64), "expected [0, 255]"),
+ ],
+ ids=["float-above-1", "float-below-0", "int-above-255"],
+ )
+ def test_convention_image_to_string_value_ranges(self, image, expected_range):
+ # A float image is read as [0, 1] and an integer one as [0, 255]; anything outside raises.
+ with pytest.raises(ValueCheckError, match=re.escape(expected_range)):
+ image_to_string(image)
+
+ @pytest.mark.parametrize("dtype", [torch.uint8, torch.int64])
+ def test_convention_image_to_string_integer_255_is_float_1(self, dtype):
+ # The accepted boundaries: integer 255 is the same colour as float 1.0, so integers are not read as [0, 1].
+ assert image_to_string(torch.full((3, 2, 4), 255, dtype=dtype)) == image_to_string(torch.ones(3, 2, 4))
+
+ def test_convention_print_max_width_defaults(self, capsys):
+ # image_to_string caps the width at 256 pixels by default and print_image at 96. Each printed pixel is one
+ # "\x1b[48;5;<code>m " escape, so a 300-pixel-wide image prints 256 or 96 cells per row.
+ image = torch.zeros(3, 2, 300)
+ string = image_to_string(image)
+ assert string.count("\033[0m\n") == 1 # H = 2 shrinks to max(1, 2 * 256 // 300) = 1 row
+ assert string.count("\033[48;5;") == 256
+ print_image(image)
+ printed = capsys.readouterr().out
+ assert printed.count("\033[0m\n") == 1 # max(1, 2 * 96 // 300) = 1 row
+ assert printed.count("\033[48;5;") == 96
diff --git a/tests/io/test_io_image.py b/tests/io/test_io_image.py
index 0f54c565a..d2d84bbc3 100644
--- a/tests/io/test_io_image.py
+++ b/tests/io/test_io_image.py
@@ -1074,3 +1074,132 @@ class TestWiderThanUint8Decodes:
expected = rf"decoded to torch\.float32, and ImageLoadType\.{load_type.name}"
with pytest.raises(NotImplementedError, match=expected):
load_image(path, load_type)
+
+
+class TestConventionsIo:
+ """Pins for the channel, dtype, alpha, orientation and format policies of ``load_image`` and ``write_image``."""
+
+ @staticmethod
+ def _rgb() -> torch.Tensor:
+ return (torch.arange(3 * 4 * 5) * 11 % 256).to(torch.uint8).view(3, 4, 5) # H = 4, W = 5, asymmetric
+
+ @pytest.mark.parametrize(
+ ("load_type", "channels"),
+ [
+ (ImageLoadType.GRAY8, 1),
+ (ImageLoadType.GRAY32, 1),
+ (ImageLoadType.RGB8, 3),
+ (ImageLoadType.RGB32, 3),
+ (ImageLoadType.RGBA8, 4),
+ ],
+ )
+ @pytest.mark.parametrize("file_channels", [1, 3])
+ def test_convention_load_image_channels_follow_the_load_type(self, tmp_path, load_type, channels, file_channels):
+ # The load type fixes the channel count whatever the file holds; only UNCHANGED keeps the file's own count.
+ path = tmp_path / "image.png"
+ write_image(path, self._rgb()[:file_channels])
+ assert load_image(path, load_type).shape == (channels, 4, 5)
+
+ @pytest.mark.parametrize("file_channels", [1, 3])
+ def test_convention_load_image_unchanged_keeps_the_file_channels(self, tmp_path, file_channels):
+ path = tmp_path / "image.png"
+ write_image(path, self._rgb()[:file_channels])
+ assert load_image(path, ImageLoadType.UNCHANGED).shape == (file_channels, 4, 5)
+
+ def test_convention_load_image_default_is_rgb32_float_in_unit_range_on_cpu(self, tmp_path):
+ pixels = self._rgb().clone()
+ pixels[0, 0, 0], pixels[0, 0, 1] = 0, 255
+ path = tmp_path / "image.png"
+ write_image(path, pixels)
+ out = load_image(path)
+ assert out.dtype == torch.float32
+ assert out.device.type == "cpu"
+ assert out.shape == (3, 4, 5)
+ assert out.min().item() == 0.0
+ assert out.max().item() == 1.0
+ torch.testing.assert_close(out, load_image(path, ImageLoadType.RGB32))
+ torch.testing.assert_close(out, pixels.float() / 255.0)
+
+ def test_convention_load_image_composites_alpha_over_white(self, tmp_path):
+ # A transparent pixel loads as white, an opaque one keeps its colour, and a semi-transparent one is
+ # composited over white and rounded; OpenCV and Pillow drop the alpha channel instead.
+ # Snippet: [round(c * 64 / 255 + 255 * (1 - 64 / 255)) for c in (200, 100, 50)] -> [241, 216, 204]
+ pixels = torch.zeros(4, 3, 5, dtype=torch.uint8) # (C, H, W), H = 3, W = 5
+ pixels[:] = torch.tensor([10, 20, 30, 255], dtype=torch.uint8)[:, None, None]
+ pixels[:, 0, 0] = torch.tensor([200, 100, 50, 64], dtype=torch.uint8)
+ pixels[:, 2, 4] = torch.tensor([7, 8, 9, 0], dtype=torch.uint8)
+ path = tmp_path / "rgba.png"
+ write_image(path, pixels)
+ out = load_image(path, ImageLoadType.RGB8)
+ assert out.shape == (3, 3, 5)
+ assert out[:, 0, 0].tolist() == [241, 216, 204]
+ assert out[:, 2, 4].tolist() == [255, 255, 255]
+ assert out[:, 1, 2].tolist() == [10, 20, 30]
+
+ def test_convention_load_image_ignores_exif_orientation(self, tmp_path):
+ # The decoded array is the stored one, (C, H, W) = (3, 4, 8); cv2.imread honours orientation 6 and would give
+ # (8, 4, 3) for this file. The APP1 block below is a TIFF header with one IFD entry: Orientation (0x0112) = 6.
+ plain = tmp_path / "plain.jpg"
+ write_image(plain, (torch.arange(3 * 4 * 8) * 5 % 256).to(torch.uint8).view(3, 4, 8))
+ exif = (
+ b"Exif\x00\x00MM\x00*\x00\x00\x00\x08" # Exif marker, big-endian TIFF header, IFD at offset 8
+ b"\x00\x01\x01\x12\x00\x03\x00\x00\x00\x01\x00\x06\x00\x00" # 1 entry: tag 0x0112, SHORT, 1, value 6
+ b"\x00\x00\x00\x00" # no next IFD
+ )
+ data = plain.read_bytes()
+ tagged = tmp_path / "tagged.jpg"
+ tagged.write_bytes(data[:2] + b"\xff\xe1" + struct.pack(">H", len(exif) + 2) + exif + data[2:])
+ out = load_image(tagged, ImageLoadType.RGB8)
+ assert out.shape == (3, 4, 8)
+ torch.testing.assert_close(out, load_image(plain, ImageLoadType.RGB8))
+
+ def test_convention_write_image_formats_per_dtype(self, tmp_path):
+ # uint8 -> jpg, png, tif; uint16 -> png, tif; float32 -> tif; everything else raises NotImplementedError.
+ image = self._rgb()
+ for ext in ("jpg", "png", "tif"):
+ write_image(tmp_path / f"u8.{ext}", image)
+ assert load_image(tmp_path / f"u8.{ext}", ImageLoadType.UNCHANGED).shape == (3, 4, 5)
+ for ext in ("png", "tif"):
+ write_image(tmp_path / f"u16.{ext}", image.to(torch.uint16) * 200)
+ out = load_image(tmp_path / f"u16.{ext}", ImageLoadType.UNCHANGED)
+ assert out.dtype == torch.uint16
+ assert out.shape == (3, 4, 5)
+ # a float32 TIFF is written without clamping: values in [-0.5, 1.5] come back unchanged
+ wide = image.float() / 255 * 2 - 0.5
+ assert wide.min() < 0
+ assert wide.max() > 1
+ write_image(tmp_path / "f32.tif", wide)
+ out = load_image(tmp_path / "f32.tif", ImageLoadType.UNCHANGED)
+ assert out.dtype == torch.float32
+ assert out.shape == (3, 4, 5)
+ torch.testing.assert_close(out, wide, rtol=0.0, atol=0.0)
+
+ rejected = [(torch.uint16, "jpg"), (torch.float32, "png"), (torch.float32, "jpg")]
+ rejected += [(torch.float64, ext) for ext in ("jpg", "png", "tif")]
+ for dtype, ext in rejected:
+ with pytest.raises(NotImplementedError, match=r"Unsupported (file extension|image dtype)"):
+ write_image(tmp_path / f"bad.{ext}", image.to(dtype))
+
+ def test_convention_write_image_jpeg_quality_default_is_80(self, tmp_path):
+ image = (torch.arange(3 * 16 * 24) * 37 % 256).to(torch.uint8).view(3, 16, 24) # H = 16, W = 24
+ written = {}
+ for name, kwargs in (("default", {}), ("q80", {"quality": 80}), ("q95", {"quality": 95})):
+ write_image(tmp_path / f"{name}.jpg", image, **kwargs)
+ written[name] = (tmp_path / f"{name}.jpg").read_bytes()
+ assert written["default"] == written["q80"]
+ assert written["default"] != written["q95"]
+
+ @pytest.mark.parametrize(
+ ("shape", "match"),
+ [
+ ((3, 0, 4), "[Zz]ero height|non zero|invalid dimensions"),
+ ((3, 4, 0), "[Zz]ero width|non zero|invalid dimensions"),
+ ],
+ )
+ def test_wart_write_image_zero_size_raises_bare_exception_5770(self, tmp_path, shape, match):
+ # #5770: a zero-height or zero-width image reaches kornia-rs, whose error is a bare ``Exception``. The fix
+ # should raise a kornia error (a ShapeError) before encoding, which flips this pin.
+ for ext in ("png", "jpg", "tif"):
+ with pytest.raises(Exception, match=match) as excinfo:
+ write_image(tmp_path / f"zero.{ext}", torch.zeros(*shape, dtype=torch.uint8))
+ assert excinfo.type is Exception