Skip to content

pixtreme.io

io

File, bytes, device-array, and wire-format boundaries.

__all__ = ('read_image', 'write_image', 'read_header', 'read_lut', 'decode_lut', 'write_lut', 'decode_image', 'encode_image', 'from_array', 'to_array', 'from_uyvy422', 'to_uyvy422', 'from_v210', 'to_v210', 'from_nv12', 'to_nv12', 'from_p010', 'to_p010', 'from_yuv420p', 'to_yuv420p', 'from_yuv422p', 'to_yuv422p', 'from_yuv444p', 'to_yuv444p', 'from_yuva444p', 'to_yuva444p', 'ImageHeader') module-attribute

ImageHeader

Bases: BaseModel

Describe an image file without decoding its pixels.

Headers produced by read_header carry a format of "PNG", "JPEG", "TIFF", "EXR", "JPEG2000", "WEBP", "BMP", "PNM", "TGA", "HDR", or "DPX", with width and height describing the stored image dimensions. parts contains each part name, a mapping from channel label to stored dtype, and a per-part deep flag. Raster files have one unnamed part, while EXR files may expose multiple parts and use the first part's data window for the dimensions.

color retains the parsed raw color attributes together with any mapped colorspace and gamma tokens and a mappability result. Instances are frozen Pydantic models; validation enforces the field structure and types, not semantic value ranges — the constraints above describe what read_header produces, not what the constructor rejects.

model_config = ConfigDict(frozen=True) class-attribute instance-attribute

format instance-attribute

width instance-attribute

height instance-attribute

parts instance-attribute

color instance-attribute

decode_lut(data)

Decode supported UTF-8 LUT bytes into GPU memory without caching.

Format markers are resolved in SPI3D, SPI1D, Cube, then 3DL specificity order. Headerless 3DL is selected only by its complete numeric structure. A selected parser never falls through. Nonidentity 3DL shapers are baked as the equally sized single-grid approximation documented by :func:read_lut.

read_lut(path)

Read a supported LUT text file into GPU memory without caching.

The extension selects Cube, 3DL, SPI1D, or SPI3D parsing. Cube red-fastest, 3DL blue-fastest, and SPI explicit-index forms normalize to RGB-indexed public values. A nonidentity 3DL shaper is baked onto an equally sized grid; that single-LUT approximation depends on the source edge density and local transform curvature. Parsing performs one bulk host-to-device transfer.

write_lut(path, lut)

Write a finite one- or three-dimensional LUT as deterministic Cube text.

The output always includes the RGB input domain and uses float32 shortest round-trip decimals. The complete table crosses device-to-host once. Parent directories are not created and no cache or ambient registry is consulted.

decode_image(data, *, channels=None, unchanged=False, colorspace=None, gamma=None)

Decode supported raster bytes into an HWC GPU Frame.

data accepts an encoded bytes payload in JPEG, PNG, TIFF, JPEG 2000, WebP, BMP, or PNM format and identifies it from its signature. EXR, TGA, HDR, and DPX are file-only formats. channels accepts a compact string or label sequence and preserves the requested order. unchanged=True preserves a supported native integer depth; the default normalizes ordinary integer storage to float32. Explicit colorspace and gamma metadata claims override embedded metadata and fixed raster defaults without transforming pixel values.

Returns a new C-contiguous HWC GPU Frame with decoded pixels, selected channel labels, and resolved metadata. Unsupported or unidentifiable formats, malformed headers, invalid tokens, and invalid channel selections raise :class:ValueError; codec failures raise :class:RuntimeError.

encode_image(frame, *, format, quality=None, compression=None, compression_level=None, lossless=None)

Encode a Frame as a supported raster byte stream.

format uses the shared case- and separator-insensitive image-format vocabulary. quality applies to JPEG and lossy WebP, compression is TIFF-only with "none"/"lzw", compression_level is PNG-only from 0 through 9, and lossless applies to JPEG 2000 and WebP. JPEG 2000 bytes use a JP2 container. Every format accepts all five Frame storage dtypes; native uint dtypes are preserved and other inputs are meaning-preservingly converted to uint8 on the GPU.

read_image(path, *, channels=None, unchanged=False, colorspace=None, gamma=None)

