kornia.io#
Package to load and save image data directly as tensors.
The package is backed by kornia-rs, a low-level computer vision
library written in Rust that is installed automatically as a dependency of
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.
import torch
import kornia as K
from kornia.io import ImageLoadType
file_path = "image.jpg"
img = K.io.load_image(file_path, ImageLoadType.UNCHANGED, device="cuda")
# (C, H, W) in the file's original dtype and channel count, on "cuda"
img = K.io.load_image(file_path, ImageLoadType.RGB8, device="cpu")
# (3, H, W) torch.uint8 in [0, 255], on "cpu"
img = K.io.load_image(file_path, ImageLoadType.GRAY8, device="cuda")
# (1, H, W) torch.uint8 in [0, 255], on "cuda"
img = K.io.load_image(file_path, ImageLoadType.GRAY32, device="cpu")
# (1, H, W) torch.float32 in [0, 1], on "cpu"
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).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].
Files and arrays tabulates the load types and the formats write_image() takes,
and maps OpenCV’s and Pillow’s readers and writers onto them.
- kornia.io.load_image(path_file, desired_type=ImageLoadType.RGB32, device='cpu')[source]#
Read an image file and decode using the Kornia Rust backend.
- Convention:
desired_typefixes the channels, the dtype and the range, whatever the file holds:GRAY8,RGB8andRGBA8give 1, 3 and 4uint8channels in [0, 255], andGRAY32andRGB32(the default) 1 and 3float32channels in [0, 1].UNCHANGEDkeeps the file’s channels and dtype, so a 16-bit PNG or TIFF loads asuint16and a float TIFF asfloat32; 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 PNGtRNSchunk counts as alpha; palette entries the chunk does not list, all of them for an empty chunk, are opaque.RGBA8keeps the alpha (255 for an opaque file), and the other types composite it over white, rounded to the nearest level.UNCHANGEDreturns a palette PNG’s indices and keeps an alpha channel as stored.GRAY8andGRAY32convert a colour file withrgb_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 orPLTE/tRNSchunk raiseValueError.Files and arrays maps OpenCV’s and Pillow’s loaders onto the load types.
- Parameters:
path_file (
str|Path) – 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 (
ImageLoadType, optional) – the desired image type, defined by color space and dtype. Default:ImageLoadType.RGB32device (
Union[str,device,None], optional) – the device where you want to get your image placed. Default:"cpu"
- Return type:
- Returns:
Image torch.Tensor with shape \((C, H, W)\).
- Raises:
TypeCheckError – if
desired_typeis not anImageLoadType(also aTypeError).OSError – if the file cannot be read, for example
FileNotFoundErrorwhen it does not exist.ValueError – if the file cannot be decoded; the message names the file.
NotImplementedError – if a type other than
UNCHANGEDis requested for a file wider than 8 bits.
- kornia.io.write_image(path_file, image, quality=80)[source]#
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, PNGuint8anduint16, and TIFFuint8,uint16andfloat32; 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
float32TIFF keeps values outside [0, 1].imageis channels first. A channels-last \((H, W, C)\) tensor is not detected: its first axis is read as the channels.Files and arrays maps
cv2.imwriteonto these arguments.Known defect: an image with zero height or width reaches kornia-rs, which raises a bare
Exceptionand leaves an empty or truncated file behind (#5770).
- Parameters:
path_file (
str|Path) – Path with a .jpg, .jpeg, .png, .tif or .tiff extension, in any letter case.image (
Tensor) – Image torch.Tensor with shape \((C, H, W)\) or \((H, W)\).quality (
int, optional) – The quality of the JPEG encoding, an integer in [0, 100] and not abool. It is validated for every format and used only for JPEG. Default:80
- Return type:
- Returns:
None.
- Raises:
TypeCheckError – if
imageis not a tensor orqualityis not an integer (also aTypeError).ValueCheckError – if
qualityis outside [0, 100] (also aValueError).BaseError – if the extension is not one of the five above.
ShapeError – if
imageis not 2-D or 3-D, or the format cannot store its channels (also aValueError).FileNotFoundError – if the directory to write into does not exist (
NotADirectoryErrorif it is a file).NotImplementedError – if the format cannot store the dtype.
Exception – kornia-rs’s bare
Exceptionwhen the file cannot be created or the image cannot be encoded.
- kornia.io.get_sample_images(resize=None, paths=_IMAGE_URLS, download=True, cache_dir=None, as_list=None, divisible_factor=None, **kwargs)[source]#
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.
- Convention:
Each image loads with
load_image()’s default type,RGB32: \((3, H, W)\)float32in [0, 1].A path is a URL only when its scheme is
httporhttps. A URL is cached undercache_dirwith the file name of its path, byte for byte as downloaded, and a cached file is loaded without downloading it again. Withdownload=False, a URL that is not cached logs an error and raisesFileNotFoundError. A download fails once the server goesKORNIA_DOWNLOAD_TIMEOUTseconds (30 s when it is unset) without answering, and an unusable value of that variable raisesValueError.resizeis(height, width)and goes toresize();divisible_factoris applied after it byresize_to_be_divisible(), so the final size can differ fromresize.**kwargsreach both.The result is one \((B, 3, H, W)\) tensor when
resizeis given andas_listis notTrue, and a list of \((3, H, W)\) tensors otherwise;as_list=Falsewithoutresizestill gives a list.
- Parameters:
paths (
List[str], optional) – A list of path or URL from which to load or download images. Defaults to the pre-defined sample image URLs if not provided. Default:_IMAGE_URLSresize (
Optional[Tuple[int,int]], optional) – Optional target size(height, width)for every image. If not provided, the images keep their sizes unlessdivisible_factoris given. Default:Nonedownload (
bool, optional) – Whether to download the images if they are not already cached. Defaults to True. Default:Truecache_dir (
Optional[str], optional) – 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. Default:Noneas_list (
Optional[bool], optional) –Trueto return a list even whenresizeis given. Default:Nonedivisible_factor (
Optional[int], optional) – If not None, each side of every image is resized to a multiple ofdivisible_factor. Default:None**kwargs (
Any) – Additional keyword arguments for both resizes.
- Returns:
the images, stacked or as a list.
- Return type: