Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

fix(io): palette and colour-key PNGs, grayscale JPEG channels, RGBA/.tif writes, argument checks (#5808)

Dmytro Mishkinb37544990236
diff --git a/changelog.d/5808.breaking.md b/changelog.d/5808.breaking.md
new file mode 100644
index 000000000..084dae2ca
--- /dev/null
+++ b/changelog.d/5808.breaking.md
@@ -0,0 +1,16 @@
+`load_image(path, ImageLoadType.UNCHANGED)` returns a grayscale JPEG as one channel, `(1, H, W)`; it used to return
+three equal channels. Image modules given a file path, such as `AugmentationSequential` and `ImageSequential`, now
+receive `(1, 1, H, W)` for such a file instead of `(1, 3, H, W)`, so a colour augmentation such as `ColorJiggle`
+raises for it, as it already did for a grayscale PNG path. Invalid arguments raise a typed kornia error up front:
+`load_image` raises `TypeCheckError` (a `TypeError`) when `desired_type` is not an `ImageLoadType`, where it raised
+`NotImplementedError`, or `AttributeError` for a 16-bit file. `write_image` raises `TypeCheckError` for an input that
+is not a tensor, where it raised `AttributeError`. It validates `quality` for every format, including PNG and TIFF,
+which used to ignore it: a value that is not an integer raises `TypeCheckError`, and one outside [0, 100] raises
+`ValueCheckError` (a `ValueError`), where a JPEG accepted 101 to 255 (101 gave the same file as 100) and raised
+`OverflowError` beyond that. A batched `(B, C, H, W)` tensor raises `ShapeError` (a `ValueError`) naming the shape,
+where kornia-rs raised a `TypeError`. Writing into a directory that does not exist raises `FileNotFoundError` naming
+the directory, and writing under a path that is a file raises `NotADirectoryError`; both used to raise a bare
+`Exception`. `get_sample_images` caches downloads under `<kornia_config.hub_cache_dir>/images` by default instead of
+a hard-coded `.kornia_hub/images`; the two are the same path unless `hub_cache_dir` is changed. A download that is not
+an image raises `ValueError` naming the cached file, which is deleted, where it raised `PIL.UnidentifiedImageError`, an
+`OSError`, so an `except OSError` clause no longer catches it.
diff --git a/changelog.d/5808.fixed.md b/changelog.d/5808.fixed.md
new file mode 100644
index 000000000..77febff59
--- /dev/null
+++ b/changelog.d/5808.fixed.md
@@ -0,0 +1,18 @@
+`load_image` returns an 8-bit palette PNG's colours under every load type except `UNCHANGED`, which still returns the
+palette indices: it used to return the indices as gray for every type. `RGBA8` takes alpha from the `tRNS` chunk, and
+the RGB and gray types composite transparent entries over white, as for any RGBA file; under these types, a palette that
+is malformed or too short for its pixels, or a `PLTE` or `tRNS` chunk that is truncated or fails its CRC check, raises
+`ValueError` naming the file instead of being used. 1-, 2- and 4-bit palette PNGs still raise, because kornia-rs cannot
+decode them. A `tRNS` colour key on an 8-bit gray or RGB PNG now makes the key colour transparent in the same way
+instead of being ignored. Compositing a semi-transparent pixel over white rounds to the nearest level instead of
+truncating, which made it up to one level too dark. `write_image` writes 4-channel (RGBA) PNGs and accepts `.tif` and
+extensions in any letter case, such as `.JPG`, all of which it used to reject; a channel count the format cannot store
+raises `ShapeError`, still a `ValueError`, naming the supported counts instead of kornia-rs's "expected 3 channels".
+`get_sample_images` saves a download byte for byte instead of decoding it and re-encoding JPEGs at Pillow's default
+quality 75, so it no longer needs Pillow. It writes each download to a temporary file of its own that replaces the
+cached file only when complete, so an interrupted download leaves no partial file in the cache and concurrent downloads
+of the same image do not interfere. A cache filled by an earlier version keeps its re-encoded files until they are
+deleted. It creates its cache directory only when it has to download, not for local paths, and treats a path as a URL
+only when its scheme is `http` or `https`, so a local file named `http_local.png` loads, and names the cached file after
+the URL's path, without its query or fragment; a URL whose path names no file raises `ValueError` before anything is
+downloaded.
diff --git a/docs/source/get-started/installation.rst b/docs/source/get-started/installation.rst
index a30d20600..3ab4c8f5c 100644
--- a/docs/source/get-started/installation.rst
+++ b/docs/source/get-started/installation.rst
@@ -69,7 +69,7 @@ notebook, whose kernel's stdin is not a terminal (use ``"auto"`` there). The def
- What it enables
- Install command
* - ``image``
- - Pillow-backed PIL input/output and display helpers, plus remote image decoding in :func:`kornia.io.get_sample_images`
+ - Pillow-backed PIL input/output and display helpers
- ``pip install "kornia[image]"``
* - ``onnx``
- :doc:`kornia.onnx </onnx>`, ONNX export of Kornia modules, and :class:`~kornia.feature.OnnxLightGlue`
diff --git a/kornia/io/io.py b/kornia/io/io.py
index 89feeb1f7..a02d1f8d1 100644
--- a/kornia/io/io.py
+++ b/kornia/io/io.py
@@ -17,21 +17,29 @@
from __future__ import annotations
+import errno
+import numbers
+import os
+import zlib
from enum import Enum
from pathlib import Path
from typing import Any, Union
+import numpy as np
import torch
from kornia_rs import io as _rs_io
import kornia
-from kornia.core.check import KORNIA_CHECK
+from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_IS_TENSOR
+from kornia.core.exceptions import ShapeError, TypeCheckError, ValueCheckError
from kornia.image.utils import image_to_tensor, tensor_to_image
+_WRITE_EXTENSIONS = (".jpg", ".jpeg", ".png", ".tif", ".tiff")
+
def _color_mode(img_np: Any) -> str:
- """Return the kornia_rs colour mode of an HxWxC array: ``"mono"`` for one channel, ``"rgb"`` otherwise."""
- return "mono" if img_np.shape[-1] == 1 else "rgb"
+ """Return the kornia_rs colour mode of an HxWxC array with 1, 3 or 4 channels."""
+ return {1: "mono", 3: "rgb", 4: "rgba"}[img_np.shape[-1]]
class ImageLoadType(Enum):
@@ -69,10 +77,122 @@ def _read_png_header(path_file: Path) -> tuple[int, int] | None:
# release decodes it, so ``read_image`` raises for such a file.
_PNG_COLOR_TYPE_TO_MODE: dict[int, str] = {
0: "mono", # Grayscale
- 3: "mono", # Indexed (palette) β€” decoded as single channel by kornia_rs
+ 3: "mono", # Indexed (palette): kornia_rs returns the indices; load_image expands them unless UNCHANGED
6: "rgba", # RGBA
}
+# Start-of-frame markers (SOF0-SOF15 without DHT 0xC4, JPG 0xC8 and DAC 0xCC); byte 5 of their payload is the number
+# of colour components.
+_JPEG_SOF_MARKERS = frozenset({0xC0, 0xC1, 0xC2, 0xC3, 0xC5, 0xC6, 0xC7, 0xC9, 0xCA, 0xCB, 0xCD, 0xCE, 0xCF})
+
+
+def _read_jpeg_components(path_file: Path) -> int | None:
+ """Return the number of colour components in a JPEG frame header, or None if the file has no readable one."""
+ with open(path_file, "rb") as f:
+ if f.read(2) != b"\xff\xd8":
+ return None
+ while True:
+ if f.read(1) != b"\xff":
+ return None
+ code = f.read(1)
+ while code == b"\xff": # fill bytes may precede a marker
+ code = f.read(1)
+ if not code:
+ return None
+ marker = code[0]
+ if marker == 0x01 or 0xD0 <= marker <= 0xD7: # markers without a length field
+ continue
+ length = f.read(2)
+ if len(length) < 2:
+ return None
+ if marker in _JPEG_SOF_MARKERS:
+ frame = f.read(6) # precision, height, width, number of components
+ return frame[5] if len(frame) == 6 else None
+ if marker == 0xDA: # start of scan before any frame header
+ return None
+ f.seek(int.from_bytes(length, "big") - 2, os.SEEK_CUR)
+
+
+def _read_png_chunks(path_file: Path) -> tuple[bytes | None, bytes | None]:
+ """Return the raw bodies of a PNG's PLTE and tRNS chunks, None for a chunk the file does not have.
+
+ Both chunks are checked as a PNG decoder checks them: a truncated body or a stored CRC that does not match the
+ chunk raises ``ValueError`` naming the file. Every other chunk is skipped unread.
+ """
+ plte: bytes | None = None
+ trns: bytes | None = None
+ with open(path_file, "rb") as f:
+ if f.read(8) != _PNG_SIGNATURE:
+ return None, None
+ while True:
+ head = f.read(8)
+ kind = head[4:8]
+ if len(head) < 8 or kind in (b"IDAT", b"IEND"): # PLTE and tRNS precede the image data
+ break
+ size = int.from_bytes(head[:4], "big")
+ if kind not in (b"PLTE", b"tRNS"):
+ f.seek(size + 4, os.SEEK_CUR) # body and CRC
+ continue
+ body = f.read(size)
+ crc = f.read(4)
+ name = kind.decode("ascii")
+ if len(body) < size or len(crc) < 4:
+ raise ValueError(f"Failed to decode image '{path_file}': its {name} chunk is truncated.")
+ if int.from_bytes(crc, "big") != zlib.crc32(kind + body):
+ raise ValueError(f"Failed to decode image '{path_file}': its {name} chunk fails its CRC check.")
+ if kind == b"PLTE":
+ plte = body
+ else:
+ trns = body
+ return plte, trns
+
+
+def _apply_png_palette_and_transparency(path_file: Path, image: torch.Tensor) -> torch.Tensor:
+ """Apply a PNG's palette and tRNS chunk to the decoded pixels; any other file is returned unchanged.
+
+ An 8-bit palette PNG (colour type 3) becomes ``(3, H, W)`` colours, or ``(4, H, W)`` with a tRNS chunk, whose
+ per-entry alphas leave unlisted entries opaque. An 8-bit gray or RGB PNG (colour types 0 and 2) with a tRNS colour
+ key becomes ``(4, H, W)`` RGBA, with alpha 0 where every sample equals the key and 255 elsewhere.
+ """
+ if path_file.suffix.lower() != ".png":
+ return image
+ header = _read_png_header(path_file)
+ if header is None or header[1] not in (0, 2, 3):
+ return image
+ bit_depth, color_type = header
+ plte, trns = _read_png_chunks(path_file)
+ if color_type == 3:
+ if plte is None:
+ return image
+ if len(plte) % 3:
+ raise ValueError(
+ f"Failed to decode image '{path_file}': its PLTE chunk has {len(plte)} bytes, not a whole number of "
+ "RGB entries."
+ )
+ colors = torch.frombuffer(bytearray(plte), dtype=torch.uint8).view(-1, 3)
+ table = colors
+ if trns is not None:
+ alpha = torch.full((colors.shape[0],), 255, dtype=torch.uint8)
+ listed = torch.frombuffer(bytearray(trns), dtype=torch.uint8)[: colors.shape[0]]
+ alpha[: listed.numel()] = listed
+ table = torch.cat([colors, alpha[:, None]], dim=1)
+ indices = image[0].long()
+ if indices.numel() and int(indices.max()) >= table.shape[0]:
+ raise ValueError(
+ f"Failed to decode image '{path_file}': a pixel uses palette entry {int(indices.max())}, "
+ f"but the palette has {table.shape[0]} entries."
+ )
+ return table.to(image.device)[indices].permute(2, 0, 1).contiguous()
+
+ # colour key: one (gray) or three (RGB) big-endian 16-bit samples; an 8-bit image uses their low bytes
+ n_samples = 1 if color_type == 0 else 3
+ if bit_depth != 8 or trns is None or len(trns) < 2 * n_samples:
+ return image
+ key = torch.tensor([trns[2 * i + 1] for i in range(n_samples)], dtype=torch.uint8, device=image.device)
+ transparent = (image == key[:, None, None]).all(dim=0, keepdim=True)
+ alpha = torch.where(transparent, 0, 255).to(torch.uint8)
+ return torch.cat([image.expand(3, -1, -1), alpha], dim=0)
+
def _load_image_to_tensor(path_file: Path, device: Union[str, torch.device, None]) -> torch.Tensor:
"""Read an image file and decode using the Kornia Rust backend.
@@ -80,11 +200,11 @@ def _load_image_to_tensor(path_file: Path, device: Union[str, torch.device, None
The decoded image is returned as numpy array with shape HxWxC.
Args:
- path_file: Path to a valid image file.
+ path_file: Path to an image file in a format kornia-rs decodes; the extension may be in any letter case.
device: the device where you want to get your image placed.
Return:
- Image torch.Tensor with shape :math:`(3,H,W)`.
+ Image torch.Tensor with shape :math:`(C, H, W)`, as decoded.
"""
# read image and return as `np.ndarray` with shape HxWxC
@@ -96,6 +216,10 @@ def _load_image_to_tensor(path_file: Path, device: Union[str, torch.device, None
pass
if path_file.suffix.lower() in [".jpg", ".jpeg"]:
img = _rs_io.read_image_jpegturbo(str(path_file))
+ if _read_jpeg_components(path_file) == 1:
+ # libjpeg-turbo decodes a grayscale JPEG into three equal channels; keep the file's one channel
+ # in its own buffer, so the three-channel decode is released
+ img = np.ascontiguousarray(img[..., :1])
elif path_file.suffix.lower() == ".png":
# None (truncated/invalid header) intentionally falls through to read_image
bit_depth, color_type = _read_png_header(path_file) or (None, None)
@@ -131,9 +255,9 @@ def _to_float32(image: torch.Tensor) -> torch.Tensor:
def _to_uint8(image: torch.Tensor) -> torch.Tensor:
- """Convert an image torch.Tensor to uint8."""
+ """Convert a float image in [0, 1] to uint8, rounding to the nearest level."""
KORNIA_CHECK(image.dtype == torch.float32)
- return image.mul(255.0).byte()
+ return image.mul(255.0).round_().clamp_(0, 255).to(torch.uint8)
def _convert_image_type(image: torch.Tensor, desired_type: ImageLoadType) -> torch.Tensor:
@@ -193,25 +317,44 @@ def load_image(
"""Read an image file and decode using the Kornia Rust backend.
Args:
- path_file: Path to a valid image file.
+ 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.
desired_type: the desired image type, defined by color space and dtype.
device: the device where you want to get your image placed.
Return:
- Image torch.Tensor with shape :math:`(3,H,W)`.
+ 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.
Raises:
- ValueError: if the file cannot be decoded, for example a truncated or corrupt image or an unsupported format.
- The message names the file and keeps the decoder's reason; the decoder's exception is the ``__cause__``.
+ TypeCheckError: if ``desired_type`` is not an :class:`ImageLoadType`. It is 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.
"""
+ if not isinstance(desired_type, ImageLoadType):
+ raise TypeCheckError(
+ f"desired_type must be an ImageLoadType, got {desired_type!r}.",
+ actual_type=type(desired_type),
+ expected_type=ImageLoadType,
+ )
if not isinstance(path_file, Path):
path_file = Path(path_file)
# read the image using the kornia_rs package
image: torch.Tensor = _load_image_to_tensor(path_file, device) # CxHxW
+ if desired_type != ImageLoadType.UNCHANGED:
+ image = _apply_png_palette_and_transparency(path_file, image)
+
return _convert_image_type(image, desired_type)
@@ -222,7 +365,7 @@ def _write_uint8_image(path_file: Path, img_np: Any, quality: int) -> None:
_rs_io.write_image_jpeg(str(path_file), img_np, mode=mode, quality=quality)
elif path_file.suffix.lower() == ".png":
_rs_io.write_image_png_u8(str(path_file), img_np, mode=mode)
- elif path_file.suffix.lower() == ".tiff":
+ elif path_file.suffix.lower() in (".tif", ".tiff"):
_rs_io.write_image_tiff_u8(str(path_file), img_np, mode=mode)
else:
raise NotImplementedError(f"Unsupported file extension: {path_file.suffix} for uint8 image")
@@ -233,7 +376,7 @@ def _write_uint16_image(path_file: Path, img_np: Any) -> None:
mode = _color_mode(img_np)
if path_file.suffix.lower() == ".png":
_rs_io.write_image_png_u16(str(path_file), img_np, mode=mode)
- elif path_file.suffix.lower() == ".tiff":
+ elif path_file.suffix.lower() in (".tif", ".tiff"):
_rs_io.write_image_tiff_u16(str(path_file), img_np, mode=mode)
else:
raise NotImplementedError(f"Unsupported file extension: {path_file.suffix} for uint16 image")
@@ -242,7 +385,7 @@ def _write_uint16_image(path_file: Path, img_np: Any) -> None:
def _write_float32_image(path_file: Path, img_np: Any) -> None:
"""Write float32 image to file."""
mode = _color_mode(img_np)
- if path_file.suffix.lower() == ".tiff":
+ if path_file.suffix.lower() in (".tif", ".tiff"):
_rs_io.write_image_tiff_f32(str(path_file), img_np, mode=mode)
else:
raise NotImplementedError(f"Unsupported file extension: {path_file.suffix} for float32 image")
@@ -252,26 +395,71 @@ def write_image(path_file: str | Path, image: torch.Tensor, quality: int = 80) -
"""Save an image file using the Kornia Rust backend.
Args:
- path_file: Path to a valid image file.
- image: Image torch.Tensor with shape :math:`(3,H,W)`, `(1,H,W)` and `(H,W)`.
- quality: The quality of the JPEG encoding. If the file extension is .png or .tiff, the quality is ignored.
+ 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.
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``.
+ 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>`_).
"""
if not isinstance(path_file, Path):
path_file = Path(path_file)
+ KORNIA_CHECK_IS_TENSOR(image)
+ if not isinstance(quality, numbers.Integral) or isinstance(quality, bool):
+ raise TypeCheckError(
+ f"quality must be an integer in [0, 100], got {quality!r}.",
+ actual_type=type(quality),
+ expected_type=numbers.Integral,
+ )
+ if not 0 <= quality <= 100:
+ raise ValueCheckError(
+ f"quality must be an integer in [0, 100], got {quality!r}.", actual_value=quality, expected_range=(0, 100)
+ )
+ suffix = path_file.suffix.lower()
KORNIA_CHECK(
- path_file.suffix in [".jpg", ".jpeg", ".png", ".tiff"],
- f"Invalid file extension: {path_file}, only .jpg, .jpeg, .png and .tiff are supported.",
+ suffix in _WRITE_EXTENSIONS,
+ f"Invalid file extension: {path_file}, only .jpg, .jpeg, .png, .tif and .tiff are supported.",
)
+ if image.dim() not in (2, 3):
+ raise ShapeError(
+ f"Invalid image shape: {tuple(image.shape)}. Expected (C, H, W) or (H, W).",
+ actual_shape=tuple(image.shape),
+ expected_shape=["C", "H", "W"],
+ )
- KORNIA_CHECK(image.dim() >= 2, f"Invalid image shape: {image.shape}. Must be at least 2D.")
+ parent = path_file.parent
+ if not parent.is_dir():
+ if parent.exists():
+ raise NotADirectoryError(errno.ENOTDIR, f"Cannot write {path_file.name} into a file", str(parent))
+ raise FileNotFoundError(errno.ENOENT, f"No such directory to write {path_file.name} into", str(parent))
img_np = tensor_to_image(image, keepdim=True, force_contiguous=True) # HxWxC
if img_np.ndim == 2:
img_np = img_np[..., None] # ensures channel dimension
+ channels = img_np.shape[-1]
+ supported = (1, 3, 4) if suffix == ".png" else (1, 3)
+ if channels not in supported:
+ raise ShapeError(
+ f"Cannot write a {channels}-channel image to {suffix}; the supported channel counts are {supported}.",
+ actual_shape=tuple(image.shape),
+ )
if image.dtype == torch.uint8:
_write_uint8_image(path_file, img_np, quality)
elif image.dtype == torch.uint16:
diff --git a/kornia/io/sample.py b/kornia/io/sample.py
index 120ccb25e..1635e3943 100644
--- a/kornia/io/sample.py
+++ b/kornia/io/sample.py
@@ -17,15 +17,17 @@
from __future__ import annotations
-import io
+import contextlib
import logging
import os
+import uuid
from typing import Any, List, Optional, Tuple, Union
+from urllib.parse import urlparse
from urllib.request import urlopen
import torch
-from kornia.core.external import PILImage as Image
+from kornia.config import kornia_config
from .io import load_image
@@ -44,17 +46,31 @@ _IMAGE_URLS: List[str] = [
def download_image(url: str, save_to: str) -> None:
- """Download an image from a given URL and save it to a specified file path.
+ """Download a file and save its bytes unchanged, so a JPEG is not decoded and re-encoded.
+
+ Each call writes the bytes to a temporary file of its own next to ``save_to`` and renames it onto ``save_to`` only
+ once the write is complete, removing it if the write fails. An interrupted download therefore never leaves a
+ partial file at ``save_to``, and concurrent downloads of the same file each replace it with a complete copy.
Args:
url: The URL of the image to download.
save_to: The file path where the downloaded image will be saved.
"""
- # get_sample_images only routes paths that start with "http" here (default: the https:// literals above).
+ # get_sample_images only routes http(s) URLs here (default: the https:// literals above).
with urlopen(url, timeout=30) as resp: # noqa: S310
- im = Image.open(io.BytesIO(resp.read()))
- im.save(save_to)
+ data = resp.read()
+ # a unique name in the destination directory keeps the rename atomic and concurrent calls apart; open() with "x"
+ # creates the file with the usual permissions (tempfile.mkstemp would make the cached image private, 0o600)
+ part = f"{save_to}.{uuid.uuid4().hex}.part"
+ try:
+ with open(part, "xb") as f:
+ f.write(data)
+ os.replace(part, save_to)
+ except BaseException:
+ with contextlib.suppress(FileNotFoundError):
+ os.remove(part)
+ raise
def get_sample_images(
@@ -80,7 +96,9 @@ def get_sample_images(
If not provided, the images will not be resized, and their original sizes will be retained.
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_hub/images".
+ 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 downloaded file that does not load as an image is
+ deleted before the error propagates, so it is not cached.
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.
divisible_factor:
@@ -96,23 +114,33 @@ def get_sample_images(
import kornia.geometry # local import to avoid a circular dependency at import time
if cache_dir is None:
- cache_dir = ".kornia_hub/images"
- os.makedirs(cache_dir, exist_ok=True)
+ cache_dir = os.path.join(kornia_config.hub_cache_dir, "images")
tensors = []
for path in paths:
- if path.startswith("http"):
- name = os.path.basename(path)
+ downloaded = False
+ url = urlparse(path)
+ if url.scheme in ("http", "https"):
+ name = os.path.basename(url.path) # the cache file is named without the URL's query or fragment
+ if not name:
+ raise ValueError(f"Cannot derive a cache file name from URL `{path}`: its path names no file.")
fname = os.path.join(cache_dir, name)
if not os.path.exists(fname) and download:
+ os.makedirs(cache_dir, exist_ok=True)
logging.info(f"Downloading `{path}` to `{fname}`.")
download_image(path, fname)
+ downloaded = True
elif not os.path.exists(fname) and not download:
logging.error(
f"Image `{path}` not found at `{fname}`. You may want to set `download=True` to download it."
)
else:
fname = path
- img_tensor = load_image(fname)
+ try:
+ img_tensor = load_image(fname)
+ except Exception:
+ if downloaded:
+ os.remove(fname) # a body that is not an image must not stay in the cache
+ raise
if resize is not None:
img_tensor = kornia.geometry.resize(img_tensor, resize, **kwargs)
if divisible_factor is not None:
diff --git a/kornia/models/base.py b/kornia/models/base.py
index d26fdd7bd..14d114eb5 100644
--- a/kornia/models/base.py
+++ b/kornia/models/base.py
@@ -47,11 +47,10 @@ def _write_png_batch(path_stem: str, image: torch.Tensor) -> None:
``ImageModule`` hands a tensor to PIL: clamped, scaled and rounded. A
``uint8`` or ``uint16`` visualization is written as-is.
- ``write_image`` takes ``(3, H, W)``, ``(1, H, W)`` or ``(H, W)``, but the
- containers document their inputs as ``(B, 3, H, W)`` and passed the batch
- straight through. The backend then rejects the rank with an error that
- names neither -- ``TypeError: argument 'image': 'ndarray' object is not an
- instance of 'ndarray'`` -- so a batch has to be split here.
+ ``write_image`` takes one image, ``(3, H, W)``, ``(1, H, W)``, ``(H, W)`` or,
+ for PNG only, ``(4, H, W)``, and rejects a batched tensor; the containers
+ document their inputs as ``(B, 3, H, W)``, so a batch is written as one file
+ per item.
A batch of one still gets an index suffix, so a caller does not have to
guess whether a file will be ``name.png`` or ``name_0.png``.
diff --git a/tests/io/test_io_image.py b/tests/io/test_io_image.py
index 4bbebcec1..a5ac419ec 100644
--- a/tests/io/test_io_image.py
+++ b/tests/io/test_io_image.py
@@ -17,6 +17,8 @@
import io
import re
+import struct
+import zlib
from pathlib import Path
import kornia_rs
@@ -24,7 +26,9 @@ import numpy as np
import pytest
import torch
+from kornia.core.exceptions import ShapeError, TypeCheckError, ValueCheckError
from kornia.io import ImageLoadType, load_image, write_image
+from kornia.io.io import _read_jpeg_components, _read_png_chunks
def create_random_img8(height: int, width: int, channels: int) -> np.ndarray:
@@ -36,12 +40,54 @@ def create_random_img8_torch(height: int, width: int, channels: int, device=None
def write_random_png_u16(path: Path, mode: str) -> None:
- """Write a random 16-bit PNG, ``"mono"`` (grayscale) or ``"rgba"``; ``write_image`` cannot write RGBA."""
+ """Write a random 16-bit PNG, ``"mono"`` (grayscale) or ``"rgba"``, with kornia-rs directly."""
channels = {"mono": 1, "rgba": 4}[mode]
img_np = np.random.randint(0, 65535, (4, 5, channels)).astype(np.uint16) # noqa: NPY002
kornia_rs.io.write_image_png_u16(str(path), img_np, mode=mode)
+def _png_chunk(kind: bytes, data: bytes) -> bytes:
+ return struct.pack(">I", len(data)) + kind + data + struct.pack(">I", zlib.crc32(kind + data) & 0xFFFFFFFF)
+
+
+def write_indexed_png(path: Path, indices: np.ndarray, palette: list, alpha: bytes | None = None) -> None:
+ """Write an 8-bit palette PNG (colour type 3) byte by byte, so the test needs no image library."""
+ height, width = indices.shape
+ raw = b"".join(b"\x00" + indices[row].astype(np.uint8).tobytes() for row in range(height))
+ chunks = [
+ _png_chunk(b"IHDR", struct.pack(">IIBBBBB", width, height, 8, 3, 0, 0, 0)),
+ _png_chunk(b"PLTE", bytes(channel for colour in palette for channel in colour)),
+ ]
+ if alpha is not None:
+ chunks.append(_png_chunk(b"tRNS", alpha))
+ chunks += [_png_chunk(b"IDAT", zlib.compress(raw)), _png_chunk(b"IEND", b"")]
+ path.write_bytes(b"\x89PNG\r\n\x1a\n" + b"".join(chunks))
+
+
+def write_png_with_trns(path: Path, pixels: np.ndarray, colour_type: int, trns: bytes | None = None) -> None:
+ """Write an 8-bit gray (colour type 0) or RGB (2) PNG with an optional tRNS colour key, byte by byte."""
+ height, width = pixels.shape[:2]
+ raw = b"".join(b"\x00" + pixels[row].astype(np.uint8).tobytes() for row in range(height))
+ chunks = [_png_chunk(b"IHDR", struct.pack(">IIBBBBB", width, height, 8, colour_type, 0, 0, 0))]
+ if trns is not None:
+ chunks.append(_png_chunk(b"tRNS", trns))
+ chunks += [_png_chunk(b"IDAT", zlib.compress(raw)), _png_chunk(b"IEND", b"")]
+ path.write_bytes(b"\x89PNG\r\n\x1a\n" + b"".join(chunks))
+
+
+def corrupt_chunk_crc(path: Path, kind: bytes) -> None:
+ """Add 1 to the stored CRC of the first ``kind`` chunk, leaving its length and body intact."""
+ data = bytearray(path.read_bytes())
+ start = data.index(kind) - 4 # the 4-byte length precedes the chunk type
+ crc_at = start + 8 + int.from_bytes(data[start : start + 4], "big")
+ data[crc_at : crc_at + 4] = ((int.from_bytes(data[crc_at : crc_at + 4], "big") + 1) & 0xFFFFFFFF).to_bytes(4, "big")
+ path.write_bytes(bytes(data))
+
+
+PALETTE = [(255, 255, 0), (0, 255, 0), (255, 0, 0), (0, 0, 255)]
+PALETTE_INDICES = np.array([[2, 1, 0], [3, 0, 1]], dtype=np.uint8) # H = 2, W = 3
+
+
@pytest.fixture(scope="session")
def png_image(tmp_path_factory):
"""RGB PNG written locally so load tests do not depend on the network."""
@@ -226,6 +272,449 @@ class TestIoImage:
assert torch.equal(loaded, img)
+class TestIndexedPng:
+ def test_unchanged_keeps_the_palette_indices(self, tmp_path: Path) -> None:
+ path = tmp_path / "indexed.png"
+ write_indexed_png(path, PALETTE_INDICES, PALETTE)
+ out = load_image(path, ImageLoadType.UNCHANGED)
+ assert out.dtype == torch.uint8
+ assert out.tolist() == [PALETTE_INDICES.tolist()]
+
+ @pytest.mark.parametrize("load_type", [ImageLoadType.RGB8, ImageLoadType.RGB32])
+ def test_rgb_types_expand_the_palette(self, tmp_path: Path, device, load_type) -> None:
+ path = tmp_path / "indexed.png"
+ write_indexed_png(path, PALETTE_INDICES, PALETTE)
+ expected = torch.tensor([PALETTE[i] for i in PALETTE_INDICES.flatten()], dtype=torch.uint8, device=device)
+ expected = expected.T.reshape(3, 2, 3)
+ if load_type == ImageLoadType.RGB32:
+ expected = expected.float() / 255.0
+ out = load_image(path, load_type, device=str(device))
+ assert out.device.type == torch.device(device).type
+ torch.testing.assert_close(out, expected)
+
+ def test_gray8_is_the_gray_of_the_palette_colours(self, tmp_path: Path) -> None:
+ path = tmp_path / "indexed.png"
+ write_indexed_png(path, PALETTE_INDICES, PALETTE)
+ # cv2.cvtColor(rgb, cv2.COLOR_RGB2GRAY): red 76, green 150, yellow 226, blue 29
+ expected = torch.tensor([[[76, 150, 226], [29, 226, 150]]], dtype=torch.uint8)
+ torch.testing.assert_close(load_image(path, ImageLoadType.GRAY8), expected)
+
+ def test_rgba8_takes_alpha_from_the_trns_chunk(self, tmp_path: Path, device) -> None:
+ path = tmp_path / "indexed_trns.png"
+ write_indexed_png(path, PALETTE_INDICES, PALETTE, alpha=bytes([0, 128])) # entries 2 and 3 stay opaque
+ out = load_image(path, ImageLoadType.RGBA8, device=str(device))
+ assert out.device.type == torch.device(device).type
+ assert out.shape == (4, 2, 3)
+ assert out[3].tolist() == [[255, 128, 0], [255, 0, 128]]
+
+ def test_rgb8_composites_transparent_palette_entries_over_white(self, tmp_path: Path) -> None:
+ path = tmp_path / "indexed_trns.png"
+ write_indexed_png(path, PALETTE_INDICES, PALETTE, alpha=bytes([0, 128]))
+ out = load_image(path, ImageLoadType.RGB8)
+ # round(c * a / 255 + 255 * (1 - a / 255)): yellow at alpha 0 -> white, green at alpha 128 -> (127, 255, 127)
+ assert out[:, 0, 2].tolist() == [255, 255, 255]
+ assert out[:, 0, 1].tolist() == [127, 255, 127]
+ assert out[:, 0, 0].tolist() == [255, 0, 0]
+
+ def test_index_beyond_the_palette_raises_naming_the_file(self, tmp_path: Path) -> None:
+ path = tmp_path / "short_palette.png"
+ write_indexed_png(path, PALETTE_INDICES, PALETTE[:2]) # indices 2 and 3 have no colour
+ with pytest.raises(ValueError, match=re.escape(path.name)):
+ load_image(path, ImageLoadType.RGB8)
+
+ def test_index_equal_to_the_palette_length_raises_naming_the_file(self, tmp_path: Path, device) -> None:
+ path = tmp_path / "three_entries.png"
+ write_indexed_png(path, PALETTE_INDICES, PALETTE[:3]) # entries 0..2; the pixel with index 3 has no colour
+ with pytest.raises(ValueError, match=re.escape(path.name)):
+ load_image(path, ImageLoadType.RGB8, device=str(device))
+
+ def test_a_palette_that_is_not_whole_rgb_entries_raises_naming_the_file(self, tmp_path: Path) -> None:
+ path = tmp_path / "bad_plte.png"
+ write_indexed_png(path, PALETTE_INDICES, [*PALETTE, (7,)]) # a 13-byte PLTE chunk
+ with pytest.raises(ValueError, match=re.escape(path.name)):
+ load_image(path, ImageLoadType.RGB8)
+
+
+class TestCorruptPngChunks:
+ # load_image reads PLTE and tRNS itself, so it checks their CRC and length like a PNG decoder; kornia-rs 0.2.0
+ # accepts a tRNS chunk with a bad CRC, which Pillow 12.3 rejects ("cannot identify image file")
+ @pytest.mark.parametrize("load_type", [ImageLoadType.RGBA8, ImageLoadType.RGB8])
+ def test_palette_trns_with_a_bad_crc_raises_naming_the_file(self, tmp_path: Path, load_type) -> None:
+ path = tmp_path / "bad_trns.png"
+ write_indexed_png(path, PALETTE_INDICES, PALETTE, alpha=bytes([0, 128]))
+ corrupt_chunk_crc(path, b"tRNS")
+ with pytest.raises(ValueError, match=re.escape(path.name) + ".*tRNS"):
+ load_image(path, load_type)
+
+ @pytest.mark.parametrize("load_type", [ImageLoadType.RGBA8, ImageLoadType.GRAY8])
+ def test_colour_key_with_a_bad_crc_raises_naming_the_file(self, tmp_path: Path, load_type) -> None:
+ path = tmp_path / "bad_key.png"
+ write_png_with_trns(
+ path, np.array([[10, 20, 10], [20, 10, 20]], dtype=np.uint8), colour_type=0, trns=struct.pack(">H", 10)
+ )
+ corrupt_chunk_crc(path, b"tRNS")
+ with pytest.raises(ValueError, match=re.escape(path.name) + ".*tRNS"):
+ load_image(path, load_type)
+
+ def test_unchanged_does_not_read_the_trns_chunk(self, tmp_path: Path) -> None:
+ # UNCHANGED returns what kornia-rs decodes, the indices, and never looks at tRNS, so its CRC is not checked
+ path = tmp_path / "bad_trns.png"
+ write_indexed_png(path, PALETTE_INDICES, PALETTE, alpha=bytes([0, 128]))
+ corrupt_chunk_crc(path, b"tRNS")
+ assert load_image(path, ImageLoadType.UNCHANGED).tolist() == [PALETTE_INDICES.tolist()]
+
+ def test_plte_with_a_bad_crc_raises_naming_the_file(self, tmp_path: Path) -> None:
+ path = tmp_path / "bad_plte.png"
+ write_indexed_png(path, PALETTE_INDICES, PALETTE)
+ corrupt_chunk_crc(path, b"PLTE")
+ with pytest.raises(ValueError, match=re.escape(path.name) + ".*PLTE"):
+ _read_png_chunks(path)
+ with pytest.raises(ValueError, match=re.escape(path.name)): # kornia-rs rejects a bad PLTE CRC itself
+ load_image(path, ImageLoadType.RGB8)
+
+ def test_truncated_plte_body_raises_naming_the_file(self, tmp_path: Path) -> None:
+ path = tmp_path / "truncated.png"
+ write_indexed_png(path, PALETTE_INDICES, PALETTE)
+ data = path.read_bytes()
+ path.write_bytes(data[: data.index(b"PLTE") + 4 + 6]) # 6 of the 12 palette bytes, then end of file
+ with pytest.raises(ValueError, match=re.escape(path.name) + ".*PLTE.*truncated"):
+ _read_png_chunks(path)
+ with pytest.raises(ValueError, match=re.escape(path.name)) as error:
+ load_image(path, ImageLoadType.RGB8)
+ assert "palette entry" not in str(error.value)
+
+
+class TestGrayJpeg:
+ @staticmethod
+ def _gray() -> torch.Tensor:
+ return (torch.arange(12 * 20) % 251).to(torch.uint8).view(1, 12, 20) # H = 12, W = 20
+
+ def test_unchanged_keeps_one_channel(self, tmp_path: Path) -> None:
+ path = tmp_path / "gray.jpg"
+ write_image(path, self._gray(), quality=95)
+ out = load_image(path, ImageLoadType.UNCHANGED)
+ assert out.shape == (1, 12, 20)
+ torch.testing.assert_close(out, load_image(path, ImageLoadType.GRAY8))
+
+ @pytest.mark.parametrize("load_type", [ImageLoadType.UNCHANGED, ImageLoadType.GRAY8])
+ def test_one_channel_owns_a_contiguous_buffer(self, tmp_path: Path, load_type) -> None:
+ path = tmp_path / "gray.jpg"
+ write_image(path, self._gray(), quality=95)
+ out = load_image(path, load_type)
+ assert out.is_contiguous()
+ assert out.untyped_storage().nbytes() == 12 * 20 # not the three-channel decode buffer
+
+ def test_rgb8_repeats_the_gray_channel(self, tmp_path: Path) -> None:
+ path = tmp_path / "gray.jpg"
+ write_image(path, self._gray(), quality=95)
+ gray = load_image(path, ImageLoadType.UNCHANGED)
+ torch.testing.assert_close(load_image(path, ImageLoadType.RGB8), gray.expand(3, -1, -1))
+
+ def test_large_app_segment_before_the_frame_header(self, tmp_path: Path) -> None:
+ plain = tmp_path / "gray.jpg"
+ write_image(plain, self._gray(), quality=95)
+ data = plain.read_bytes()
+ payload = b"Exif\x00\x00" + b"x" * 60000 # a camera-sized APP1 block between SOI and the frame header
+ tagged = tmp_path / "gray_exif.jpg"
+ tagged.write_bytes(data[:2] + b"\xff\xe1" + struct.pack(">H", len(payload) + 2) + payload + data[2:])
+ out = load_image(tagged, ImageLoadType.UNCHANGED)
+ assert out.shape == (1, 12, 20)
+ torch.testing.assert_close(out, load_image(plain, ImageLoadType.UNCHANGED))
+
+ @pytest.mark.parametrize(
+ ("marker", "fill", "components"),
+ [(0xC0, b"", 1), (0xC2, b"", 1), (0xC2, b"\xff\xff", 1), (0xC2, b"", 3), (0xC9, b"", 1)],
+ ids=["baseline", "progressive", "progressive-after-fill-bytes", "progressive-3-components", "arithmetic"],
+ )
+ def test_frame_header_component_count(self, tmp_path: Path, marker, fill, components) -> None:
+ # SOI, an APP0 segment, optional fill bytes, then a baseline (C0), progressive (C2) or arithmetic (C9) frame
+ # header: precision 8, height 12, width 20, the component count and 3 bytes per component
+ app0 = b"\xff\xe0" + struct.pack(">H", 16) + b"JFIF\x00" + bytes(9)
+ sof = struct.pack(">BHHB", 8, 12, 20, components) + bytes(3 * components)
+ header = b"\xff\xd8" + app0 + fill + bytes([0xFF, marker]) + struct.pack(">H", len(sof) + 2) + sof
+ path = tmp_path / "header.jpg"
+ path.write_bytes(header)
+ assert _read_jpeg_components(path) == components
+
+ def test_color_jpeg_unchanged_keeps_three_channels(self, tmp_path: Path) -> None:
+ path = tmp_path / "color.jpg"
+ write_image(path, create_random_img8_torch(12, 20, 3))
+ assert load_image(path, ImageLoadType.UNCHANGED).shape == (3, 12, 20)
+
+
+class TestAlphaRounding:
+ def test_semi_transparent_rgba_rounds_after_compositing(self, tmp_path: Path) -> None:
+ path = tmp_path / "rgba.png"
+ pixels = np.zeros((2, 3, 4), dtype=np.uint8)
+ pixels[...] = (200, 100, 50, 64)
+ kornia_rs.io.write_image_png_u8(str(path), pixels, mode="rgba")
+ # round(c * 64 / 255 + 255 * (1 - 64 / 255)) for c = 200, 100, 50 -> 241.2, 216.1, 203.5
+ assert load_image(path, ImageLoadType.RGB8)[:, 0, 0].tolist() == [241, 216, 204]
+
+
+class TestWriteImageValidation:
+ def test_rgba_png_round_trips(self, tmp_path: Path) -> None:
+ rgba = create_random_img8_torch(4, 5, 4)
+ path = tmp_path / "rgba.png"
+ write_image(path, rgba)
+ assert torch.equal(load_image(path, ImageLoadType.UNCHANGED), rgba)
+
+ def test_rgba_16_bit_png_round_trips(self, tmp_path: Path) -> None:
+ rgba = torch.randint(0, 65535, (4, 4, 5), dtype=torch.int32).to(torch.uint16)
+ path = tmp_path / "rgba16.png"
+ write_image(path, rgba)
+ assert torch.equal(load_image(path, ImageLoadType.UNCHANGED), rgba)
+
+ @pytest.mark.parametrize("ext", [".jpg", ".tiff"])
+ def test_rgba_to_a_format_without_alpha_raises_and_writes_nothing(self, tmp_path: Path, ext) -> None:
+ path = tmp_path / f"rgba{ext}"
+ with pytest.raises(ShapeError, match="4-channel"):
+ write_image(path, create_random_img8_torch(4, 5, 4))
+ assert not path.exists()
+
+ @pytest.mark.parametrize("ext", [".png", ".jpg", ".tiff"])
+ def test_two_channels_raise_and_write_nothing(self, tmp_path: Path, ext) -> None:
+ path = tmp_path / f"two{ext}"
+ with pytest.raises(ShapeError, match="2-channel"):
+ write_image(path, create_random_img8_torch(4, 5, 2))
+ assert not path.exists()
+
+ def test_an_unsupported_channel_count_is_still_a_value_error(self, tmp_path: Path) -> None:
+ # kornia-rs raised ValueError for these before write_image checked them; ShapeError keeps that catchable
+ with pytest.raises(ValueError, match="5-channel"):
+ write_image(tmp_path / "five.png", create_random_img8_torch(4, 5, 5))
+
+ @pytest.mark.parametrize("dtype", [torch.uint8, torch.uint16, torch.float32])
+ def test_tif_round_trips_every_tiff_dtype(self, tmp_path: Path, dtype) -> None:
+ image = torch.arange(3 * 4 * 5).view(3, 4, 5)
+ image = image.to(dtype) / 60 if dtype == torch.float32 else image.to(dtype)
+ path = tmp_path / "short.tif"
+ write_image(path, image)
+ assert torch.equal(load_image(path, ImageLoadType.UNCHANGED), image)
+
+ @pytest.mark.parametrize("name", ["upper.JPG", "upper.PNG", "short.tif", "mixed.TiFf"])
+ def test_extension_case_and_tif(self, tmp_path: Path, name) -> None:
+ rgb = create_random_img8_torch(4, 5, 3)
+ path = tmp_path / name
+ write_image(path, rgb)
+ loaded = load_image(path, ImageLoadType.UNCHANGED)
+ assert loaded.shape == (3, 4, 5)
+ if not name.lower().endswith(".jpg"):
+ assert torch.equal(loaded, rgb) # lossless formats round-trip exactly
+
+ def test_batched_tensor_raises_and_writes_nothing(self, tmp_path: Path) -> None:
+ path = tmp_path / "batched.png"
+ with pytest.raises(ShapeError, match=re.escape("(C, H, W)")):
+ write_image(path, create_random_img8_torch(4, 5, 3)[None])
+ assert not path.exists()
+
+
+class TestColourKeyPng:
+ # colour type 0 (gray) and 2 (RGB) PNGs carry a tRNS colour key: pixels equal to it are transparent
+ def test_gray_key_becomes_transparent_in_rgba8(self, tmp_path: Path) -> None:
+ path = tmp_path / "gray_key.png"
+ write_png_with_trns(
+ path, np.array([[10, 20, 10], [20, 10, 20]], dtype=np.uint8), colour_type=0, trns=struct.pack(">H", 10)
+ )
+ # Pillow 12.3 Image.open(path).convert("RGBA") alpha: [[0, 255, 0], [255, 0, 255]]
+ assert load_image(path, ImageLoadType.RGBA8)[3].tolist() == [[0, 255, 0], [255, 0, 255]]
+
+ def test_gray_key_composites_over_white_in_gray8(self, tmp_path: Path) -> None:
+ path = tmp_path / "gray_key.png"
+ write_png_with_trns(
+ path, np.array([[10, 20, 10], [20, 10, 20]], dtype=np.uint8), colour_type=0, trns=struct.pack(">H", 10)
+ )
+ # the keyed 10s composite over white to 255; the opaque 20s keep their value. Pillow 12.3:
+ # Image.alpha_composite(Image.new("RGBA", (3, 2), "white"), Image.open(path).convert("RGBA")).convert("L")
+ assert load_image(path, ImageLoadType.GRAY8)[0].tolist() == [[255, 20, 255], [20, 255, 20]]
+
+ def test_rgb_key_composites_over_white_in_rgb8(self, tmp_path: Path) -> None:
+ pixels = np.zeros((2, 3, 3), dtype=np.uint8)
+ pixels[0, 0] = (1, 2, 3)
+ path = tmp_path / "rgb_key.png"
+ write_png_with_trns(path, pixels, colour_type=2, trns=struct.pack(">HHH", 1, 2, 3))
+ out = load_image(path, ImageLoadType.RGB8)
+ assert out[:, 0, 0].tolist() == [255, 255, 255]
+ assert out[:, 1, 2].tolist() == [0, 0, 0]
+
+ def test_rgb_key_needs_every_sample_to_match(self, tmp_path: Path) -> None:
+ pixels = np.zeros((2, 3, 3), dtype=np.uint8)
+ pixels[0] = [(1, 2, 3), (1, 2, 0), (1, 0, 0)] # the key, then two pixels sharing some of its samples
+ path = tmp_path / "rgb_key_partial.png"
+ write_png_with_trns(path, pixels, colour_type=2, trns=struct.pack(">HHH", 1, 2, 3))
+ # Pillow 12.3 Image.open(path).convert("RGBA") alpha: [[0, 255, 255], [255, 255, 255]]
+ assert load_image(path, ImageLoadType.RGBA8)[3].tolist() == [[0, 255, 255], [255, 255, 255]]
+
+ def test_unchanged_ignores_the_key(self, tmp_path: Path) -> None:
+ path = tmp_path / "gray_key.png"
+ write_png_with_trns(
+ path, np.array([[10, 20, 10], [20, 10, 20]], dtype=np.uint8), colour_type=0, trns=struct.pack(">H", 10)
+ )
+ assert load_image(path, ImageLoadType.UNCHANGED).shape == (1, 2, 3)
+
+ def test_png_without_a_key_stays_opaque(self, tmp_path: Path) -> None:
+ path = tmp_path / "gray_nokey.png"
+ write_png_with_trns(path, np.array([[10, 20, 10], [20, 10, 20]], dtype=np.uint8), colour_type=0)
+ assert load_image(path, ImageLoadType.RGBA8)[3].tolist() == [[255] * 3] * 2
+
+
+class TestIoArgumentChecks:
+ def test_write_into_a_missing_directory_raises_file_not_found(self, tmp_path: Path) -> None:
+ path = tmp_path / "missing" / "x.png"
+ with pytest.raises(FileNotFoundError, match="missing"):
+ write_image(path, create_random_img8_torch(4, 5, 3))
+
+ def test_write_into_a_file_as_directory_raises_not_a_directory(self, tmp_path: Path) -> None:
+ parent = tmp_path / "plain_file"
+ parent.write_bytes(b"")
+ with pytest.raises(NotADirectoryError, match="plain_file"):
+ write_image(parent / "x.png", create_random_img8_torch(4, 5, 3))
+
+ def test_write_into_the_current_directory_with_a_bare_filename(self, tmp_path: Path, monkeypatch) -> None:
+ monkeypatch.chdir(tmp_path)
+ write_image("bare.png", create_random_img8_torch(4, 5, 3))
+ assert (tmp_path / "bare.png").exists()
+
+ @pytest.mark.parametrize("desired_type", ["RGB8", 2])
+ def test_load_image_rejects_a_load_type_that_is_not_an_image_load_type(self, png_image, desired_type) -> None:
+ with pytest.raises(TypeCheckError, match="ImageLoadType"):
+ load_image(png_image, desired_type)
+
+ @pytest.mark.parametrize("quality", [-1, 101, np.int64(101)])
+ def test_write_image_rejects_quality_outside_0_100(self, tmp_path: Path, quality) -> None:
+ with pytest.raises(ValueCheckError, match="quality"):
+ write_image(tmp_path / "q.jpg", create_random_img8_torch(4, 5, 3), quality=quality)
+
+ @pytest.mark.parametrize("quality", [80.5, True, "80"])
+ def test_write_image_rejects_a_quality_that_is_not_an_integer(self, tmp_path: Path, quality) -> None:
+ with pytest.raises(TypeCheckError, match="quality"):
+ write_image(tmp_path / "q.jpg", create_random_img8_torch(4, 5, 3), quality=quality)
+
+ def test_quality_is_validated_for_png_too(self, tmp_path: Path) -> None:
+ with pytest.raises(ValueCheckError, match="quality"):
+ write_image(tmp_path / "q.png", create_random_img8_torch(4, 5, 3), quality=101)
+
+ @pytest.mark.parametrize("quality", [0, 100, np.int64(90)])
+ def test_write_image_accepts_any_integer_quality_in_0_100(self, tmp_path: Path, quality) -> None:
+ path = tmp_path / "q.jpg"
+ write_image(path, create_random_img8_torch(4, 5, 3), quality=quality)
+ assert load_image(path, ImageLoadType.RGB8).shape == (3, 4, 5)
+
+ def test_write_image_rejects_a_non_tensor(self, tmp_path: Path) -> None:
+ with pytest.raises(TypeCheckError):
+ write_image(tmp_path / "n.png", np.zeros((3, 4, 5), dtype=np.uint8))
+
+
+class TestSampleImages:
+ def test_local_paths_create_no_cache_directory(self, tmp_path: Path) -> None:
+ from kornia.io import get_sample_images
+
+ path = tmp_path / "local.png"
+ write_image(path, create_random_img8_torch(4, 5, 3))
+ get_sample_images(paths=[str(path)], cache_dir=str(tmp_path / "cache"))
+ assert not (tmp_path / "cache").exists()
+
+ def test_a_relative_path_starting_with_http_is_a_local_file(self, tmp_path: Path, monkeypatch) -> None:
+ from kornia.io import get_sample_images
+
+ monkeypatch.chdir(tmp_path)
+ write_image(tmp_path / "http_local.png", create_random_img8_torch(4, 5, 3))
+ out = get_sample_images(paths=["http_local.png"], cache_dir=str(tmp_path / "cache"))
+ assert out[0].shape == (3, 4, 5)
+
+ def test_default_cache_dir_follows_the_hub_config(self, tmp_path: Path, monkeypatch) -> None:
+ from unittest import mock
+
+ from kornia.config import kornia_config
+ from kornia.io import get_sample_images
+
+ monkeypatch.setattr(kornia_config, "hub_cache_dir", str(tmp_path / "hub"))
+ payload = tmp_path / "src.png"
+ write_image(payload, create_random_img8_torch(4, 5, 3))
+ with mock.patch("kornia.io.sample.urlopen") as mock_urlopen:
+ mock_urlopen.return_value.__enter__.return_value.read.return_value = payload.read_bytes()
+ get_sample_images(paths=["https://example.invalid/sample.png"])
+ assert (tmp_path / "hub" / "images" / "sample.png").exists()
+
+ @pytest.mark.parametrize("suffix", ["?token=abc", "#section"])
+ def test_a_url_query_or_fragment_is_not_part_of_the_cache_name(self, tmp_path: Path, suffix) -> None:
+ from unittest import mock
+
+ from kornia.io import get_sample_images
+
+ source = tmp_path / "source.png"
+ write_indexed_png(source, PALETTE_INDICES, PALETTE)
+ cache = tmp_path / "cache"
+ with mock.patch("kornia.io.sample.urlopen") as mock_urlopen:
+ mock_urlopen.return_value.__enter__.return_value.read.return_value = source.read_bytes()
+ out = get_sample_images(paths=[f"https://example.invalid/x/palette.png{suffix}"], cache_dir=str(cache))
+ assert sorted(p.name for p in cache.iterdir()) == ["palette.png"]
+ assert (out[0][:, 0, 0] * 255).round().tolist() == [255.0, 0.0, 0.0] # index 2 is red: the palette applies
+
+ @pytest.mark.parametrize(
+ "url", ["https://example.invalid", "https://example.invalid/", "https://example.invalid/dir/"]
+ )
+ def test_a_url_without_a_file_name_raises_before_downloading(self, tmp_path: Path, url) -> None:
+ from unittest import mock
+
+ from kornia.io import get_sample_images
+
+ cache = tmp_path / "cache"
+ with mock.patch("kornia.io.sample.urlopen") as mock_urlopen:
+ with pytest.raises(ValueError, match=re.escape(url)):
+ get_sample_images(paths=[url], cache_dir=str(cache))
+ mock_urlopen.assert_not_called()
+ assert not cache.exists()
+
+ def test_concurrent_downloads_of_the_same_image_both_succeed(self, tmp_path: Path) -> None:
+ import os
+ import threading
+ from concurrent.futures import ThreadPoolExecutor
+ from unittest import mock
+
+ from kornia.io import get_sample_images
+
+ image = create_random_img8_torch(4, 5, 3)
+ source = tmp_path / "source.png"
+ write_image(source, image)
+ payload = source.read_bytes()
+ cache = tmp_path / "cache"
+ both_written = threading.Barrier(2, timeout=10)
+ real_replace = os.replace
+
+ def replace_after_both_writes(src, dst):
+ both_written.wait() # both calls have missed the cache and finished writing before either replaces
+ return real_replace(src, dst)
+
+ def fetch():
+ return get_sample_images(paths=["https://example.invalid/x/same.png"], cache_dir=str(cache))[0]
+
+ with (
+ mock.patch("kornia.io.sample.urlopen") as mock_urlopen,
+ mock.patch("kornia.io.sample.os.replace", replace_after_both_writes),
+ ThreadPoolExecutor(max_workers=2) as pool,
+ ):
+ mock_urlopen.return_value.__enter__.return_value.read.return_value = payload
+ results = [future.result() for future in [pool.submit(fetch), pool.submit(fetch)]]
+ expected = image.float() / 255.0
+ for out in results:
+ torch.testing.assert_close(out, expected)
+ assert sorted(p.name for p in cache.iterdir()) == ["same.png"] # no temporary file is left behind
+ assert (cache / "same.png").read_bytes() == payload
+
+ def test_a_download_that_is_not_an_image_is_not_cached(self, tmp_path: Path) -> None:
+ from unittest import mock
+
+ from kornia.io import get_sample_images
+
+ cache = tmp_path / "cache"
+ with mock.patch("kornia.io.sample.urlopen") as mock_urlopen:
+ mock_urlopen.return_value.__enter__.return_value.read.return_value = b"<html>not found</html>"
+ with pytest.raises(ValueError, match=re.escape("sample.png")):
+ get_sample_images(paths=["https://example.invalid/sample.png"], cache_dir=str(cache))
+ assert not (cache / "sample.png").exists()
+
+
class TestDownloadImage:
"""Offline pins for ``kornia.io.sample.download_image``; ``urlopen`` is mocked, no network is touched."""
@@ -250,6 +739,79 @@ class TestDownloadImage:
assert saved.size == (4, 3)
assert saved.getpixel((0, 0)) == (10, 20, 30)
+ def test_writes_the_downloaded_bytes_without_decoding(self, tmp_path):
+ from unittest import mock
+
+ from kornia.io.sample import download_image
+
+ payload = b"\xff\xd8 bytes that no image decoder accepts"
+ with mock.patch("kornia.io.sample.urlopen") as mock_urlopen:
+ mock_urlopen.return_value.__enter__.return_value.read.return_value = payload
+ dst = tmp_path / "panda.jpg"
+ download_image(self.URL, str(dst))
+ assert dst.read_bytes() == payload
+ assert sorted(p.name for p in tmp_path.iterdir()) == ["panda.jpg"] # no temporary file is left behind
+
+ def test_the_destination_appears_only_once_the_write_is_complete(self, tmp_path):
+ from unittest import mock
+
+ from kornia.io.sample import download_image
+
+ dst = tmp_path / "panda.jpg"
+ writes = []
+
+ def watching_open(path, mode="r", *args, **kwargs):
+ handle = open(path, mode, *args, **kwargs) # noqa: SIM115 - returned to the code under test
+ real_write = handle.write
+
+ def write(data):
+ writes.append((str(path), dst.exists())) # a process killed here must not leave a partial dst
+ return real_write(data)
+
+ handle.write = write
+ return handle
+
+ payload = b"\xff\xd8" + bytes(100)
+ with (
+ mock.patch("kornia.io.sample.urlopen") as mock_urlopen,
+ mock.patch("kornia.io.sample.open", watching_open, create=True),
+ ):
+ mock_urlopen.return_value.__enter__.return_value.read.return_value = payload
+ download_image(self.URL, str(dst))
+ assert len(writes) == 1
+ written, dst_existed = writes[0]
+ assert not dst_existed
+ assert Path(written).parent == tmp_path # a temporary file next to dst, so the final rename is atomic
+ assert Path(written).name.startswith("panda.jpg.")
+ assert written.endswith(".part")
+ assert dst.read_bytes() == payload
+
+ def test_an_interrupted_write_leaves_no_file(self, tmp_path):
+ from unittest import mock
+
+ from kornia.io.sample import download_image
+
+ def failing_open(path, mode="r", *args, **kwargs):
+ handle = open(path, mode, *args, **kwargs) # noqa: SIM115 - returned to the code under test
+ real_write = handle.write
+
+ def write(data):
+ real_write(data[:5]) # part of the body reaches the disk, then the device fills up
+ raise OSError(28, "No space left on device")
+
+ handle.write = write
+ return handle
+
+ dst = tmp_path / "panda.jpg"
+ with (
+ mock.patch("kornia.io.sample.urlopen") as mock_urlopen,
+ mock.patch("kornia.io.sample.open", failing_open, create=True),
+ ):
+ mock_urlopen.return_value.__enter__.return_value.read.return_value = b"\xff\xd8" + bytes(100)
+ with pytest.raises(OSError, match="No space left"):
+ download_image(self.URL, str(dst))
+ assert list(tmp_path.iterdir()) == [] # neither dst nor the temporary file
+
def test_http_error_propagates(self, tmp_path):
import urllib.error
from unittest import mock
diff --git a/tests/models/test_model_base.py b/tests/models/test_model_base.py
index b6be0daed..5e7adb6c3 100644
--- a/tests/models/test_model_base.py
+++ b/tests/models/test_model_base.py
@@ -137,8 +137,8 @@ class TestModelBaseMixinSaveWritesRealFiles:
shipped: the mock accepts any dtype and any rank, so nothing checked that
what the containers hand it is something it can actually write. `visualize`
returns float images and the containers document batched input, and
- `write_image` accepts neither -- PNG is uint8/uint16 only, and the rank has
- to be (3, H, W), (1, H, W) or (H, W).
+ `write_image` accepts neither -- PNG is uint8/uint16 only, and it takes one
+ image: (3, H, W), (1, H, W), (H, W) or, for PNG, (4, H, W).
"""
@pytest.mark.parametrize("dtype", [torch.float32, torch.float64, torch.float16])