Decode a supported image file into an HWC GPU Frame.

path selects PNG, JPEG, TIFF, EXR, JPEG 2000, WebP, BMP, PNM, TGA, HDR, or DPX case-insensitively by extension. channels accepts a compact channel string or a sequence of labels and preserves the requested order. With no selection, raster files retain their RGB, RGBA, one-channel Y, or two-channel YA layout; EXR selects unique R, G, B, and an optional A across its parts. Ambiguous EXR labels require part.channel qualification.

The default converts ordinary integer storage, including DPX code values, to normalized float32 and promotes EXR HALF to float32. EXR UINT is instead converted literally to float32 without normalization. unchanged=True preserves uint8, uint16, uint32, float16, or float32 storage where representable, including exact EXR UINT sample bits. HDR is natively decoded to float32, so unchanged=True returns the same values and dtype as its default read. Explicit colorspace and gamma tokens override mapped file metadata, which overrides the fixed sRGB/sRGB raster, ACES2065-1/linear EXR, or Rec.709/linear HDR defaults; these are metadata claims and do not transform pixel values.

Codec-backed raster pixels decode through nvImageCodec into CUDA memory. TGA structure and RLE decode on the CPU before a GPU kernel produces the Frame. HDR likewise parses and expands RGBE scanlines on the CPU, then transfers only flat uint8 RGBE bytes for one-pass GPU ldexp decoding. EXPOSURE, PRIMARIES, and COLORCORR header variables are retained for header inspection but are not applied to pixels or metadata. DPX transfers only raw packed bytes and performs endian resolution, filled unpacking, normalization, and channel selection in one GPU pass. EXR scanline and tiled parts use the source-fixed native, custom-CPU, or GPU codec lane for their compression; multipart and sampled selections are materialized from part-local self-owned decoder views. Encoded bytes use :func:decode_image; EXR, TGA, HDR, and DPX are file-only formats. Missing files raise :class:FileNotFoundError; unsupported extensions, invalid tokens, channel selection, or incompatible unchanged EXR channels raise :class:ValueError; header or codec failures raise :class:RuntimeError.

write_image(path, frame, *, quality=None, compression=None, compression_level=None, lossless=None, dwa_level=None, bit_depth=None, dtype=None)

Write a Frame using the format selected from path's extension.

Every format accepts uint8, uint16, uint32, float16, and float32 Frame storage. Native uint raster dtypes are preserved; other raster inputs are meaning-preservingly converted to uint8 on the GPU. EXR defaults to HALF for every Frame dtype except uint32, which defaults to native UINT. EXR-only dtype may explicitly select "float16", "float32", or "uint32"; conversion follows :func:pixtreme.values.recode_dtype. TGA writes uint8 RLE under the same conversion meaning. HDR uses float32 as its native/default container and writes RGBE new-style RLE. DPX uses float32 as its native/default container and writes uncompressed big-endian data. No colorspace or gamma conversion is performed. Codec-backed raster output validates each format's channel layout and encodes through nvImageCodec from GPU data. EXR accepts unique channel labels, uses the source-fixed CPU/GPU backend table, writes chromaticities derived from frame.colorspace, and marks ACES2065-1 containers.

Metadata persistence is format-bound: raster output writes no public color vocabulary metadata, so frame.colorspace and frame.gamma are not preserved there. EXR persists only the chromaticities and ACES container flag derived from frame.colorspace; frame.gamma is not stored there. HDR writes no EXPOSURE, PRIMARIES, COLORCORR, or public color-vocabulary metadata. DPX records a transfer characteristic derived from frame.gamma.

quality applies to JPEG and lossy WebP and accepts integers 1 through 100. compression selects TIFF "none"/"lzw" or EXR "none", "rle", "zip", "zips", "piz", "pxr24", "b44", "b44a", "dwaa", or "dwab" according to the output format. EXR defaults to "zip". dwa_level applies only to DWAA/DWAB and defaults to 45.0 when omitted. compression_level is PNG-only and accepts integers 0 through 9. lossless applies to JPEG 2000 and WebP. bit_depth applies only to DPX, accepts 8, 10, 12, or 16, and defaults to 10. dtype applies only to EXR and accepts "float16", "float32", "uint32", or None. Successful writes return None.

Unsupported extensions, channel layouts, or encode options raise :class:ValueError. Codec failures and unwritable output paths raise :class:RuntimeError; parent directories are not created. Use :func:encode_image when encoded raster bytes rather than a file are needed.

read_header(path)

Inspect image structure and color attributes without decoding pixels.

path is selected case-insensitively by its supported raster, EXR, HDR, or DPX extension. The returned :class:ImageHeader reports format, dimensions, part names, channel storage dtypes, per-part deep state, and raw plus vocabulary-mapped color metadata. EXR dimensions come from the first part's data window. HDR EXPOSURE, PRIMARIES, and COLORCORR assignments are exposed as raw attributes only; pixel reads do not apply their values. DPX reports its native bit depth, byte order, packing, and mapped transfer.

Header probing imports no pixel codec and creates no CUDA context or GPU allocation. A missing file raises :class:FileNotFoundError, an unsupported extension raises :class:ValueError, and malformed or unreadable header data raises :class:RuntimeError.

from_array(data, *, colorspace, gamma, channels, matrix=None, layout=None, dtype=None, bit_depth=None, scale=None, mean=None, std=None, copy=None)

Construct a Frame from a CuPy array or CUDA DLPack producer.

layout declares HWC, NHWC, CHW, or NCHW input. dtype selects one of the five Frame storage dtypes. The inverse affine formula is x = (y * std + mean) / scale; it round-trips :func:pixtreme.io.to_array with the same scalar or per-channel constants and computes in fp32.

bit_depth selects the 8, 10, 12, 14, or 16-bit unsigned full-scale grid and normalizes a matching uint container by 2^bit_depth - 1 into fp32. It cannot be combined with affine constants; explicit dtype must be "float32".

copy=None retains a zero-copy HWC/NHWC view when possible and otherwise performs one fused copy. copy=False strictly guarantees zero-copy and raises if contiguity, layout, dtype, or affine processing requires a write. copy=True always gives the Frame private storage. Host arrays and CPU DLPack producers are rejected rather than transferred implicitly. matrix stamps YCbCr basis provenance only; it never changes array values, ownership, layout, dtype, or affine processing. DLPack import asks the producer to make its data ready on the current CuPy stream; any repacking kernel is enqueued on that same stream. The function does not perform host synchronization, so direct CuPy inputs must already be ordered for that stream and a different consumer stream must wait on a CUDA event.

to_array(frame, *, channels=None, layout=None, dtype=None, bit_depth=None, scale=None, mean=None, std=None, out=None, copy=None)

Export a Frame to a CuPy device array, optionally in one fused affine pass.

channels selects and orders labels. layout is HWC, NHWC, CHW, or NCHW. The affine formula is y = (x * scale - mean) / std and is the inverse of :func:from_array when the same constants are used. Constants may be scalars or one value per exported channel; arithmetic is fp32 before the faithful dtype cast.

bit_depth selects the 8, 10, 12, 14, or 16-bit unsigned full-scale grid. It clips fp32 values to [0, 1], scales by 2^bit_depth - 1, and rounds half away from zero. The output dtype is uint8 for 8-bit codes and uint16 otherwise. It cannot be combined with affine constants. Use :func:pixtreme.values.quantize when the result should remain a metadata-bearing Frame.

copy=None uses a zero-copy view when possible and otherwise makes one fused copy. copy=False strictly requires zero-copy and raises when repacking is unavoidable. copy=True always returns private storage. With out, copy must be omitted and the destination must be an exactly shaped, exactly typed, C-contiguous cupy.ndarray; the fused pass writes there directly and returns that same object. A non-CuPy DLPack producer is intentionally rejected as a destination; explicitly create a writable view with cp.from_dlpack(tensor) and pass that CuPy array instead.

The returned cupy.ndarray is itself a DLPack producer. Frame is also a DLPack producer through its protocol methods; no to_tensor or to_dlpack helper is needed. Any copy or fused export is enqueued on the current CuPy stream and does not perform host synchronization. Consume the result on that stream, or make another stream wait on an event recorded after this call before it reads the result.

from_nv12(buf, *, width, height, colorspace=None, gamma=None, matrix=None, range='legal', siting='left', interpolation='bilinear')

