czifile¶
Read Carl Zeiss image files (CZI).
Czifile is a Python library for reading image data and metadata from Carl Zeiss Image (CZI) files, the native file format of ZEN by Carl Zeiss Microscopy GmbH.
Czifile is a pure-Python library under the BSD-3-Clause license. It provides single-call array access to scenes and spatial ROIs, xarray DataArray output with physical axis coordinates, multi-scene merging, per-dimension selection by integer, slice, or sequence, chunk-based iteration, and pyramid-level access. It handles Fast Airyscan upsampling and PALM downsampling with optional stored-resolution output, and assembles FCS and line-scan files from T-chunked subblocks. It also supports Zstd and JPEG XR compression, pixel type promotion across channels, and direct access to all ZISRAW segments and file-level attachments.
- Author:
- License:
BSD-3-Clause
- Version:
2026.4.30
- DOI:
Quickstart¶
Install the czifile package and all dependencies from the Python Package Index:
python -m pip install -U czifile[all]
See Examples for using the programming interface.
Source code, examples, and support are available on GitHub.
Requirements¶
This revision was tested with the following requirements and dependencies (other versions may work):
CPython 3.12.10, 3.13.13, 3.14.4 64-bit
NumPy 2.4.4
Imagecodecs 2026.3.6
Xarray 2026.4.0 (recommended)
Matplotlib 3.10.9 (optional)
Tifffile 2026.4.11 (optional)
Revisions¶
2026.4.30
Omit axes from coords when no meaningful metadata is available (breaking).
Return coords[‘T’] as float seconds instead of datetime64 (breaking).
Replace pixel_series with coord_scales in CziImage.attrs (breaking).
Add coord_offsets, coord_scales, coord_units, and mpp properties to CziImage.
Add datetime property to CziImage returning acquisition start as datetime64.
Drop support for numpy 2.0 (SPEC0).
2026.4.11
Fall back to parsing numeric channel names as float coords[‘C’].
2026.3.17
Add cache for decoded subblock arrays.
Prefer imagecodecs’ WIC over JPEGXR codec if available.
Import imagecodecs functions on demand.
2026.3.15
Replace CziImagePlanes with CziImageChunks (breaking).
Add CziImage.chunks method for flexible chunk-based iteration.
Add CziFile.metadata_segment property.
Add offset properties to CziAttachmentEntryA1 and subblock entry classes.
Add CziSegmentId.packed property returning the 16-byte on-disk field.
Manage update_pending flag in CziFile context manager for writable handles.
Improve documentation.
2026.3.14
Add option to return pixel data at stored resolution.
Allow sequence and slice of scene indices in imread and asarray/asxarray.
Interpret dimension slice selection as absolute coordinates.
Add command line options to select dimensions.
2026.3.12
Rewrite with many breaking changes.
Support Zstd compression schemes.
Support reading subblock masks.
Add CziFile.scenes interface.
Add pyramid level access via CziImage.levels.
Add option to read subset of image data.
Add option to iterate over image planes in any dimension order.
Add xarray-style attributes.
Add asxarray method to return image as xarray DataArray with metadata.
Add fillvalue and maxworkers parameters to asarray.
Add option to specify pixel type.
Promote pixel type when channels have mixed types.
Remove Mosaic dimension from CziDirectoryEntryDV.dims; use mosaic_index.
Reduce caching of CziDirectoryEntryDV properties.
Remove resize and order parameters from asarray (breaking).
Remove czi2tif function and command line script.
Prefix public class names with Czi.
Raise CziFileError for issues with CZI file structure.
Use logging instead of warnings.
Improve representation of instances.
Add pytest-based unit tests.
Add type hints.
Convert docstrings to Google style with Sphinx directives.
Remove imagecodecs-lite fallback; require imagecodecs.
Remove scipy/ndimage dependency.
Make tifffile an optional dependency.
Drop support for Python < 3.12 and numpy < 2 (SPEC 0).
2019.7.2.3
…
Refer to the CHANGES file for older revisions.
Notes¶
The API is not stable yet and might change between revisions.
Carl Zeiss AG is a manufacturer of microscopes and scientific instruments. CZI is a proprietary file format written by Zeiss acquisition software such as ZEN to store microscopy images and metadata.
CZI files are based on the ZISRAW (Zeiss Image Segment Raw) container specification, which is confidential and does not permit writing CZI files:
ZISRAW (CZI) File Format Design Specification Release Version 1.2.2.“CZI 07-2016/CZI-DOC ZEN 2.3/DS_ZISRAW-FileFormat.pdf”
The ZISRAW format organizes data into typed, length-prefixed segments: a file header, image subblocks, XML metadata, and attachments. Each image subblock carries pixels for one tile or Z-plane across up to ten logical dimensions (X, Y, Z, channel, time, scene, phase, illumination, rotation, and mosaic index). Pixel data may be stored uncompressed or compressed with JPEG, JPEG XR, or Zstd.
Only a subset of the 2016 specification is implemented. Specifically, multi-file images and topography images are not supported. Some features are untested due to lack of sample files.
Czifile relies on the imagecodecs package for decoding LZW, Zstd, JPEG, and JPEG XR compressed images.
Other libraries for reading CZI files (all GPL or LGPL licensed): libczi, pylibCZIrw, bioio-czi, bio-formats, libCZI (deprecated), and pylibczi (deprecated).
Examples¶
Read image data of the first scene from a CZI file as numpy array:
>>> arr = imread('Example.czi')
>>> assert arr.shape == (2, 2, 3, 486, 1178)
>>> assert arr.dtype == 'uint16'
Access scenes, shape, and metadata:
>>> with CziFile('Example.czi') as czi:
... assert len(czi.scenes) == 3
... img = czi.scenes[0] # 0 is the absolute coordinate of the first scene
... assert img.shape == (2, 2, 3, 486, 1178)
... assert img.dims == ('T', 'C', 'Z', 'Y', 'X')
... assert img.dtype == 'uint16'
... assert img.compression.name == 'ZSTDHDR'
... assert list(img.channels) == ['DAPI', 'EGFP']
... assert czi.metadata().startswith('<ImageDocument>')
...
Select dimensions and read as numpy array:
>>> with CziFile('Example.czi') as czi:
... img = czi.scenes[0]
... assert img.sizes == {'T': 2, 'C': 2, 'Z': 3, 'Y': 486, 'X': 1178}
...
... # integer selection: fix T=0 and C=0; result has Z, but no T or C axis
... volume = img(T=0, C=0).asarray()
... assert volume.shape == (3, 486, 1178)
...
... # None selection: keep all values but reorder dimensions
... # dims order follows the kwargs order, then spatial dims
... # T (unspecified) comes first, then C, Z (in kwargs order), then Y X
... tczyx = img(C=None, Z=None).asarray()
... assert tczyx.shape == (2, 2, 3, 486, 1178)
...
... # read in C-outer, Z-inner, T-innermost order with parallelism
... arr = img(C=None, Z=None, T=None).asarray(maxworkers=8)
... assert arr.shape == (2, 3, 2, 486, 1178) # 'C', 'Z', 'T', 'Y', 'X'
...
... # img.bbox gives (x, y, width, height) in global CZI coordinates
... x0, y0, *_ = img.bbox
... plane_roi = img(T=0, C=0, roi=(x0, y0, 128, 128)).asarray()
... assert plane_roi.shape == (3, 128, 128) # 'Z', 'Y', 'X'
...
... # fill pixels outside subblock coverage with a specific value
... padded = img(C=0, roi=(0, 0, 2048, 2048)).asarray(fillvalue=0)
... assert padded.shape == (2, 3, 2048, 2048) # 'T', 'Z', 'Y', 'X'
...
Iterate image chunks:
>>> with CziFile('Example.czi') as czi:
... img = czi.scenes[0]
...
... # iterate individual Y/X planes as CziImage views
... # by default, all non-spatial dims are iterated one-at-a-time
... for chunk in img.chunks():
... assert isinstance(chunk, CziImage)
... assert chunk.asarray().shape == (486, 1178)
...
... # keep C in each chunk: iterate T and Z only
... for chunk in img.chunks(C=None):
... assert chunk.asarray().shape == (2, 486, 1178)
...
... # batch Z into groups of 3; last chunk may be smaller if Z indivisible
... for chunk in img.chunks(Z=3):
... assert chunk.sizes['Z'] <= 3
...
... # spatial tiling: iterate T x C x Z x grid
... for chunk in img.chunks(Y=256, X=256):
... assert chunk.shape[-2] <= 256
... assert chunk.shape[-1] <= 256
...
... # keep C, tile spatially
... for chunk in img.chunks(C=None, Y=256, X=256):
... assert chunk.dims[0] == 'C'
...
Read image as xarray DataArray with physical coordinates and attributes:
>>> with CziFile('Example.czi') as czi:
... xarr = czi.scenes[0].asxarray()
... assert xarr.name == 'Scene 0'
... assert xarr.sizes == {'T': 2, 'C': 2, 'Z': 3, 'Y': 486, 'X': 1178}
... assert xarr.coords['X'].size == 1178 # physical axis coordinates
...
Access multiple scenes:
>>> with CziFile('Example.czi') as czi:
... # iterate scenes individually and read as arrays
... for img in czi.scenes.values():
... arr = img.asarray()
...
... # query which scenes (indices) are available
... assert list(czi.scenes.keys()) == [0, 1, 2]
...
... # select the second scene
... assert czi.scenes[1].sizes == {
... 'T': 2,
... 'C': 2,
... 'Z': 3,
... 'Y': 256,
... 'X': 256,
... }
...
... # merge selected scenes into one
... img = czi.scenes(scene=[0, 1]) # first 2 scenes
... assert img.sizes == {'T': 2, 'C': 2, 'Z': 3, 'Y': 1109, 'X': 1760}
...
... # merge all scenes into one
... img = czi.scenes()
... assert img.sizes == {'T': 2, 'C': 2, 'Z': 3, 'Y': 2055, 'X': 2581}
...
Access pyramid levels:
>>> with CziFile('Example.czi') as czi:
... img = czi.scenes[0]
... assert img.is_pyramid
... assert len(img.levels) == 2 # full resolution + 1 downsampled level
... assert img.levels[0] is img # full resolution level is the same as img
... overview = img.levels[1] # lowest-res level
... assert overview.sizes == {'T': 2, 'C': 2, 'Z': 3, 'Y': 243, 'X': 589}
...
Access attachments:
>>> with CziFile('Example.czi') as czi:
... for attachment in czi.attachments():
... name = attachment.attachment_entry.name
... data = attachment.data() # decoded (ndarray, tuple, bytes...)
... raw = attachment.data(raw=True) # bytes; may be written to file
...
... # convenience shortcut for TimeStamps attachment data
... assert czi.timestamps.shape == (2,)
...
Low-level access to CZI file segments:
>>> with CziFile('Example.czi') as czi:
... # file header: version, GUIDs, and segment offsets
... hdr = czi.header
... assert hdr.version == (1, 0)
... assert str(hdr.file_guid) == 'f8a61493-053e-c94e-bae0-bc7e96d18997'
... assert not hdr.update_pending
...
... # iterate all subblock segments sequentially via the directory
... for segdata in czi.subblocks():
... entry = segdata.directory_entry
... assert entry.dims == ('H', 'T', 'C', 'Z', 'Y', 'X', 'S')
... assert entry.start == (0, 0, 0, 0, 0, 582, 0)
... assert entry.shape == (1, 1, 1, 1, 486, 1178, 1)
... assert entry.stored_shape == (1, 1, 1, 1, 243, 589, 1)
... assert entry.compression == CziCompressionType.ZSTDHDR
... assert segdata.data_offset == 661865 # offset of image data
... assert segdata.data_size == 183875 # size of compressed image data
... tile = segdata.data() # decompressed image data as numpy array
... assert tile.shape == entry.stored_shape
... assert tile.dtype == entry.pixel_type.dtype
... assert isinstance(segdata.data(raw=True), bytes) # compressed data
... assert segdata.metadata().startswith('<METADATA>')
... break # just the first subblock segment for demonstration
...
... # iterate only image tiles in a selected image view
... img = czi.scenes[0](T=0, C=0, Z=0)
... for entry in img.directory_entries:
... segdata = entry.read_segment_data(czi)
... assert isinstance(segdata, CziSubBlockSegmentData)
... tile = segdata.data()
... assert tile.shape == entry.stored_shape
... break # just the first filtered directory entry
...
... # walk all file segments by type using their ZISRAW segment IDs
... for segdata in czi.segments(CziSegmentId.ZISRAWSUBBLOCK):
... assert isinstance(segdata, CziSubBlockSegmentData)
...
... # direct low-level segment header at a known file offset
... seg = CziSegment(czi, czi.header.directory_position)
... assert seg.sid == CziSegmentId.ZISRAWDIRECTORY
... assert seg.used_size == 68768
... seg_data = seg.data()
... assert isinstance(seg_data, CziSubBlockDirectorySegmentData)
...
View the images and metadata in a CZI file from the console:
$ python -m czifile Example.czi
License¶
Copyright (c) 2013-2026, Christoph Gohlke
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
czifile module¶
- czifile.__version__ = '2026.4.30'¶
Czifile version string.
- class czifile.CziAttachmentDirectorySegmentData(segment, /)¶
Bases:
CziSegmentDataZISRAWATTDIR segment data. Sequence of CziAttachmentEntryA1.
- Parameters:
segment (CziSegment) – Associated segment.
- SID: str = 'ZISRAWATTDIR'¶
CziSegment identifier.
- __init__(segment, /)¶
- Parameters:
segment (CziSegment)
- Return type:
None
- entries: tuple[CziAttachmentEntryA1, ...]¶
Sequence of attachment entries.
- static file_positions(fh, /)¶
Return file positions of associated attachment segments.
Lightweight alternative to full parsing: reads only the file offsets without constructing
CziAttachmentEntryA1objects. Useful for recovery or when only segment locations are needed.- Parameters:
fh (IO[bytes]) – File handle to read from.
- Return type:
tuple[int, …]
- property segment: CziSegment¶
Parent segment associated with data.
- __str__()¶
Return str(self).
- Return type:
str
- class czifile.CziAttachmentEntryA1(fh, /)¶
Bases:
objectAttachmentEntry - Schema A1.
Part of
CziAttachmentSegmentDataandCziAttachmentDirectorySegmentData.- Parameters:
fh (IO[bytes]) – File handle to read from.
- __init__(fh, /)¶
- Parameters:
fh (IO[bytes])
- Return type:
None
- offset: int¶
Position of attachment entry in file.
- file_position: int¶
Position of associated
CziAttachmentSegmentDatain file.
- file_part: int¶
Part number in multi-file scenarios.
- content_guid: UUID¶
Unique identifier used in references.
- content_file_type: CziContentFileType¶
Content file identifier.
- name: str¶
Name of attachment.
- static read_file_position(fh, /)¶
Return position of associated
CziAttachmentSegmentData.- Parameters:
fh (IO[bytes]) – File handle to read from.
- Return type:
int
- property schema_type: str¶
Attachment entry schema type.
- property filename: str¶
Unique file name for saving attachment.
- property name_offset: int¶
Position of name field in file (80 bytes, zero-padded).
- read_segment_data(czifile, /)¶
Return associated attachment segment data from file.
- Parameters:
czifile (CziFile) – CZI file to read from.
- Return type:
- __repr__()¶
Return repr(self).
- Return type:
str
- __str__()¶
Return str(self).
- Return type:
str
- class czifile.CziAttachmentSegmentData(segment, /)¶
Bases:
CziSegmentDataZISRAWATTACH segment data.
Contains binary or text data as specified in
attachment_entry.- Parameters:
segment (CziSegment) – Associated segment.
- SID: str = 'ZISRAWATTACH'¶
CziSegment identifier.
- __init__(segment, /)¶
- Parameters:
segment (CziSegment)
- Return type:
None
- data_size: int¶
Size of data section.
- attachment_entry: CziAttachmentEntryA1¶
Core information about attachment.
- data_offset: int¶
Position of attachment embedded in file.
- property segment: CziSegment¶
Parent segment associated with data.
- save(filename=None, directory='.')¶
Write attachment to file.
- Parameters:
filename (str | os.PathLike[Any] | None) – Name of file to save attachment. Defaults to
CziAttachmentEntryA1.filename().directory (str | os.PathLike[Any]) – Directory for attachment. Defaults to current directory.
- Return type:
None
- data(*, raw: Literal[True]) bytes¶
- data(*, raw: Literal[False] = False) Any
- data(*, raw: bool) Any
Return content of embedded attachment.
- Parameters:
raw (bool) – If true, return contents as bytes, else return decoded contents according to
CziContentFileType.read_content.- Return type:
Any
- __str__()¶
Return str(self).
- Return type:
str
- class czifile.CziCompressionType(*values)¶
Bases:
IntEnumPixel data compression type.
- __format__(format_spec, /)¶
Convert to a string according to format_spec.
- __new_member__(value, /)¶
Create enum member.
- Parameters:
value (int)
- Return type:
Self
- UNKNOWN = -1¶
Unknown compression type.
- UNCOMPRESSED = 0¶
No compression.
- JPEG = 1¶
JPEG lossy.
- LZW = 2¶
Lempel-Ziv-Welch.
- JPEGLL = 3¶
JPEG lossless (undocumented).
- JPEGXR = 4¶
JPEG XR.
- ZSTD = 5¶
ZStandard.
- ZSTDHDR = 6¶
ZStandard with header and shuffle filter.
- CAMERARAW = 100¶
Camera specific RAW data.
- SYSTEMRAW = 1000¶
System specific RAW data.
- __new__(value)¶
- __str__()¶
Return repr(self).
- Return type:
str
- static decoder(value, /)¶
Return decoder function for compression type value.
Resolved lazily on first call per value and cached. For JPEG XR (value 4), prefers WIC on Windows when available and falls back to
imagecodecs.jpegxr_decode()otherwise.- Parameters:
value (int) – Integer compression type value.
- Returns:
Decoder callable, or
Noneif no decoder is needed.- Return type:
Callable[…, Any] | None
- class czifile.CziContentFileType(*values)¶
Bases:
StrEnumAttachment file type identifier.
- __format__(format_spec, /)¶
Return a formatted version of the string as described by format_spec.
- __str__()¶
Return str(self).
- __new_member__(value, read_content=read_bytes)¶
Create enum member with associated attachment-content reader.
- Parameters:
value (str)
read_content (Callable[..., Any])
- Return type:
Self
- UNKNOWN = ''¶
Unknown attachment type.
- BINARY = 'BINARY'¶
Binary attachment type.
- CZI = 'CZI'¶
Embedded CZI file containing slide label, preview or pre-scan image.
- ZISRAW = 'ZISRAW'¶
Embedded CZI file.
- CZTIMS = 'CZTIMS'¶
Time stamps. Unit depends on producing CZI writer.
- CZEVL = 'CZEVL'¶
Events reported during timeseries.
- CZLUT = 'CZLUT'¶
Color lookup tables.
- CZFOC = 'CZFOC'¶
Focus positions relative to acquisition start.
- CZEXP = 'CZEXP'¶
Experiment definitions (XML).
- CZHWS = 'CZHWS'¶
HardwareSetting used to record image (XML).
- CZMVM = 'CZMVM'¶
MultiviewMicroscopy information (XML).
- CZFBMX = 'CZFBMX'¶
FiberMatrix (XML).
- CZPML = 'CZPML'¶
PalMoleculeList information (undocumented).
- ZIP = 'ZIP'¶
ZIP compressed attachment.
- ZIP_COMP = 'Zip-Comp'¶
ZIP compressed XML.
- JPG = 'JPG'¶
JPEG compressed thumbnail or preview image.
- read_content: Callable[..., Any]¶
Callable that decodes attachment content for this file type.
- __new__(value)¶
- class czifile.CziDeletedSegmentData(segment, /)¶
Bases:
CziSegmentDataDELETED segment data. Ignore.
- Parameters:
segment (CziSegment) – Associated segment.
- SID: str = 'DELETED'¶
CziSegment identifier.
- __init__(segment, /)¶
- Parameters:
segment (CziSegment)
- Return type:
None
- property segment: CziSegment¶
Parent segment associated with data.
- __str__()¶
Return str(self).
- Return type:
str
- class czifile.CziDimensionEntryDV1(data, /)¶
Bases:
objectDimension Entry - Schema DV.
- Parameters:
data (bytes) – Byte stream of dimension entry.
- __init__(data, /)¶
- Parameters:
data (bytes)
- Return type:
None
- start: int¶
Start index. May be < 0.
- size: int¶
Logical size of dimension.
- start_coordinate: float¶
Physical start coordinate.
- stored_size: int¶
Stored size if sub or supersampling, else 0.
- dimension: CziDimensionType¶
Single character code identifying dimension.
- property schema_type: str¶
Dimension entry schema type.
- __repr__()¶
Return repr(self).
- Return type:
str
- __str__()¶
Return str(self).
- Return type:
str
- class czifile.CziDimensionType(*values)¶
Bases:
StrEnumSingle character code identifying dimension in pixel and metadata.
- __new__(value)¶
- __format__(format_spec, /)¶
Return a formatted version of the string as described by format_spec.
- __str__()¶
Return str(self).
- UNKNOWN = 'Q'¶
Unknown dimension.
- WIDTH = 'X'¶
Pixel index in X direction used for tiled images.
- HEIGHT = 'Y'¶
Pixel index in Y direction used for tiled images.
- DEPTH = 'Z'¶
Slice index in Z direction.
- CHANNEL = 'C'¶
Channel in multi-channel data set.
- TIME = 'T'¶
Sequentially acquired series of data.
- ROTATION = 'R'¶
Data is recorded from various angles.
- SCENE = 'S'¶
Cluster index contiguous region in mosaic image.
- ILLUMINATION = 'I'¶
Illumination direction index.
- BLOCK = 'B'¶
Acquisition block index in segmented experiments.
- MOSAIC = 'M'¶
Mosaic tile index identifying all tiles in specific plane.
- PHASE = 'H'¶
Phase index for specific acquisition methods.
- VIEW = 'V'¶
View index for multi-view images such as SPIM.
- class czifile.CziDirectoryEntryDV(fh, /)¶
Bases:
objectDirectory Entry - Schema DV [Directory Variable length].
Image subset indices and size information.
- Parameters:
fh (IO[bytes]) – File handle to read from.
- __init__(fh, /)¶
- Parameters:
fh (IO[bytes])
- Return type:
None
- offset: int¶
Position of directory entry in file.
- file_position: int¶
Position of associated subblock segment in file.
- file_part: int¶
Part number in multi-file scenarios.
- dimensions_count: int¶
Number of dimension entries.
- pixel_type: CziPixelType¶
Type of pixel data.
- compression: CziCompressionType¶
Type of pixel data compression.
- pyramid_type: CziPyramidType¶
Type of image pyramid.
- decode: Callable[..., Any] | None¶
Decoder function for pixel data, or None if uncompressed.
- mosaic_index: int¶
Mosaic tile index, -1 if undefined.
- scene_index: int¶
CziScene index, -1 if undefined.
- dims: tuple[str, ...]¶
Dimension names, excluding mosaic and scene.
- shape: tuple[int, ...]¶
Logical size of dimensions, excluding mosaic and scene.
- start: tuple[int, ...]¶
Start indices of dimensions, excluding mosaic and scene.
- stop: tuple[int, ...]¶
Upper indices of dimensions, excluding mosaic and scene.
- stored_shape: tuple[int, ...]¶
Stored size of dimensions, excluding mosaic and scene.
- is_pyramid: bool¶
Pixel data is sub- or supersampled along some dimensions.
- static read_file_position(fh, /)¶
Return position of associated
CziSubBlockSegmentData.- Parameters:
fh (IO[bytes]) – File handle to read from.
- Return type:
int
- property start_coordinate: tuple[float, ...]¶
Physical start coordinate of dimension, excluding mosaic and scene.
Values preserve the original float32 precision from the file.
- property schema_type: str¶
Directory entry schema type.
- property storage_size: int¶
Number of bytes used to store CziDirectoryEntryDV.
- property subblock_entry_offset: int¶
Position of inline directory entry within associated subblock.
Allows accessing dimension start values without going through the SubBlockDirectory.
- property dtype: dtype¶
Numpy data type of pixel type.
- property ndim: int¶
Number of dimensions, excluding mosaic and scene.
- property size: int¶
Number of items in array described by dimensions.
- property scale: tuple[float, ...]¶
Sub / supersampling factors.
- read_dimension_entries(fh, /)¶
Return all dimension entries from file, including M and S.
Unlike the constructor, iterates forward and includes every dimension without filtering, keyed by
CziDimensionType.- Parameters:
fh (IO[bytes]) – File handle to read from.
- Return type:
- read_segment_data(czifile, /)¶
Return associated subblock segment data from file.
- Parameters:
czifile (CziFile) – CZI file to read from.
- Return type:
- __repr__()¶
Return repr(self).
- Return type:
str
- __str__()¶
Return str(self).
- Return type:
str
- class czifile.CziEventListEntry(fh, /)¶
Bases:
objectCziEventListEntry content schema.
- Parameters:
fh (IO[bytes]) – File handle to read from.
- __init__(fh, /)¶
- Parameters:
fh (IO[bytes])
- Return type:
None
- time: float¶
Time of event in seconds relative to controller start time.
- description: str¶
Description of event.
- event_type: CziEventType¶
Type of event.
- __repr__()¶
Return repr(self).
- Return type:
str
- __str__()¶
Return str(self).
- Return type:
str
- class czifile.CziEventType(*values)¶
Bases:
IntEnumType of CziEventListEntry (EV_TYPE).
- __format__(format_spec, /)¶
Convert to a string according to format_spec.
- __new__(value)¶
- UNKNOWN = -1¶
Unknown event type.
- MARKER = 0¶
Experimental annotation.
- TIMER_CHANGE = 1¶
Time interval changed.
- BLEACH_START = 2¶
Start of bleach operation.
- BLEACH_STOP = 3¶
Stop of bleach operation.
- TRIGGER = 4¶
Trigger signal detected on user port of electronic module.
- final class czifile.CziFile(file, /, *, mode=None, squeeze=True)¶
Bases:
BinaryFileRead image and metadata from Carl Zeiss Image (CZI) file.
CziFile instances must be closed with
CziFile.close(), which is automatically called when using the ‘with’ context manager.CziFile instances are not thread-safe. All attributes are read-only.
- Parameters:
file (str | os.PathLike[Any] | IO[bytes]) – CZI file to read. Open file objects must be positioned at CZI header.
mode (Literal['r', 'r+', 'rb', 'r+b'] | None) – File open mode if
fileis file name. Defaults to'r'.squeeze (bool) – If True, remove dimensions of length 1 from results.
- Raises:
CziFileError – File is not a valid ZISRAW file.
Notes
Opening a file with
mode='r+'enables in-place modification viafilehandle. When used as a context manager, theupdate_pendingflag in the file header is automatically set on entry and cleared on clean exit. It remains set if an exception occurs, triggering a warning on the next open.- __init__(file, /, *, mode=None, squeeze=True)¶
- Parameters:
file (str | os.PathLike[Any] | IO[bytes])
mode (Literal['r', 'r+', 'rb', 'r+b'] | None)
squeeze (bool)
- Return type:
None
- header: CziFileHeaderSegmentData¶
Global file metadata such as file version and GUID.
- property maxcache: int | None¶
Maximum number of decoded subblock arrays to cache.
None(default) enables automatic cache management:CziImage.chunks()activates a scoped cache when spatial tiling is requested and leaves it disabled otherwise.0explicitly disables caching for all operations. Positive integer sets a persistent FIFO cache of that size. Cache is keyed by file offset and uses FIFO eviction. Caching is only applied to compressed subblocks.
- segments(kind=None, /)¶
Return iterator over segment data of specified kind.
- Parameters:
kind (str | Sequence[str] | None) – CziSegment identifier or sequence of identifiers to match. By default, all segments are returned.
- Return type:
Generator[CziSegmentData]
- metadata(*, asdict: Literal[False] = False) str¶
- metadata(*, asdict: Literal[True]) dict[str, Any]
- metadata(*, asdict: bool) str | dict[str, Any]
Return data of CziMetadataSegmentData from file.
Return an empty string, or
{}whenasdict=True, if no CziMetadataSegmentData is found.- Parameters:
asdict (bool) – Return metadata as dict instead of XML.
- Return type:
str | dict[str, Any]
- property xml_element: Element | None¶
Parsed XML root element of CZI metadata, or
None.
- property metadata_segment: CziMetadataSegmentData | None¶
Metadata segment data, or
Noneif not found.
- property subblock_directory: tuple[CziDirectoryEntryDV, ...]¶
All directory entries in file.
Uses subblock directory segment if available, else searches for subblock segments in file.
- property filtered_subblock_directory: tuple[CziDirectoryEntryDV, ...]¶
Directory entries filtered to pyramid level 0.
Entries with a mosaic index are sorted by mosaic index so that tiles with higher M-index are composited on top.
- property attachment_directory: tuple[CziAttachmentEntryA1, ...]¶
All attachment entries in file.
Uses attachment directory segment if available, else searches for attachment segments in file.
- subblocks()¶
Yield all subblock segment data in file.
- Return type:
Generator[CziSubBlockSegmentData]
- attachments()¶
Yield all attachment segment data in file.
- Return type:
Generator[CziAttachmentSegmentData]
- save_attachments(directory=None)¶
Save all attachments to files.
- Parameters:
directory (str | os.PathLike[Any] | None)
- Return type:
None
- property timestamps: NDArray[Any] | None¶
Timestamps from TimeStamps attachment, or
None.Values are float64. The unit depends on the CZI producer: some files store seconds relative to the start of acquisition, others store OLE Automation Dates (days since 1899-12-30).
- asarray(*, scene=FIRST_SCENE, roi=None, pixeltype=None, fillvalue=0, storedsize=False, maxworkers=None, out=None, **selection)¶
Return image data from file as numpy array.
- Parameters:
scene (SelectionValue) – Absolute S-coordinate(s) of scene(s) to read. Defaults to the first available scene. An
intselects a single scene by its S-coordinate. Asliceselects scenes whose S-coordinate falls within the range defined by the slice. A sequence ofintmerges the specified scenes into one array. IfNone, read all scenes merged into one array. Useczi.scenes.keys()to enumerate valid values.roi (tuple[int, int, int, int] | None) – Spatial region of interest in absolute pixel coordinates
(x, y, width, height). IfNone, read the entire image.pixeltype (CziPixelType | None) – Output pixel type. If
None, use the pixel type of the image. When specified, tiles are converted during compositing.fillvalue (ArrayLike | None) – Value for pixels not covered by any subblock.
storedsize (bool) – Return pixel data at stored resolution. Skip resampling of Airyscan and PALM tiles.
maxworkers (int | None) – Maximum number of threads to decode subblock data. By default, up to half the CPU cores are used.
out (OutputType) – Output destination for image data. If
None, create a new NumPy array in main memory. If'memmap', create a memory-mapped array in a temporary file. If anumpy.ndarray, a writable, initialized array of compatible shape and dtype. If afile nameoropen file, create a memory-mapped array in the specified file.**selection (SelectionValue) – Dimension selections forwarded to
CziImage.__call__().
- Return type:
NDArray[Any]
- asxarray(*, scene=FIRST_SCENE, roi=None, pixeltype=None, fillvalue=0, storedsize=False, maxworkers=None, out=None, **selection)¶
Return image data from file as xarray DataArray.
- Parameters:
scene (SelectionValue) – Absolute S-coordinate(s) of scene(s) to read. Defaults to the first available scene. An
intselects a single scene by its S-coordinate. Asliceselects scenes whose S-coordinate falls within the range defined by the slice. A sequence ofintmerges the specified scenes into one DataArray. IfNone, read all scenes merged into one DataArray.roi (tuple[int, int, int, int] | None) – Spatial region of interest in absolute pixel coordinates
(x, y, width, height). IfNone, read the entire image.pixeltype (CziPixelType | None) – Output pixel type. If
None, use the pixel type of the image. When specified, tiles are converted during compositing.fillvalue (ArrayLike | None) – Value for pixels not covered by any subblock.
storedsize (bool) – Return pixel data at stored resolution. Skip resampling of Airyscan and PALM tiles.
maxworkers (int | None) – Maximum number of threads to decode subblock data. By default, up to half the CPU cores are used.
out (OutputType) – Output destination for backing NumPy array. If
None, create a new NumPy array in main memory. If'memmap', create a memory-mapped array in a temporary file. If anumpy.ndarray, a writable, initialized array of compatible shape and dtype. If afile nameoropen file, create a memory-mapped array in the specified file.**selection (SelectionValue) – Dimension selections forwarded to
CziImage.__call__().
- Return type:
DataArray
- __repr__()¶
Return repr(self).
- Return type:
str
- __str__()¶
Return str(self).
- Return type:
str
- class czifile.CziFileError¶
Bases:
ValueErrorException to indicate invalid CZI file structure.
- __weakref__¶
list of weak references to the object
- class czifile.CziFileHeaderSegmentData(segment, /)¶
Bases:
CziSegmentDataZISRAWFILE file header segment data.
Contains global file metadata such as file version and GUID.
- Parameters:
segment (CziSegment) – Associated segment.
- SID: str = 'ZISRAWFILE'¶
CziSegment identifier.
- __init__(segment, /)¶
- Parameters:
segment (CziSegment)
- Return type:
None
- file_part: int¶
Part number in multi-file scenarios.
- directory_position: int¶
Position of subblock directory segment in file.
- metadata_position: int¶
Position of metadata segment in file.
- attachment_directory_position: int¶
Position of attachment directory segment in file.
- version: tuple[int, int]¶
Major and minor file version.
- update_pending: bool¶
File has inconsistent state.
- primary_file_guid: UUID¶
Globally unique identifier of main file.
- file_guid: UUID¶
Globally unique identifier of file.
- property segment: CziSegment¶
Parent segment associated with data.
- __str__()¶
Return str(self).
- Return type:
str
- class czifile.CziImage(parent, directory_entries, /, *, name='', squeeze=True, roi=None, pixeltype=None, storedsize=False, selection=None)¶
Bases:
objectFiltered view of image data in a CZI file.
A CziImage represents a subset of subblock directory entries, filtered by scene, dimension selection, or pyramid level.
All attributes are read-only.
- Parameters:
parent (CziFile) – CziFile instance providing file access.
directory_entries (tuple[CziDirectoryEntryDV, ...]) – Subblock directory entries for this image view.
name (str) – Display name incorporating scene and selection info.
squeeze (bool) – If true, remove dimensions of length 1 from results.
roi (tuple[int, int, int, int] | None) – Spatial region of interest in absolute pixel coordinates
(x, y, width, height). IfNone, use the full extent.pixeltype (CziPixelType | None) – Output pixel type override. If
None, the pixel type is taken from the first directory entry. When set,dtype,shape, andasarray()all reflect the requested type.storedsize (bool) – If true, return pixel data at the stored resolution instead of resampling to the logical size. Airyscan sub-sampled tiles are returned at their smaller stored size; PALM super-resolution tiles at their larger stored size. Raises
ValueErrorwhen subblocks have non-uniform stored-to-logical ratios (apply a dimension selection first to make ratios uniform).selection (dict[str, SelectionValue] | None) – Dimension selections as mapping of dimension name to
int,slice,Sequence[int], orNone.
Notes
All coordinates are absolute (CZI file-level), not relative to a scene or subblock. This follows the ZISRAW specification and the behaviour of the libczi reference implementation. This applies consistently across the API:
Dimension selection (
**kwargstoCziImage.__call__()): an integer value such asT=0orC=1selects subblocks whose file-level start coordinate for that dimension equals the given value. If the file’s T axis starts at 5, useT=5to select the first time point -T=0would match nothing. ASequence[int]selects subblocks whose coordinate equals any of the given absolute values. Asliceselects subblocks whose coordinate falls within the range defined by the slice start/stop/step, all interpreted as absolute coordinate values (not positional offsets).ValueErroris raised if the selection matches no subblocks. The dimensionsX,Y, andS(color samples) are excluded from**selection: useroifor spatial cropping andCziScenes(CziFile.scenes) for scene selection.Dimension ordering: the output axis order follows three groups: (1) unspecified non-spatial dimensions, in their original file order; (2) explicitly specified dimensions (including
None), in the order they appear as keyword arguments; (3) spatial dimensions (Y, X, S), always last. Dimensions selected with an integer are collapsed and absent from the output. UseCziImage.dimsorCziImage.sizesto read back the resulting order.ROI (
roiparameter):(x, y, width, height)are global pixel coordinates, matching the values inCziImage.bboxandCziImage.start.Squeeze and size-1 dimensions: when
squeeze=True(the default), dimensions of length 1 are removed fromCziImage.dims,CziImage.start, and theCziImageChunksiteration axes. Disable squeeze withCziFile(file, squeeze=False)to access all coordinate axes unconditionally.Scene access (
CziScenes): scene selection uses the absolute S-coordinate, consistent with all other dimension access. Here, S-coordinate refers to scene indices, not the sample dimensionS.czi.scenes[4]selects the scene whose S-coordinate is 4 in the file.KeyErroris raised for an unknown S-coordinate.czi.scenes(scene=slice(2, 5))returns a merged image of all scenes whose S-coordinate falls inrange(2, 5). S-coordinates within the range that are absent from the file are silently skipped, andKeyErroris raised only when the range is entirely empty. Useczi.scenes.keys()to enumerate valid S-coordinate keys.scene_indiceson aCziImagereturns the S-coordinate(s) as a sorted tuple:(4,)for a single scene,(0, 1)for a merged two-scene image, orNonefor files without an explicit S dimension. Roundtrip:czi.scenes(scene=image.scene_indices)reconstructs the same image.- __init__(parent, directory_entries, /, *, name='', squeeze=True, roi=None, pixeltype=None, storedsize=False, selection=None)¶
- Parameters:
parent (CziFile)
directory_entries (tuple[CziDirectoryEntryDV, ...])
name (str)
squeeze (bool)
roi (tuple[int, int, int, int] | None)
pixeltype (CziPixelType | None)
storedsize (bool)
selection (dict[str, SelectionValue] | None)
- Return type:
None
- __call__(*, roi=None, pixeltype=None, storedsize=None, **selection)¶
Return new CziImage with dimension selection and/or ROI.
- Parameters:
roi (tuple[int, int, int, int] | None) – Spatial region of interest in absolute pixel coordinates
(x, y, width, height).pixeltype (CziPixelType | None) – Output pixel type override. If
None, inherit any existing override from this image.storedsize (bool | None) – Return pixel data at stored resolution without resampling. If
None, inherit from parent image.**selection (SelectionValue) –
Dimension selections. Keys are dimension names (single uppercase characters, excluding X/Y/S). Values can be
int(single index),slice(range),Sequence[int](specific indices), orNone(all values; use for dimension ordering only). All values are absolute CZI file-level coordinates.Output dimension order is determined as follows: (1) unspecified non-spatial dimensions, in file order; (2) specified dimensions, in the order they appear as keyword arguments; (3) spatial dimensions (Y, X, and optionally S), always last. Dimensions selected with an
intare collapsed and do not appear in the output shape.
- Raises:
TypeError – If this CziImage already has a ROI applied, or if a dimension selection is requested on an image that already has a dimension selection or ROI applied. Applying a ROI to an image that already has a dimension selection is permitted (one level of chaining only):
img(C=0)(roi=...)works, but further calls on the result always raiseTypeError.ValueError – If roi width or height is not positive, or if a dimension name is unknown or spatial.
- Return type:
Example:
# img.dims = ('T', 'C', 'Z', 'Y', 'X') # fix C=1: result has dims ('T', 'Z', 'Y', 'X') sub = img(C=1) # reorder to Z-outer, T-inner; result has dims ('Z', 'T', 'Y', 'X') sub = img(Z=None, T=None) # combine: fix T to first time-point, then reorder C outer Z inner # all coordinate values are absolute CZI file-level indices sub = img(T=0, C=None, Z=None) # dims: ('C', 'Z', 'Y', 'X') # crop to a 256x256 ROI (absolute pixel coordinates) x0, y0, *_ = img.bbox sub = img(C=0, roi=(x0, y0, 256, 256))
- property name: str¶
Display name of image incorporating scene and selection info.
- property compression: CziCompressionType¶
Compression type of image.
- property scene_indices: tuple[int, ...] | None¶
Absolute S-coordinates of this image’s scene(s), or None.
Return a sorted tuple of S-coordinate values as stored in the CZI file - the same values used as keys in
CziScenes.Single scene at S=2:
(2,)Merged scenes S=0 and S=1:
(0, 1)All merged scenes: sorted S-coordinate values present in the image, for example
(2, 4, 7)File with no explicit S dimension (implicit):
None
Roundtrip:
czi.scenes(scene=image.scene_indices)reproduces this image. ReturnNonefor implicit single-scene files.
- property pixeltype: CziPixelType¶
Pixel type of image data.
Return the explicit override if one was provided, otherwise the best common type across all channels.
- property dtype: numpy.dtype[Any]¶
NumPy data type of image.
- property sizes: Mapping[str, int]¶
Ordered mapping of dimension name to length.
- property shape: tuple[int, ...]¶
Shape of image.
- property dims: tuple[str, ...]¶
Dimension names of image.
- property axes: str¶
Character codes for each dimension in image.
- property ndim: int¶
Number of image dimensions.
- property nbytes: int¶
Number of bytes consumed by image.
- property size: int¶
Number of elements in image.
- property start: tuple[int, ...]¶
Minimum start indices per dimension.
- property bbox: tuple[int, int, int, int]¶
Spatial bounding box in absolute pixel coordinates.
- Returns:
Bounding box as
(x, y, width, height).
- property coords: Mapping[str, NDArray[Any]]¶
Mapping of dimension names to physical coordinate arrays.
Only dimensions with meaningful physical coordinates are included. Dimensions without metadata (integer-index-only) are absent.
Spatial dimensions (X, Y, Z) use pixel spacing in meters from CZI scaling metadata.
T uses elapsed seconds from interval metadata when available, or the TimeStamps attachment as fallback. See
datetimefor the acquisition wall-clock time. When T comes from the TimeStamps attachment only (no interval metadata), it is absent fromcoord_offsets,coord_scales, andcoord_units.C uses the midpoint of
DetectionWavelengthin nanometres fromchannelswhen that field is present for every channel in the slice and the ranges are mutually non-overlapping (narrow spectral bins, for example LSM980 spectral imaging). When the ranges overlap, channel names are used instead. WhenDetectionWavelengthis absent, channel names are used; if all names parse as floats (for example, wavelengths encoded as names like'480'), a float array is returned.S (color samples) return
['Red', 'Green', 'Blue']for RGB images and['Red', 'Green', 'Blue', 'Alpha']for RGBA images. Absent for grayscale images (S squeezed away or S=1).
- property coord_offsets: dict[str, float]¶
Coordinate offsets (first pixel position) per axis.
Map dimension character codes to the coordinate value of the first pixel. Only axes with numeric coordinates are included. Values are always float.
- property coord_scales: dict[str, float]¶
Coordinate step sizes per axis.
Map dimension character codes to the spacing between consecutive coordinate values. Only axes with numeric, regularly spaced coordinates are included. For non-spatial axes (T, C), axes with fewer than two elements are excluded because the step cannot be determined.
- property coord_units: dict[str, str]¶
Coordinate unit strings per axis.
Map dimension character codes to their full name unit string. Only axes with numeric coordinates are included.
- property mpp: tuple[float, float] | None¶
Pixel spacing in micrometer as (mpp-x, mpp-y), or None.
- property datetime: datetime64 | None¶
Acquisition start datetime from file metadata, or None.
Parsed from the
AcquisitionDateAndTimeXML field. Timezone information is stripped before parsing. Return None when the field is absent, contains the zero sentinel (0001-01-01T00:00:00), or cannot be parsed.
- property channels: Mapping[str, dict[str, Any]]¶
Per-channel metadata keyed by channel name.
Return a dict keyed by channel name (falling back to channel Id when no name is available).
Each value is a dict whose keys are XML tag names from the ZISRAW
Channelelement (ExcitationWavelength,DetectionWavelength,Fluor,AcquisitionMode, etc.) plus display-setting fields (DyeName,DyeMaxExcitation,DyeMaxEmission,ShortName,Color).DetectionWavelengthis a(lo, hi)float tuple when the XML encodes a range, or a scalar float for single-value elements.
- property objective: Mapping[str, Any]¶
Objective lens metadata keyed by XML tag name.
Return a dict containing a subset of the Objective XML element tags defined in the ZISRAW specification.
- property attrs: Mapping[str, Any]¶
Image metadata as dict.
- property directory_entries: tuple[CziDirectoryEntryDV, ...]¶
Filtered directory entries for this image view.
- property is_pyramid: bool¶
Image has multiple pyramid levels.
- property is_pyramid_level: bool¶
Image is downsampled pyramid overview.
- property is_upsampled: bool¶
Subblocks are stored sub-sampled and expanded on read (Airyscan).
- property is_downsampled: bool¶
Subblocks are stored above logical resolution (PALM).
- property storedsize: bool¶
Return pixel data at stored resolution without resampling.
- asarray(*, fillvalue=0, maxworkers=None, out=None)¶
Return image data from file as numpy array.
- Parameters:
fillvalue (ArrayLike | None) – Value for pixels not covered by any subblock.
maxworkers (int | None) – Maximum number of threads to decode subblock data. By default, up to half the CPU cores are used.
out (OutputType) – Output destination for image data. If
None, create a new NumPy array in main memory. If'memmap', create a memory-mapped array in a temporary file. If anumpy.ndarray, a writable, initialized array of compatible shape and dtype. If afile nameoropen file, create a memory-mapped array in the specified file.
- Return type:
NDArray[Any]
- asxarray(**kwargs)¶
Return image data as xarray DataArray.
- Parameters:
**kwargs (Any) – Keyword arguments forwarded to
asarray():fillvalue,maxworkers, andout.- Return type:
DataArray
- chunks(*, squeeze=True, maxcache=None, **sizes)¶
Return image chunks as CziImage views.
Each chunk is a
CziImagewith the full API includingasarray(),asxarray(),bbox,dims,sizes, and__call__().- Parameters:
squeeze (bool) – Whether to drop size-1 dimensions from each chunk. When
False, size-1 axes such as the single T or Z index per chunk are retained indimsandshape.maxcache (int | None) – Number of decoded subblock arrays to cache during iteration. Only active when
CziFile.maxcacheisNone(auto mode, the default).None(default) auto-detects: computes how many subblocks can overlap one grid tile ((floor((tile_x-2)/sub_w)+2) * (floor((tile_y-2)/sub_h)+2) * layers), wherelayersis the product of any non-spatial dimensions specified insizes, using their batch size or full axis size forNone; capped at the subblock count and 64; 0 when no spatial tiling is requested. Pass 0 to disable caching, or an explicit positive integer to set the temporary FIFO cache size for this iteration.**sizes (int | None) –
Chunk size specification as keyword arguments. Keys are dimension names, values control behavior:
Absent non-spatial dimension: iterated one-at-a-time.
Absent spatial dimension (Y, X): kept in full.
Nonevalue: full axis kept in each chunk.intvalue: axis batched into groups of that size. For spatial dimensions, this produces a tiling grid.
- Return type:
Notes
With no size arguments, non-spatial dimensions of length > 1 are iterated one-at-a-time (equivalent to plane-by-plane iteration). Dimensions of length 1 are skipped when the parent image uses squeeze (the default).
squeezecontrols only how each chunk presents its dimensions: size-1 axes are dropped whenTrue(default) and retained whenFalse.Example:
# iterate individual Y/X planes for chunk in img.chunks(): process(chunk.asarray()) # keep C in each chunk, iterate T and Z for chunk in img.chunks(C=None): assert 'C' in chunk.dims # batch Z into groups of 10 for chunk in img.chunks(Z=10): arr = chunk.asarray() # spatial tiling: 512x512 tiles for chunk in img.chunks(Y=512, X=512): tile = chunk.asarray()
For bulk reads, use
CziImage.asarray()directly, which is faster as it composites all tiles in a single parallel pass.
- __repr__()¶
Return repr(self).
- Return type:
str
- __weakref__¶
list of weak references to the object
- final class czifile.CziImageChunks(image, sizes=None, /, *, squeeze=True, maxcache=None)¶
Bases:
objectLazy container of image chunks from a CziImage.
Each chunk is a
CziImageview covering a subset of the parent image’s dimensions. Keyword arguments toCziImage.chunks()control which dimensions are iterated and how they are batched.With no keyword arguments, non-spatial dimensions of length > 1 are iterated one-at-a-time, producing individual Y/X planes. Dimensions of length 1 are skipped when the parent image uses squeeze (the default).
squeezecontrols only how each chunk presents its dimensions: size-1 axes are dropped whenTrue(default) and retained whenFalse. Spatial dimensions (Y, X) are always kept in full unless explicitly tiled with anintvalue.- Parameters:
image (CziImage) – Source CziImage.
sizes (dict[str, int | None] | None) –
Chunk size specification as mapping of dimension name to
intorNone. Values control behavior:Absent non-spatial dimension: iterated one-at-a-time.
Absent spatial dimension (Y, X): kept in full.
Nonevalue: full axis kept in each chunk.intvalue: axis batched into groups of that size. For spatial dimensions, this produces a tiling grid.
squeeze (bool) – Whether to drop size-1 dimensions from each chunk.
maxcache (int | None) – Maximum number of decoded subblock arrays to cache during iteration.
None(default) auto-detects: computes how many subblocks can overlap one grid tile ((floor((tile_x-2)/sub_w)+2) * (floor((tile_y-2)/sub_h)+2) * layers), wherelayersis the product of any non-spatial dimensions specified insizes, using their batch size or full axis size forNone; capped at the subblock count and 64; 0 when no spatial tiling.0disables caching. Positive integer sets an explicit limit. Only active whenCziFile.maxcacheisNone(auto mode, the default). The cache is set on the parentCziFilefor the duration of iteration and restored on exit.
- __init__(image, sizes=None, /, *, squeeze=True, maxcache=None)¶
- Parameters:
image (CziImage)
sizes (dict[str, int | None] | None)
squeeze (bool)
maxcache (int | None)
- Return type:
None
- __len__()¶
Number of chunks.
- Return type:
int
- __repr__()¶
Return repr(self).
- Return type:
str
- __weakref__¶
list of weak references to the object
- class czifile.CziMetadataSegmentData(segment, /)¶
Bases:
CziSegmentDataZISRAWMETADATA segment data.
Contains global image metadata in UTF-8 encoded XML format.
- Parameters:
segment (CziSegment) – Associated segment.
- SID: str = 'ZISRAWMETADATA'¶
CziSegment identifier.
- __init__(segment, /)¶
- Parameters:
segment (CziSegment)
- Return type:
None
- xml_size: int¶
Size of XML data.
- attachment_size: int¶
Size of binary attachments (unused).
- xml_offset: int¶
Position of XML metadata in file.
- property segment: CziSegment¶
Parent segment associated with data.
- data()¶
Read and return XML metadata payload.
- Return type:
str
- __str__()¶
Return str(self).
- Return type:
str
- class czifile.CziPixelType(*values)¶
Bases:
IntEnumType of pixel data.
- __format__(format_spec, /)¶
Convert to a string according to format_spec.
- __new_member__(value, dtype='u1', samples=1, /)¶
Create enum member with associated numpy dtype and sample count.
- Parameters:
value (int)
dtype (str)
samples (int)
- Return type:
Self
- UNKNOWN = -1¶
Unknown pixel type.
- GRAY8 = 0¶
8-bit unsigned integer.
- GRAY16 = 1¶
16-bit unsigned integer.
- GRAY32FLOAT = 2¶
32-bit floating point.
- BGR24 = 3¶
8-bit unsigned integers for Blue, Green, Red color samples.
- BGR48 = 4¶
16-bit unsigned integers for Blue, Green, Red color samples.
- BGR96FLOAT = 8¶
32-bit floating points for Blue, Green, Red color samples.
- BGRA32 = 9¶
8-bit unsigned integers for Blue, Green, Red, Alpha color samples.
- GRAY64COMPLEXFLOAT = 10¶
64-bit complex number.
- BGR192COMPLEXFLOAT = 11¶
64-bit complex numbers for Blue, Green, Red color samples.
- GRAY32 = 12¶
32-bit signed integer.
- GRAY64 = 13¶
64-bit floating point.
- dtype: numpy.dtype[Any]¶
Numpy data type of pixel type.
- samples: int¶
Number of samples in pixel type.
- __new__(value)¶
- static get(dtype, samples)¶
Return pixel type matching dtype and samples.
- Parameters:
dtype (DTypeLike)
samples (int)
- Return type:
- class czifile.CziPyramidType(*values)¶
Bases:
IntEnumImage pyramid type using SubBlocks of different resolution.
The use of these values is undocumented.
- __format__(format_spec, /)¶
Convert to a string according to format_spec.
- __new__(value)¶
- UNKNOWN = -1¶
Unknown pyramid type.
- NONE = 0¶
Not pyramidal.
- SINGLE_SUBBLOCK = 1¶
Single subblock pyramid.
- MULTI_SUBBLOCK = 2¶
Multi subblock pyramid.
- class czifile.CziScenes(parent, /, *, squeeze=True)¶
Bases:
Mapping[int,CziImage]Mapping of scene S-coordinates to
CziImageinstances.Keys are the absolute S-coordinate values stored in the CZI file. For files that have no explicit scene (S) dimension, the single implicit scene is exposed under the synthetic key
0.Full
collections.abc.Mappinginterface is provided:scenes[s] # CziImage for scene S=s s in scenes # True when S=s is a valid key len(scenes) # number of scenes scenes.keys() # S-coordinate values (ascending) scenes.values() # CziImage instances in key order scenes.items() # (S-coordinate, CziImage) pairs
Use the call syntax to obtain a merged
CziImagespanning all or a selection of scenes:scenes() # all scenes merged into one CziImage scenes(scene=0) # scene with S-coordinate 0 scenes(scene=[0, 2]) # scenes S=0 and S=2 merged
The first scene (lowest S-coordinate) is conveniently accessed as:
next(iter(scenes.values()))
- Parameters:
parent (CziFile)
squeeze (bool)
- __call__(*, scene=None, roi=None, **selection)¶
Return CziImage for one or multiple scenes merged.
- Parameters:
scene (SelectionValue) – Absolute S-coordinate(s) of scene(s) to select.
Nonemerges all scenes into oneCziImage.intselects a single scene by its S-coordinate.sliceselects scenes whose S-coordinate falls within the range defined by the slice (absolute S-coordinates), consistent withintselection.Sequence[int]selects and merges specific scenes. For files without an explicit S dimension, use0(orNone).roi (tuple[int, int, int, int] | None) – Spatial region of interest in absolute pixel coordinates
(x, y, width, height). Applied to the resulting CziImage.**selection (SelectionValue) – Dimension selections forwarded to
CziImage.__call__().
- Raises:
KeyError – If a requested scene key is not present in the file.
- Return type:
- __getitem__(key, /)¶
Return CziImage for scene with S-coordinate key.
- Raises:
KeyError – If key is not a valid scene S-coordinate.
- Parameters:
key (int)
- Return type:
- __iter__()¶
Iterate over scene S-coordinate keys in ascending order.
- Return type:
Iterator[int]
- __len__()¶
Number of scenes.
- Return type:
int
- __repr__()¶
Return repr(self).
- Return type:
str
- __str__()¶
Return str(self).
- Return type:
str
- class czifile.CziSegment(czifile, offset=None, /)¶
Bases:
objectZISRAW segment.
- Parameters:
czifile (CziFile) – CZI file to read from.
offset (int) – Position of segment in file. If
None, use current file position.
- __init__(czifile, offset=None, /)¶
- Parameters:
czifile (CziFile)
offset (int | None)
- Return type:
None
- offset: int¶
Position of segment in file.
- allocated_size: int¶
Number of bytes allocated for segment.
- sid: CziSegmentId¶
CziSegment identifier.
- used_size: int¶
Currently used number of bytes for segment.
- property filehandle: IO[bytes]¶
File handle.
- property data_offset: int¶
Position of segment data in file.
- data()¶
Read and return segment payload.
- Return type:
- __repr__()¶
Return repr(self).
- Return type:
str
- __str__()¶
Return str(self).
- Return type:
str
- class czifile.CziSegmentData(segment, /)¶
Bases:
objectAbstract base class for segment data.
- Parameters:
segment (CziSegment)
- SID: str¶
CziSegment identifier.
- abstractmethod __init__(segment, /)¶
- Parameters:
segment (CziSegment)
- Return type:
None
- abstract property segment: CziSegment¶
Parent segment associated with data.
- __repr__()¶
Return repr(self).
- Return type:
str
- __weakref__¶
list of weak references to the object
- class czifile.CziSegmentId(*values)¶
Bases:
StrEnumCziSegment identifier.
- __format__(format_spec, /)¶
Return a formatted version of the string as described by format_spec.
- __str__()¶
Return str(self).
- __new_member__(value, read_segment_data=CziUnknownSegmentData)¶
Create enum member with associated segment-data reader.
- Parameters:
value (str)
read_segment_data (Callable[[CziSegment], CziSegmentData])
- Return type:
Self
- UNKNOWN = ''¶
Unknown segment.
- ZISRAWFILE = 'ZISRAWFILE'¶
File header segment.
- ZISRAWMETADATA = 'ZISRAWMETADATA'¶
Metadata segment.
- ZISRAWDIRECTORY = 'ZISRAWDIRECTORY'¶
SubBlock directory segment.
- ZISRAWSUBBLOCK = 'ZISRAWSUBBLOCK'¶
SubBlock segment.
- ZISRAWATTDIR = 'ZISRAWATTDIR'¶
Attachment directory segment.
- ZISRAWATTACH = 'ZISRAWATTACH'¶
Attachment segment.
- DELETED = 'DELETED'¶
Deleted segment data.
- read_segment_data: Callable[[CziSegment], CziSegmentData]¶
Callable that parses payload for this segment identifier.
- __new__(value)¶
- property packed: bytes¶
Segment ID as 16-byte little-endian field.
Return the identifier encoded as cp1252 and zero-padded to 16 bytes, matching the on-disk segment header layout.
- class czifile.CziSegmentNotFoundError¶
Bases:
ValueErrorException to indicate that file does not contain segment at position.
- __weakref__¶
list of weak references to the object
- class czifile.CziSubBlockDirectorySegmentData(segment, /)¶
Bases:
CziSegmentDataZISRAWDIRECTORY segment data.
Contains entries of any kind, currently only CziDirectoryEntryDV.
- Parameters:
segment (CziSegment) – Associated segment.
- SID: str = 'ZISRAWDIRECTORY'¶
CziSegment identifier.
- __init__(segment, /)¶
- Parameters:
segment (CziSegment)
- Return type:
None
- entries: tuple[CziDirectoryEntryDV, ...]¶
Directory entries.
- static file_positions(fh, /)¶
Return file positions of associated
SubBlocksegments.Lightweight alternative to full parsing: reads only the file offsets without constructing
CziDirectoryEntryDVobjects. Useful for recovery or when only segment locations are needed.- Parameters:
fh (IO[bytes]) – File handle to read from.
- Return type:
tuple[int, …]
- property segment: CziSegment¶
Parent segment associated with data.
- __str__()¶
Return str(self).
- Return type:
str
- class czifile.CziSubBlockSegmentData(segment, /)¶
Bases:
CziSegmentDataZISRAWSUBBLOCK segment data (ImageSubBlock).
Contains XML metadata, optional attachments, and homogeneous, contiguous pixel data.
- Parameters:
segment (CziSegment) – Associated segment.
- SID: str = 'ZISRAWSUBBLOCK'¶
CziSegment identifier.
- __init__(segment, /)¶
- Parameters:
segment (CziSegment)
- Return type:
None
- metadata_size: int¶
Size of metadata section.
- attachment_size: int¶
Size of optional attachment section.
- data_size: int¶
Size of data section.
- directory_entry: CziDirectoryEntryDV¶
Image subset indices and size information.
- data_offset: int¶
Position of data section in file.
- property segment: CziSegment¶
Parent segment associated with data.
- property directory_entry_offset: int¶
Position of inline directory entry in file.
- property metadata_offset: int¶
Position of metadata section in file.
- metadata(*, asdict: Literal[False] = False, fixesc: bool = True) str¶
- metadata(*, asdict: Literal[True], fixesc: bool = True) dict[str, Any]
- metadata(*, asdict: bool = False, fixesc: bool = True) str | dict[str, Any]
Return metadata from file.
- Parameters:
asdict (bool) – If true, return metadata as dict, else XML (default).
fixesc (bool) – Replace
<and>with<and>. Fixes frequent, unparsable XML elements.
- Return type:
str | dict[str, Any]
- data(*, raw: Literal[False] = False) NDArray[Any]¶
- data(*, raw: Literal[True]) bytes
- data(*, raw: bool = False) bytes | NDArray[Any]
Return image data from file.
- Parameters:
raw (bool) – If false (default), return decoded image data from file, else return undecoded data.
- Return type:
bytes | NDArray[Any]
- attachments()¶
Return optional attachments from file.
- Returns:
Sequence of tuples of guid and binary attachments.
- Return type:
tuple[tuple[bytes, bytes], …]
- mask()¶
Return subblock validity mask, or
Noneif absent.The mask is a boolean ndarray of shape
(height, width)whereTrueindicates a pixel that was written by the encoder.Falsepixels are gaps - they were not covered by the sensor and should be treated as background. The compositing code inCziImage.asarray()uses this mask to avoid overwriting already-composited pixels with gap values.- Return type:
NDArray[Any] | None
- __str__()¶
Return str(self).
- Return type:
str
- class czifile.CziUnknownSegmentData(segment, /)¶
Bases:
CziSegmentDataUnknown segment data. Ignore.
- Parameters:
segment (CziSegment) – Associated segment.
- SID: str = 'UNKNOWN'¶
CziSegment identifier.
- __init__(segment, /)¶
- Parameters:
segment (CziSegment)
- Return type:
None
- property segment: CziSegment¶
Parent segment associated with data.
- __str__()¶
Return str(self).
- Return type:
str
- czifile.imread(files: str | os.PathLike[Any] | IO[bytes], /, *, scene: SelectionValue = FIRST_SCENE, roi: tuple[int, int, int, int] | None = None, pixeltype: CziPixelType | None = None, fillvalue: ArrayLike | None = 0, storedsize: bool = False, squeeze: bool = True, maxworkers: int | None = None, asxarray: Literal[False] = False, out: OutputType = None, **selection: SelectionValue) NDArray[Any]¶
- czifile.imread(files: str | os.PathLike[Any] | IO[bytes], /, *, scene: SelectionValue = FIRST_SCENE, roi: tuple[int, int, int, int] | None = None, pixeltype: CziPixelType | None = None, fillvalue: ArrayLike | None = 0, storedsize: bool = False, squeeze: bool = True, maxworkers: int | None = None, asxarray: Literal[True], out: OutputType = None, **selection: SelectionValue) DataArray
- czifile.imread(files: str | os.PathLike[Any] | IO[bytes], /, *, scene: SelectionValue = FIRST_SCENE, roi: tuple[int, int, int, int] | None = None, pixeltype: CziPixelType | None = None, fillvalue: ArrayLike | None = 0, storedsize: bool = False, squeeze: bool = True, maxworkers: int | None = None, asxarray: bool, out: OutputType = None, **selection: SelectionValue) NDArray[Any] | DataArray
Return image data from CZI file as numpy array or xarray DataArray.
- Parameters:
files (str | os.PathLike[Any] | IO[bytes]) – File name or seekable binary stream.
scene (SelectionValue) – Absolute S-coordinate(s) of scene(s) to read. Defaults to the first available scene. An
intselects a single scene by its S-coordinate. Asliceselects scenes whose S-coordinate falls within the range defined by the slice. A sequence ofintmerges the specified scenes into one array. IfNone, read all scenes merged into one array.roi (tuple[int, int, int, int] | None) – Spatial region of interest in absolute pixel coordinates
(x, y, width, height).pixeltype (CziPixelType | None) – Output pixel type. If
None, use the pixel type of the image. When specified, tiles are converted during compositing.fillvalue (ArrayLike | None) – Value for pixels not covered by any subblock.
storedsize (bool) – Return pixel data at stored resolution. Skip resampling of Airyscan and PALM tiles.
squeeze (bool) – If True, remove dimensions of length 1 from result.
maxworkers (int | None) – Maximum number of threads to decode subblock data. By default, up to half the CPU cores are used.
asxarray (bool) – If True, return an xarray DataArray instead of a numpy array.
out (OutputType) – Output destination for image data. Passed to
CziImage.asarray()orCziImage.asxarray().**selection (SelectionValue) – Dimension selections forwarded to
CziImage.__call__().
- Return type:
NDArray[Any] | DataArray
- czifile.logger()¶
Return module logger.
- Return type:
Logger
- czifile.CONVERT_PIXELTYPE¶
Map of (source, target) CziPixelType pairs to converter functions.