Skip to main content

ZX Codec for Python

Install the zx-codec distribution and import zxcodec. It requires Python 3.10 or newer and NumPy 1.24 or newer. The Windows x64 wheel selects baseline or accelerated kernels at runtime according to processor and operating-system support. The Linux x86-64 and ARM64 release wheels target glibc 2.28 or newer.

python -m pip install zx-codec==1.0.1

To install a prebuilt release wheel offline (with numpy>=1.24 already installed or present in the wheel directory):

python -m pip install --no-index --find-links . zx-codec==1.0.1

Legacy code can import pyzx when that name is available. In an environment with the quantum-computing pyzx package in the same installation directory, import pyzx loads the quantum package and import zxcodec loads ZX Codec. In environments with multiple installation directories, Python follows its usual import path order. If an older ZX Codec wheel using the pyzx distribution name is installed, use import zxcodec to select the new implementation.

Prebuilt native wheels for Windows x64, Linux x86-64, Linux ARM64, and macOS Apple Silicon are distributed via PyPI and GitHub Releases (https://github.com/7owel/ZX-Codec/releases). The public GitHub repository distributes the bitstream specifications, conformance test vectors, C++20 strip reference implementation, and FFmpeg bridge under Apache-2.0; the full multicore SIMD production encoder source tree is maintained separately.

import zxcodec as zx

encoded = zx.encode_zxi(rgba16, icc=profile, preset="fast", threads=4)
full = zx.decode_zxi(encoded, threads=4)

with zx.RasterReader("pyramid.zxil") as image:
    first, stats = image.read_tile(511, 519, 1024, 1024, return_stats=True)
    crops = image.read_tiles([(32, 64, 512, 512), (384, 640, 512, 512)])
    thumbnail = image.thumbnail(max_size=256)
    icc = image.read_icc()

planes = zx.read_hdr("workboard.zxf", channels=["Depth", "Flow.X"], threads=4)
sensor = zx.read_raw("camera.zxrw", threads=4)
rgb = zx.read_raw_preview("camera.zxrw", half=True, threads=4)
frame = zx.read_frame("production.zxv1", 13, threads=4)

Raster rectangles are layer-local at the requested pyramid level. Layer and frame indices start at zero. Use layer=None to choose the stored preview when present. HDR returns named, bit-preserving float16, float32 or uint32 planes. RAW reads return the native sensor values or a separate oriented RGB8 development. Video returns a tuple of native planes in the file's pixel-format order, with 10/12-bit samples in little-endian uint16. Returned arrays remain valid after the reader closes. ZVL2 is a lossy edit profile. Its arrays reflect the stored stream.

Pass a path or a C-contiguous byte buffer to RasterReader, read_roi, or HDRReader. The reader holds a borrowed buffer until it closes. Keep mutable sources unchanged during that lifetime. encode_zxi returns a read-only memoryview over the native result. Set as_bytes=True for a detached Python bytes copy. The in-memory ZXI, tiled ZXIL and ZXF read paths use no temporary files. Decoders can allocate destination arrays or fill caller-owned arrays.

With a tiled RasterReader, open_read_bytes reports the native input reads during opening. return_stats=True reports reads for each crop call or the sum for a batch, including reference tile reads when required. These are bytes read from the source abstraction and do not measure physical disk traffic.

Reading from object storage

read_roi, read_hdr and read_video_frame also accept HTTP(S) URLs, fsspec URLs and open, seekable binary streams. The matching readers and raster/HDR batch APIs accept the same sources and can reuse an open reader across requests.

pixels = zx.read_roi(signed_zxi_url, 32, 64, 128, 96)
frame = zx.read_video_frame(signed_video_url, 13, threads=8)

with zx.open_range("s3://bucket/workboard.zxf", storage_options={"anon": True}) as source:
    depth = zx.read_hdr(source, channels="Depth", roi=(32, 64, 128, 96))["Depth"]

For an HTTP(S) object, the reader uses a one-byte probe to obtain the object size, then requests the ranges required by the selected image region, channels, or video frame. It validates 206 Partial Content and the response bounds, rejects 200 OK without reading its body and uses a strong ETag when available to keep reads on the same version. Use a signed URL or pass headers= to open_range() for an authenticated HTTP source. When opened explicitly, the range source exposes .size, .read_at(offset, length) and HTTP .stats. Readable objects must stay open and stable until their ZX reader closes. The caller owns supplied streams and range sources. A supplied seekable stream retains its original position between calls. A custom read_at(offset, length) source can supply its size as an attribute or via open_range(source, size=...).

For s3:// and other fsspec protocols, install fsspec and the appropriate backend, such as s3fs. ZX opens these URLs with the backend's read cache disabled. An already open stream uses the caller's cache settings. A ranged video reader reports frame count, dimensions, bit depth, time base and pixel format. Path-based VideoReader.info also reports the full local metadata.

For frequent selective reads of a ZXF2 image, build its channel companion once at ingest. Save the returned source SHA-256 in the dataset manifest. The reader uses it to check the association without fetching the original.

meta = zx.build_zxf_companion("workboard.zxf", "workboard.range.bin",
                                channels=["Z", "N.X", "N.Y", "N.Z"])
with zx.open_zxf_companion(companion_url, source_digest=meta["source_digest"]) as selected:
    depth = selected.read("Z", threads=4)["Z"]
    transferred = selected.stats["payload_bytes"]

A cold HTTP read of a contiguous group of whole lanes takes four successful range requests, including the one-byte probe. A partial-height ROI fetches only its intersecting stripes in each lane. Selected packet checksums are verified before decoding. Use read_hdr(original, channels=...) for an unindexed channel or an object without a companion. Older version-1 companions support the same read API and omit checksum and source-digest metadata. Supplying source_digest requires a version-2 companion.

Batch destinations

For local ZXV1 files, VideoReader.read_frames(indices, out=..., workers=...) decodes arbitrary indices in order, including repeated frames. For multiple cameras, keep the readers and a reusable pool of 1–32 workers open:

import torch
from zxcodec import VideoBatch, VideoReader

with VideoReader("left.zxv1") as left, VideoReader("right.zxv1") as right:
    with VideoBatch(workers=4) as batch:
        cameras = (left, right)
        rows = [(13, 12), (2, 2), (7, 6)]
        shape, dtype = batch.output_shape(cameras, len(rows) * len(cameras))
        host = torch.empty(shape, dtype=getattr(torch, dtype.name), pin_memory=True)
        batch.read_synchronized(cameras, rows, out=host)
        device = host.to("cuda", non_blocking=True)
        torch.cuda.synchronize()  # Reuse host only after the copy finishes.

Each row supplies a common index or one index per camera. Results follow row order, then camera order. Readers must use the same geometry and pixel format. Equal-sized native planes yield (frames, channels, height, width). Subsampled formats or packed=True yield uint8 rows of length reader.frame_bytes. reader.plane_shapes gives the geometry of each plane.

The decoder fills a contiguous CPU tensor or writable, aligned C-contiguous NumPy array directly. Without out, it allocates a NumPy result. torch.from_dlpack shares this storage on CPU. The separate CUDA upload copies the decoded bytes. Corrupt packets can leave partial output. For remote video, use read_frame. In multi-worker PyTorch DataLoader pipelines, open each VideoReader inside the worker process that reads it.

import numpy as np
import zxcodec as zx

rects = [(32, 64, 128, 96), (384, 640, 128, 96)]
with zx.RasterReader("pyramid.zxil") as image:
    pixels = np.empty((2, 96, 128, 3), dtype=np.uint8)
    assert image.read_tiles(rects, out=pixels) is pixels

depth = np.empty((2, 1, 96, 128), dtype=np.float32)
assert zx.read_hdr_batch(["frame-01.zxf", "frame-02.zxf"], channels="Depth",
                           roi=rects[0], out=depth) is depth

read_raster_batch and read_hdr_batch read one item per source in order. Pass roi= to repeat a rectangle, rois= for one rectangle per source or omit both to read full frames. HDRReader.read_batch(rois) reuses an open source for multiple rectangles. Each dense batch requires matching region dimensions, channels and dtypes. RasterReader.read_tiles(rects) keeps its list result unless out= or an explicit layout= requests a dense batch.

Raster batches write interleaved (B,H,W,C) (layout="BHWC"). A homogeneous HDR selection writes planar (B,C,H,W) (layout="BCHW") in the selected channel order. Either layout spelling works for one channel or one pixel, where the byte order is identical. Other layout requests raise ValueError. Pass {name: array} for mixed HDR, with a separate (B,H,W) array in each channel's stored type. The same name must keep its dtype across sources. The named path issues separate channel reads into those arrays.

Each out array must be writable, aligned, C-contiguous and have the exact shape and dtype. It is returned by identity. The decoder writes its output into each batch slot and uses its usual tile or stripe workspace. If data decoding fails, slots may already contain decoded pixels. NumPy arrays can be borrowed by torch.from_dlpack on CPU without copying their sample data.

import torch

tensor = torch.from_dlpack(depth)
assert tensor.data_ptr() == depth.ctypes.data

For repeated RAW reads, pass a writable array of the same shape and dtype as out=. A RawReader also keeps the file mapping open between reads.

verify(path) runs the native whole-stream validation. An invalid stream raises ZXError when the affected data is read or validated. Missing raster paths also pass through normal Python file I/O errors. These are reader APIs.

ZXI, ZXIL, ZXF and ZX-RAW accept threads=1..64. Use threads=0 to select the available physical CPU concurrency. The thread budget bounds the work for each request. Video reads accept threads=1..32, with 0 selecting one worker. ZX-Photo reads accept threads=0..4. Use a context manager or close() to release an open reader.

Writing arrays

Pass aligned, C-contiguous native-endian NumPy arrays. The writers borrow the input buffers for the call. Keep them stable until the call returns. Use numpy.ascontiguousarray explicitly if a cropped or transposed view needs packing. Convert foreign-endian types explicitly before writing.

zx.write_hdr("scene.zxf", {"Beauty.R": half_plane, "Z": depth_f32, "ID": id_u32})
zx.write_zxi("frame.zxi", rgba16, alpha="straight", icc=profile)
zx.write_zxil("layers.zxil", {"Background": rgb8, "Foreground": rgba16})
zx.write_video("clip.zxv1", timed_frames, width=w, height=h, pix_fmt="yuv422p10le",
                 time_base=(1, 30), color_range="tv")

Each HDR entry is a separate two-dimensional float16, float32 or uint32 array. The Python entry stores a zero-origin data/display window, pLinear=0 and no ancillary EXR attributes. It writes ZXF2 for both homogeneous and mixed input. ZXIL accepts full-canvas, ordered RGB/RGBA layers with uint8, uint16 or float16 samples. Layers use normal blend, full opacity and visible state. Video input uses a contiguous array per frame in native planar order. Items may be (array, PTS, duration), or bare frames with consecutive unit durations. Encoded files use native atomic output staging. The writers invoke no helper process and create no intermediate image or video interchange file.

PyTorch training adapters

Install PyTorch in the training environment. The optional zxcodec.torch_io module imports it when samples are used. NumPy-only decoding keeps its existing dependencies.

Given local camera files and the tabular rows of a LeRobot episode, the three lines below send matching images, states and actions to a CUDA training step. cameras maps names such as front and wrist to local ZXV1 files with planar GBR or BT.709 YUV 4:4:4 (full or limited range) and straight or absent alpha. train_step is your training function.

from zxcodec.torch_io import MultiCameraVideoDataset, PinnedVideoPrefetcher
with MultiCameraVideoDataset.from_lerobot(cameras, rows, episode_index=0, workers=4) as data, PinnedVideoPrefetcher(data, batch_size=8) as batches:
    for batch in batches: train_step(batch)

Use frame_indices= for independent camera frame numbers and frame_offsets= for the start of each episode in a shared camera file. Pass a PyTorch batch sampler to PinnedVideoPrefetcher(data, batches=sampler) to choose random rows. For CPU training pass the dataset to torch.utils.data.DataLoader.

Verification and public resources

To verify an installed wheel locally against the public conformance verifier from https://github.com/7owel/ZX-Codec:

# Windows x64 / Linux x86-64:
python -B samples/verify_installed_wheel.py 1.0.1 x64
# Linux ARM64 / macOS Apple Silicon:
python -B samples/verify_installed_wheel.py 1.0.1 arm64
  • Documentation & Benchmarks: https://github.com/7owel/ZX-Codec/blob/v1.0.1/docs/BENCHMARKS.md
  • Distribution & Licensing Terms: https://github.com/7owel/ZX-Codec/blob/v1.0.1/docs/distribution.md
  • Interactive Browser Workbench: https://7owel.github.io/ZX-Codec/demo/

Metadata

Release files for zx-codec 1.0.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Built distributions (wheels)

Table of built distributions (wheels) for zx-codec 1.0.1
File Actions
zx_codec-1.0.1-py3-none-win_amd64.whl Python 3 none Windows x86-64 Details for zx_codec-1.0.1-py3-none-win_amd64.whl
zx_codec-1.0.1-py3-none-manylinux_2_28_x86_64.whl Python 3 none Linux glibc 2.28+ x86-64 Details for zx_codec-1.0.1-py3-none-manylinux_2_28_x86_64.whl
zx_codec-1.0.1-py3-none-manylinux_2_28_aarch64.whl Python 3 none Linux glibc 2.28+ ARM64 Details for zx_codec-1.0.1-py3-none-manylinux_2_28_aarch64.whl
zx_codec-1.0.1-py3-none-macosx_11_0_arm64.whl Python 3 none macOS 11.0+ ARM64 Details for zx_codec-1.0.1-py3-none-macosx_11_0_arm64.whl

Total release size: 10.3 MB

Release files / zx_codec-1.0.1-py3-none-win_amd64.whl

Download URL zx_codec-1.0.1-py3-none-win_amd64.whl
Size 3.3 MB
Tags Python 3 Windows x86-64
SHA-256 checksum
How to use checksums
bce22aefac0031a93f8c8ec8220173c417143cf1037f6d4e69725cae6b85a3a4
BLAKE2b-256 checksum
How to use checksums
73db185a4f7dcd5da9be9d81e17b2d9e0c24604b260607fc395ac845f5d5d5ad
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.12.13

Release files / zx_codec-1.0.1-py3-none-manylinux_2_28_x86_64.whl

Download URL zx_codec-1.0.1-py3-none-manylinux_2_28_x86_64.whl
Size 4.3 MB
Tags Linux glibc 2.28+ x86-64 Python 3
SHA-256 checksum
How to use checksums
185ce3cc7af007a2f82c49b173fbe3603e7da7f64848d05902381f604ddafe08
BLAKE2b-256 checksum
How to use checksums
9987bc5b9094d2403f5e84f94bd40b6d05617dc36d5f45160b43d26edd38ec34
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.12.13

Release files / zx_codec-1.0.1-py3-none-manylinux_2_28_aarch64.whl

Download URL zx_codec-1.0.1-py3-none-manylinux_2_28_aarch64.whl
Size 1.6 MB
Tags Linux glibc 2.28+ ARM64 Python 3
SHA-256 checksum
How to use checksums
2f5f87af4a291f63b7ea88f3ebd75fd0272642d3ac1dedfce8acc30b0beb7c72
BLAKE2b-256 checksum
How to use checksums
fb076bc90a3799d915f5e4fb97b2cff564f4091a5b799d36bca4ff2c46880af3
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.12.13

Release files / zx_codec-1.0.1-py3-none-macosx_11_0_arm64.whl

Download URL zx_codec-1.0.1-py3-none-macosx_11_0_arm64.whl
Size 1.1 MB
Tags Python 3 macOS 11.0+ ARM64
SHA-256 checksum
How to use checksums
d37bc7777b132f4a4a7beb05b4205603a9e5f974da4bbe2a02680a544e0d7d92
BLAKE2b-256 checksum
How to use checksums
933664d8d2be87e35c2877759f890c7fc69c22ee229fb4282678906b31b9a4de
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.12.13

Security for zx-codec 1.0.1

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

1.0.1 This release

4 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page