Construct a full-range fp32 YCbCr444 Frame from uint8 NV12.

The C-contiguous 1D layout is one Y plane followed by an interleaved Cb Cr plane. siting places 4:2:0 chroma at H.273 left, center, or topleft offsets; interpolation evaluates one of the eight resize-family point kernels at that phase with replicate edges. range expands legal code positions without clipping or maps full uint8. colorspace / gamma override placeholders and matrix stamps basis provenance only. The conversion kernel is enqueued on the current CuPy stream and the call does not perform host synchronization. Order the decoder surface onto that stream before calling; a different consumer stream must wait on a CUDA event.

to_nv12(frame, *, range='legal', siting='left', interpolation='area')

Pack frame as an 8-bit Y plane followed by interleaved Cb/Cr.

range selects code-value mapping, siting selects the 4:2:0 chroma phase, and interpolation selects the chroma downsampling filter. Packing is enqueued on the current CuPy stream without host synchronization; consume on that stream or pass its handle/event to the encoder.

from_p010(buf, *, width, height, colorspace=None, gamma=None, matrix=None, range='legal', siting='left', interpolation='bilinear')

Construct a full-range fp32 YCbCr444 Frame from uint16 P010.

The C-contiguous 1D layout is one Y plane followed by interleaved Cb Cr. Each 10-bit code is MSB aligned in uint16; the lower 6 bits are padding and are ignored. siting selects the H.273 4:2:0 phase, interpolation selects one of eight point filters, and range expands legal positions without clipping or maps the full 10-bit domain. colorspace / gamma override placeholders and matrix stamps basis provenance only. The conversion kernel is enqueued on the current CuPy stream and the call does not perform host synchronization. Order the decoder surface onto that stream before calling; a different consumer stream must wait on a CUDA event.

to_p010(frame, *, range='legal', siting='left', interpolation='area')

Pack frame as P010 with 10-bit codes in each uint16 word's MSB.

The lower 6 bits are zero. range selects code-value mapping, siting selects the 4:2:0 chroma phase, and interpolation selects its filter. Packing is enqueued on the current CuPy stream without host synchronization; consume on that stream or pass its handle/event to the encoder.

from_uyvy422(buf, *, width, height, colorspace=None, gamma=None, matrix=None, range='legal', interpolation='bilinear')

Construct a full-range fp32 YCbCr444 Frame from uint8 UYVY422.

The packed order is U0 Y0 V0 Y1. A C-contiguous 1D buffer or NDI-style (H, W, 2) view is accepted; reshape the buffer without a copy when moving between those forms. Horizontal chroma is co-sited at even luma samples and interpolation selects one of the eight point filters. range expands H.273 legal code positions without clipping, or maps the full uint8 container when set to "full". colorspace / gamma override placeholders and matrix stamps basis provenance without changing pixel values.

to_uyvy422(frame, *, range='legal', interpolation='area')

Pack frame as U0 Y0 V0 Y1 bytes in a private 1D array.

The output is the flattened form of an (H, W, 2) uint8 image. range maps normalized YCbCr to full- or legal-range codes, while interpolation selects the horizontal chroma downsampling filter.

from_v210(buf, *, width, height, colorspace=None, gamma=None, matrix=None, range='legal', interpolation='bilinear')

Construct a full-range fp32 YCbCr444 Frame from v210 uint32 words.

Each four-word group stores six horizontally co-sited 10-bit pixels. Every row occupies a 128-byte aligned word span (48-pixel storage units), including the zero-filled padding convention. The input is one C-contiguous 1D uint32 buffer. interpolation upsamples horizontal chroma, and range expands H.273 legal code positions without clipping or maps the full 10-bit domain. colorspace / gamma override placeholders and matrix stamps basis provenance only.

to_v210(frame, *, range='legal', interpolation='area')

Pack frame into little-endian v210 uint32 words.

Each scanline is aligned to a 128-byte boundary and all padding words are zero. range controls code-value mapping and interpolation controls horizontal chroma downsampling.

from_yuv420p(buf, *, width, height, bit_depth=8, colorspace=None, gamma=None, matrix=None, range='legal', siting='left', interpolation='bilinear')

Construct a full-range fp32 YCbCr444 Frame from planar YUV420.

The C-contiguous 1D plane order is Y, Cb, Cr. bit_depth accepts 8 (uint8) or 10 (lower-aligned uint16). siting selects the H.273 left, center, or topleft 4:2:0 phase, and interpolation selects one of eight resize-family point filters with replicate edges. range expands legal positions without clipping or maps the full code domain. colorspace / gamma override placeholders and matrix stamps basis provenance only.

to_yuv420p(frame, *, bit_depth=8, range='legal', siting='left', interpolation='area')

Pack frame as contiguous planar Y, Cb, Cr 4:2:0 samples.

bit_depth chooses the code container, range chooses code-value mapping, siting selects chroma phase, and interpolation selects the chroma downsampling filter.

from_yuv422p(buf, *, width, height, bit_depth=8, colorspace=None, gamma=None, matrix=None, range='legal', interpolation='bilinear')

Construct a full-range fp32 YCbCr444 Frame from planar YUV422.

The C-contiguous 1D plane order is Y, Cb, Cr. bit_depth accepts 8 (uint8), 10, or 12 (lower-aligned uint16). Chroma is horizontally co-sited and vertically full; interpolation applies only on the horizontal axis. range expands H.273 legal positions without clipping or maps the full code domain. colorspace / gamma override placeholders and matrix stamps basis provenance only.

to_yuv422p(frame, *, bit_depth=8, range='legal', interpolation='area')

Pack frame as contiguous planar Y, Cb, Cr 4:2:2 samples.

bit_depth chooses the code container, range chooses code-value mapping, and interpolation selects horizontal chroma downsampling.

from_yuv444p(buf, *, width, height, bit_depth=10, colorspace=None, gamma=None, matrix=None, range='legal')

Construct a full-range fp32 YCbCr444 Frame from planar YUV444.

The C-contiguous 1D plane order is Y, Cb, Cr. bit_depth accepts 10 or 12, stored lower-aligned in uint16. No chroma resampling is performed. range expands H.273 legal positions without clipping or maps the full code domain. colorspace / gamma override placeholders and matrix stamps basis provenance only.

to_yuv444p(frame, *, bit_depth=10, range='legal')

Pack frame as planar Y, Cb, Cr 4:4:4 samples.

Parameters

frame: A float32 Frame with exact ("Y", "Cb", "Cr") channels and positive geometry. No chroma resampling is performed. bit_depth: Stored code depth, either 10 (default) or 12. Codes are lower-aligned in a uint16 container. range: "full" or "legal" YCbCr code mapping. Values are rounded half away from zero and clipped only to the physical container domain, not the legal interval.

Returns

cupy.ndarray A new privately owned C-contiguous 1D uint16 array with shape (H * W * 3,) and plane order Y, Cb, Cr.

Raises

ValueError If frame has the wrong channels or dtype, geometry is invalid, or bit_depth or range is outside its closed domain.

from_yuva444p(buf, *, width, height, bit_depth=12, colorspace=None, gamma=None, matrix=None, range='legal')

Construct a full-range fp32 YCbCrA4444 Frame from planar YUVA444.

The C-contiguous 1D plane order is Y, Cb, Cr, A. bit_depth is 12, stored lower-aligned in uint16. YCbCr follows the selected range without clipping, while A is always decoded against full scale 0...4095. No chroma resampling is performed. colorspace / gamma override placeholders and matrix stamps basis provenance only.

to_yuva444p(frame, *, bit_depth=12, range='legal')

Pack frame as planar Y, Cb, Cr, A 4:4:4:4 samples.

Parameters

frame: A float32 Frame with exact ("Y", "Cb", "Cr", "A") channels and positive geometry. No chroma resampling is performed. bit_depth: Stored code depth, fixed at 12. Codes are lower-aligned in a uint16 container. range: "full" or "legal" YCbCr code mapping. Alpha always maps over full scale. Values are rounded half away from zero and clipped only to the physical container domain, not the legal interval.

Returns

cupy.ndarray A new privately owned C-contiguous 1D uint16 array with shape (H * W * 4,) and plane order Y, Cb, Cr, A.

Raises

ValueError If frame has the wrong channels or dtype, geometry is invalid, or bit_depth or range is outside its closed domain.