### start Source: https://github.com/cgohlke/czifile/blob/master/_autodocs/api-reference/cziimage.md Gets the start indices in each dimension after squeezing (if enabled). All indices are absolute CZI file-level coordinates. ```APIDOC ## Property: start ```python @property def start(self) -> tuple[int, ...] ``` Start indices in each dimension after squeezing (if enabled). All indices are absolute CZI file-level coordinates. ``` -------------------------------- ### Example Usage: Catching CziFileError Source: https://github.com/cgohlke/czifile/blob/master/_autodocs/errors.md Provides an example of how to use a try-except block to catch CziFileError when opening and reading a CZI file. It also includes handling for FileNotFoundError and other unexpected exceptions. ```python import czifile # Catch CZI-specific errors try: with czifile.CziFile('file.czi') as czi: image = czi.asarray() except czifile.CziFileError as e: print(f"Cannot read CZI file: {e}") except FileNotFoundError: print("File not found") except Exception as e: print(f"Unexpected error: {e}") ``` -------------------------------- ### Get czifile Package Version Source: https://github.com/cgohlke/czifile/blob/master/_autodocs/QUICK_REFERENCE.md Print the installed version of the czifile package. ```python import czifile print(czifile.__version__) # Package version ``` -------------------------------- ### Quick Start: Reading CZI Files Source: https://github.com/cgohlke/czifile/blob/master/_autodocs/INDEX.md Demonstrates basic usage of czifile.imread for simple file reading and using CziFile as a context manager to access image data and metadata. ```python import czifile # Simple usage image = czifile.imread('microscopy.czi') # With context manager with czifile.CziFile('microscopy.czi') as czi: image = czi.asarray() metadata = czi.metadata(asdict=True) ``` -------------------------------- ### datetime Source: https://github.com/cgohlke/czifile/blob/master/_autodocs/api-reference/cziimage.md Retrieves the acquisition start datetime as a numpy datetime64 object. Returns None if the datetime is not available. ```APIDOC ## Property: datetime ```python @property def datetime(self) -> numpy.datetime64 | None ``` Acquisition start datetime as numpy datetime64, or None if not available. ``` -------------------------------- ### Example: Convert 16-bit Grayscale to 8-bit Pixel Data Source: https://github.com/cgohlke/czifile/blob/master/_autodocs/types.md Demonstrates how to use the CONVERT_PIXELTYPE dictionary to find and apply a converter function for changing pixel data from 16-bit grayscale to 8-bit. ```python import czifile # Convert 16-bit grayscale to 8-bit source_type = czifile.CziPixelType.GRAY16 target_type = czifile.CziPixelType.GRAY8 if (source_type, target_type) in czifile.CONVERT_PIXELTYPE: converter = czifile.CONVERT_PIXELTYPE[(source_type, target_type)] result = converter(data) ``` -------------------------------- ### CziImage Data Selection and Manipulation Examples Source: https://github.com/cgohlke/czifile/blob/master/_autodocs/api-reference/cziimage.md Demonstrates various ways to use the CziImage.__call__ method to select subsets of image data, reorder dimensions, and apply spatial cropping. Ensure the CziFile is opened correctly before using these methods. ```python import czifile with czifile.CziFile('image.czi') as czi: img = czi.asarray() # Returns CziImage # 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)) ``` -------------------------------- ### Iterate and Print Segment IDs Source: https://github.com/cgohlke/czifile/blob/master/_autodocs/types.md Example demonstrating how to open a CZI file and iterate through its segments, printing the segment ID for each. Requires the 'czifile' library. ```python import czifile with czifile.CziFile('image.czi') as czi: for segment_data in czi.segments(): print(f"Segment type: {segment_data.segment.sid}") ``` -------------------------------- ### Example Usage of CziPixelType.get() and imread() Source: https://github.com/cgohlke/czifile/blob/master/_autodocs/types.md Demonstrates how to use the CziPixelType.get() static method to find the appropriate pixel type for a given numpy dtype and sample count, and how to use this with imread(). ```python import czifile import numpy as np # Get pixel type for uint16 single channel pixel_type = czifile.CziPixelType.get(np.uint16, 1) print(pixel_type) # CziPixelType.GRAY16 # Use in imread image = czifile.imread('image.czi', pixeltype=czifile.CziPixelType.GRAY32FLOAT) ``` -------------------------------- ### Iterate and Print CZI Attachment Information Source: https://github.com/cgohlke/czifile/blob/master/_autodocs/api-reference/segments.md Demonstrates how to open a CZI file, iterate through its attachment directory, and print details for each attachment. Requires the czifile library to be installed. ```python import czifile with czifile.CziFile('image.czi') as czi: for entry in czi.attachment_directory: print(f"Name: {entry.name}") print(f"Type: {entry.content_file_type}") print(f"Size: {entry.storage_size} bytes") ``` -------------------------------- ### Read and Print Segment Information Source: https://github.com/cgohlke/czifile/blob/master/_autodocs/api-reference/segments.md Example demonstrating how to open a CZI file, create a CziSegment object at a specific offset, and print its type and allocated size. It also shows how to retrieve and print the parsed segment data. ```python import czifile with czifile.CziFile('image.czi') as czi: # Read a segment at specific offset segment = czifile.CziSegment(czi, 0) # Read header segment print(f"Segment type: {segment.sid}") print(f"Allocated size: {segment.allocated_size}") # Get parsed data header_data = segment.data() print(f"Header: {header_data}") ``` -------------------------------- ### Access CZI File Header Information Source: https://github.com/cgohlke/czifile/blob/master/_autodocs/api-reference/segments.md Demonstrates how to open a CZI file and access its header attributes like version and GUID. Requires the 'czifile' library. ```python import czifile with czifile.CziFile('image.czi') as czi: header = czi.header print(f"Format version: {header.major_version}.{header.minor_version}") print(f"File GUID: {header.file_guid.hex()}") print(f"Metadata at: {header.metadata_position}") ``` -------------------------------- ### Handle Attachments in CZI Files Source: https://github.com/cgohlke/czifile/blob/master/_autodocs/INDEX.md Provides examples for saving all attachments from a CZI file to a directory or processing individual attachments to access their filename, type, and size. ```python with czifile.CziFile('image.czi') as czi: # Save all attachments czi.save_attachments('/output/attachments') # Or process individually for attachment in czi.attachments: print(f"Attachment: {attachment.filename}") print(f"Type: {attachment.content_file_type}") print(f"Size: {attachment.content_size}") ``` -------------------------------- ### Iterating Through Image Dimensions Source: https://github.com/cgohlke/czifile/blob/master/_autodocs/types.md Example of how to open a CZI file and iterate through its scene dimensions to identify specific types like TIME or DEPTH. ```python import czifile with czifile.CziFile('image.czi') as czi: img = czi.scenes[0] # Iterate dimensions for dim_name in img.dims: if dim_name == czifile.CziDimensionType.TIME: print("Time dimension found") elif dim_name == czifile.CziDimensionType.DEPTH: print("Z dimension (depth) found") ``` -------------------------------- ### Get Scene Images Source: https://github.com/cgohlke/czifile/blob/master/_autodocs/api-reference/cziscenes.md Retrieve a view of all CziImage instances, ordered by their S-coordinate. Use this to access the image data for each scene. ```python import czifile with czifile.CziFile('mosaic.czi') as czi: for scene_image in czi.scenes.values(): print(f"Scene shape: {scene_image.shape}") ``` -------------------------------- ### Convenience Property: First Scene Source: https://github.com/cgohlke/czifile/blob/master/_autodocs/api-reference/cziscenes.md Access the first scene (lowest S-coordinate) conveniently. This provides a quick way to get the initial scene's image data without explicit iteration. ```APIDOC ## Convenience Property: First Scene ### Description Access the first scene (lowest S-coordinate) conveniently. ### Example ```python import czifile with czifile.CziFile('mosaic.czi') as czi: first_scene = next(iter(czi.scenes.values())) ``` ``` -------------------------------- ### Read Entire CZI Image with czifile Source: https://github.com/cgohlke/czifile/blob/master/_autodocs/00_START_HERE.md Use this snippet for the simplest way to read an entire CZI image into a NumPy array. Ensure the 'czifile' library is installed. ```python import czifile # Read entire image image = czifile.imread('microscopy.czi') print(image.shape) # e.g., (512, 512) ``` -------------------------------- ### Initialize BinaryFile Source: https://github.com/cgohlke/czifile/blob/master/_autodocs/api-reference/binaryfile.md Instantiate BinaryFile with a file path or stream. Optionally enable memory mapping for improved random-access performance. Files are opened in binary mode. ```python class BinaryFile: def __init__( self, file: str | os.PathLike[str] | IO[bytes], /, *, mode: Literal['r', 'r+'] | None = None, memmap: bool = False, ) -> None ``` -------------------------------- ### Basic CZI File Operations with Context Manager Source: https://github.com/cgohlke/czifile/blob/master/_autodocs/api-reference/binaryfile.md Demonstrates using `czifile.CziFile` as a context manager for reading an image and accessing file properties. This method ensures resources are properly managed. ```python import czifile # Using context manager (recommended) with czifile.CziFile('large_image.czi', memmap=True) as czi: image = czi.asarray() ``` -------------------------------- ### Get Number of Scenes Source: https://github.com/cgohlke/czifile/blob/master/_autodocs/api-reference/cziscenes.md Get the total number of scenes in the CZI file. This is useful for pre-allocating memory or setting up loops. ```python import czifile with czifile.CziFile('mosaic.czi') as czi: num_scenes = len(czi.scenes) print(f"File contains {num_scenes} scenes") ``` -------------------------------- ### __enter__ and __exit__ Source: https://github.com/cgohlke/czifile/blob/master/_autodocs/api-reference/binaryfile.md Implementation of the context manager protocol for BinaryFile objects. ```APIDOC ## __enter__ and __exit__ ### Description These methods implement the context manager protocol, enabling the use of BinaryFile objects within `with` statements for automatic resource management. ### Method ```python def __enter__(self) -> Self def __exit__( self, exc_type: type[BaseException] | None, exc_value: BaseException | None, traceback: TracebackType | None, ) -> None ``` ``` -------------------------------- ### Get Number of Scenes Source: https://github.com/cgohlke/czifile/blob/master/_autodocs/api-reference/cziscenes.md Get the total number of scenes available in the CZI file. This is useful for pre-allocating memory or setting up loops. ```APIDOC ## Method: __len__ ### Description Returns the number of scenes in the CZI file. ### Method Signature ```python def __len__(self) -> int: ``` ### Returns int: Number of scenes. ### Example ```python import czifile with czifile.CziFile('mosaic.czi') as czi: num_scenes = len(czi.scenes) print(f"File contains {num_scenes} scenes") ``` ``` -------------------------------- ### Using CziFile as a Context Manager Source: https://github.com/cgohlke/czifile/blob/master/_autodocs/api-reference/czifile.md Demonstrates how to use the CziFile class as a context manager to ensure the file is automatically closed after use. This is the recommended way to open and access CZI files. ```python with czifile.CziFile('image.czi') as czi: image = czi.asarray() # File is automatically closed here ``` -------------------------------- ### Get Scene Keys Source: https://github.com/cgohlke/czifile/blob/master/_autodocs/api-reference/cziscenes.md Retrieve a view object containing the S-coordinate keys of all scenes in ascending order. This allows you to get a list of available scene identifiers. ```APIDOC ## Method: keys ### Description Returns a view of the S-coordinate values in ascending order. ### Method Signature ```python def keys(self) -> KeysView[int]: ``` ### Returns KeysView: S-coordinate values in ascending order. ### Example ```python import czifile with czifile.CziFile('mosaic.czi') as czi: scene_coords = list(czi.scenes.keys()) print(f"Available scenes: {scene_coords}") ``` ``` -------------------------------- ### coord_units Source: https://github.com/cgohlke/czifile/blob/master/_autodocs/api-reference/cziimage.md Gets the physical coordinate units for each dimension. ```APIDOC ## Property: coord_units ```python @property def coord_units(self) -> dict[str, str] ``` Physical coordinate units for each dimension. ``` -------------------------------- ### coord_offsets Source: https://github.com/cgohlke/czifile/blob/master/_autodocs/api-reference/cziimage.md Gets the physical coordinate offsets for each dimension. ```APIDOC ## Property: coord_offsets ```python @property def coord_offsets(self) -> dict[str, float] ``` Physical coordinate offsets for each dimension. ``` -------------------------------- ### Select and Read Scenes from CZI Files Source: https://github.com/cgohlke/czifile/blob/master/_autodocs/QUICK_REFERENCE.md Demonstrates how to select and read individual scenes, all scenes, specific scenes by index or range, and retrieve scenes as arrays. ```python with czifile.CziFile('mosaic.czi') as czi: scenes = czi.scenes # Single scene scene0 = scenes[0] # By S-coordinate # All scenes all_scenes = scenes() # Specific scenes merged = scenes(scene=[0, 2, 4]) # Scene range range_scenes = scenes(scene=slice(0, 5)) # Get as array image = scene0.asarray() ``` -------------------------------- ### nbytes Source: https://github.com/cgohlke/czifile/blob/master/_autodocs/api-reference/cziimage.md Gets the number of bytes in the image data. ```APIDOC ## Property: nbytes ```python @property def nbytes(self) -> int ``` Number of bytes in the image data. ``` -------------------------------- ### ndim Source: https://github.com/cgohlke/czifile/blob/master/_autodocs/api-reference/cziimage.md Gets the number of dimensions after squeezing (if enabled). ```APIDOC ## Property: ndim ```python @property def ndim(self) -> int ``` Number of dimensions after squeezing (if enabled). ``` -------------------------------- ### Scene Selection with czifile.imread Source: https://github.com/cgohlke/czifile/blob/master/_autodocs/api-reference/imread.md Demonstrates reading specific scenes, merging multiple scenes, or reading all scenes merged from a CZI file. ```python import czifile # Read specific scene scene1 = czifile.imread('mosaic.czi', scene=1) # Merge multiple scenes merged = czifile.imread('mosaic.czi', scene=[0, 1, 2]) # Read all scenes merged all_scenes = czifile.imread('mosaic.czi', scene=None) ``` -------------------------------- ### dtype Source: https://github.com/cgohlke/czifile/blob/master/_autodocs/api-reference/cziimage.md Gets the Numpy dtype of image data. ```APIDOC ## Property: dtype ```python @property def dtype(self) -> numpy.dtype[Any] ``` Numpy dtype of image data. ``` -------------------------------- ### Open CZI Files Source: https://github.com/cgohlke/czifile/blob/master/_autodocs/QUICK_REFERENCE.md Demonstrates different ways to open CZI files, including simple read, memory mapping for large files, and a one-line read operation. ```python # Simple read with czifile.CziFile('image.czi') as czi: image = czi.asarray() ``` ```python # With memory mapping (for large files) with czifile.CziFile('image.czi', memmap=True) as czi: image = czi.asarray() ``` ```python # One-line read image = czifile.imread('image.czi') ``` -------------------------------- ### size Source: https://github.com/cgohlke/czifile/blob/master/_autodocs/api-reference/cziimage.md Gets the total number of elements, which is the product of the shape. ```APIDOC ## Property: size ```python @property def size(self) -> int ``` Total number of elements (product of shape). ``` -------------------------------- ### BinaryFile Initialization Source: https://github.com/cgohlke/czifile/blob/master/_autodocs/api-reference/binaryfile.md Initializes a BinaryFile object. It can accept a file path, a file-like object, or a stream. Optional parameters include the file mode and a flag for memory mapping. ```APIDOC ## Class: BinaryFile ```python class BinaryFile: def __init__( self, file: str | os.PathLike[str] | IO[bytes], /, *, mode: Literal['r', 'r+'] | None = None, memmap: bool = False, ) -> None ``` ### Parameters | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | file | str \| os.PathLike[str] \| IO[bytes] | Yes | — | File name or seekable binary stream. | | mode | Literal['r', 'r+'] \| None | No | None | File open mode if `file` is a file name. Defaults to `'r'`. Files are always opened in binary mode. | | memmap | bool | No | False | Map file into memory. Improves random-access performance on large files but ignored if memory mapping is not available or if the stream doesn't support it. | ### Raises | Error | Condition | |-------|-----------| | TypeError | File is a text stream, or an unsupported type. | | ValueError | Invalid file name, extension, or stream. File stream is not seekable. | ### Notes Memory mapping can improve random-access read performance on large files or repeated reads by reducing syscall overhead and data copying. For sequential one-pass reads, regular buffered I/O may be faster. ``` -------------------------------- ### axes Source: https://github.com/cgohlke/czifile/blob/master/_autodocs/api-reference/cziimage.md Gets the dimension names concatenated as a single string. ```APIDOC ## Property: axes ```python @property def axes(self) -> str ``` Dimension names concatenated as a single string. ``` -------------------------------- ### shape Source: https://github.com/cgohlke/czifile/blob/master/_autodocs/api-reference/cziimage.md Gets the shape of image data after squeezing (if enabled). ```APIDOC ## Property: shape ```python @property def shape(self) -> tuple[int, ...] ``` Shape of image data after squeezing (if enabled). ``` -------------------------------- ### coord_scales Source: https://github.com/cgohlke/czifile/blob/master/_autodocs/api-reference/cziimage.md Gets the physical coordinate scales (pixel sizes) for each dimension. ```APIDOC ## Property: coord_scales ```python @property def coord_scales(self) -> dict[str, float] ``` Physical coordinate scales (pixel sizes) for each dimension. ``` -------------------------------- ### Import czifile and numpy Source: https://github.com/cgohlke/czifile/blob/master/_autodocs/QUICK_REFERENCE.md Import the necessary libraries for using czifile and numpy. ```python import czifile import numpy as np ``` -------------------------------- ### dims Source: https://github.com/cgohlke/czifile/blob/master/_autodocs/api-reference/cziimage.md Gets the dimension names in output order after squeezing (if enabled). ```APIDOC ## Property: dims ```python @property def dims(self) -> tuple[str, ...] ``` Dimension names in output order after squeezing (if enabled). ``` -------------------------------- ### Get Numpy Dtype Source: https://github.com/cgohlke/czifile/blob/master/_autodocs/api-reference/cziimage.md Access the Numpy dtype of the image data. ```python @property def dtype(self) -> numpy.dtype[Any] ``` -------------------------------- ### sizes Source: https://github.com/cgohlke/czifile/blob/master/_autodocs/api-reference/cziimage.md Gets a dictionary mapping dimension names to their sizes after squeezing (if enabled). ```APIDOC ## Property: sizes ```python @property def sizes(self) -> dict[str, int] ``` Dictionary mapping dimension names to their sizes after squeezing (if enabled). ### Example ```python sizes = img.sizes # {'T': 10, 'C': 3, 'Z': 20, 'Y': 512, 'X': 512} ``` ``` -------------------------------- ### CziImage Constructor Parameters Source: https://github.com/cgohlke/czifile/blob/master/_autodocs/configuration.md Specifies the parameters for initializing a CziImage object. Requires a CziFile parent and directory entries. Options include name, dimension squeezing, region of interest, pixel type, stored size, and dimension selections. ```python def __init__( parent: CziFile, directory_entries: tuple[CziDirectoryEntryDV, ...], /, *, name: str = '', squeeze: bool = True, roi: tuple[int, int, int, int] | None = None, pixeltype: CziPixelType | None = None, storedsize: bool = False, selection: dict[str, SelectionValue] | None = None, ) -> None ``` -------------------------------- ### Get Image Shape Source: https://github.com/cgohlke/czifile/blob/master/_autodocs/api-reference/cziimage.md Access the shape of the image data after squeezing (if enabled). ```python @property def shape(self) -> tuple[int, ...] ``` -------------------------------- ### Open CZI File in Writable Mode Source: https://github.com/cgohlke/czifile/blob/master/_autodocs/api-reference/binaryfile.md Demonstrates opening a CZI file in read/write mode ('r+') using a context manager. Verifies if the file is writable and checks the update pending status in the header. Writing to CZI files requires a deep understanding of the format. ```python import czifile import struct # Open file for reading and writing with czifile.CziFile('image.czi', mode='r+') as czi: if czi.writable: # File is open for writing # Note: Writing to CZI files requires understanding the format print("File is writable") print(f"Update pending: {czi.header.update_pending}") ``` -------------------------------- ### CziFile Constructor Parameters Source: https://github.com/cgohlke/czifile/blob/master/_autodocs/configuration.md Defines the parameters for initializing a CziFile object. Supports specifying the file path, read/write mode, memory mapping, and dimension squeezing. ```python def __init__( file: str | os.PathLike[Any] | IO[bytes], /, *, mode: Literal['r', 'r+', 'rb', 'r+b'] | None = None, memmap: bool = False, squeeze: bool = True, ) -> None ``` -------------------------------- ### mpp Source: https://github.com/cgohlke/czifile/blob/master/_autodocs/api-reference/cziimage.md Gets the microns per pixel for X and Y dimensions, or None if not available in metadata. ```APIDOC ## Property: mpp ```python @property def mpp(self) -> tuple[float, float] | None ``` Microns per pixel for X and Y dimensions, or None if not available in metadata. ``` -------------------------------- ### Configure Root Logger for czifile Source: https://github.com/cgohlke/czifile/blob/master/_autodocs/api-reference/logger.md Set up the root logger using basicConfig to manage logging for the entire application, including czifile. You can then specifically adjust the 'czifile' logger's level if needed. ```python import czifile import logging # Configure root logger logging.basicConfig( level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s' ) # Suppress verbose czifile messages if desired logging.getLogger('czifile').setLevel(logging.WARNING) # Or set to DEBUG for detailed parsing information logging.getLogger('czifile').setLevel(logging.DEBUG) with czifile.CziFile('image.czi') as czi: image = czi.asarray() ``` -------------------------------- ### name Source: https://github.com/cgohlke/czifile/blob/master/_autodocs/api-reference/cziimage.md Gets the display name of this image view, including scene and selection information. ```APIDOC ## Property: name ```python @property def name(self) -> str ``` Display name of this image view, including scene and selection info. ``` -------------------------------- ### pixeltype Source: https://github.com/cgohlke/czifile/blob/master/_autodocs/api-reference/cziimage.md Gets the pixel type of image data. Reflects the requested pixeltype override if specified. ```APIDOC ## Property: pixeltype ```python @property def pixeltype(self) -> CziPixelType ``` Pixel type of image data. Reflects the requested pixeltype override if specified. ``` -------------------------------- ### Get Axes String Source: https://github.com/cgohlke/czifile/blob/master/_autodocs/api-reference/cziimage.md Access the dimension names concatenated as a single string after squeezing (if enabled). ```python @property def axes(self) -> str ``` -------------------------------- ### Get Dimension Names Source: https://github.com/cgohlke/czifile/blob/master/_autodocs/api-reference/cziimage.md Retrieve a tuple of dimension names in output order after squeezing (if enabled). ```python @property def dims(self) -> tuple[str, ...] ``` -------------------------------- ### Access First Scene Conveniently Source: https://github.com/cgohlke/czifile/blob/master/_autodocs/api-reference/cziscenes.md Access the first scene (lowest S-coordinate) directly without explicit iteration. This is a shortcut for retrieving the initial scene's image data. ```python import czifile with czifile.CziFile('mosaic.czi') as czi: first_scene = next(iter(czi.scenes.values())) ``` -------------------------------- ### Use BinaryFile as a Context Manager Source: https://github.com/cgohlke/czifile/blob/master/_autodocs/api-reference/binaryfile.md BinaryFile instances can be used as context managers, which automatically handle closing the file and cleaning up resources upon exiting the `with` block. This is the recommended approach for file operations. ```python import czifile with czifile.BinaryFile('file.bin') as bf: # Use file pass # File is automatically closed here ``` -------------------------------- ### Get Image Sizes Source: https://github.com/cgohlke/czifile/blob/master/_autodocs/api-reference/cziimage.md Retrieve a dictionary mapping dimension names to their sizes after squeezing (if enabled). ```python @property def sizes(self) -> dict[str, int] ``` ```python sizes = img.sizes # {'T': 10, 'C': 3, 'Z': 20, 'Y': 512, 'X': 512} ``` -------------------------------- ### Read Image Data from CZI Files Source: https://github.com/cgohlke/czifile/blob/master/_autodocs/QUICK_REFERENCE.md Shows how to read image data, including specific channels, channel ranges, multiple channels, Z-planes, and time points. Also demonstrates combining selections. ```python # Full image image = czifile.imread('image.czi') ``` ```python # Specific channel channel = czifile.imread('image.czi', C=0) ``` ```python # Channel range (absolute coordinates) channels = czifile.imread('image.czi', C=slice(0, 5)) ``` ```python # Multiple channels multi = czifile.imread('image.czi', C=[0, 2, 4]) ``` ```python # Z-planes z_plane = czifile.imread('image.czi', Z=10) z_range = czifile.imread('image.czi', Z=slice(5, 15)) ``` ```python # Time points timepoint = czifile.imread('image.czi', T=0) timeseries = czifile.imread('image.czi', T=None) # All T ``` ```python # Combine selections image = czifile.imread('image.czi', C=0, Z=10, T=slice(0, 50)) ``` -------------------------------- ### Get Pixel Type Source: https://github.com/cgohlke/czifile/blob/master/_autodocs/api-reference/cziimage.md Retrieve the pixel type of the image data. This reflects any specified pixeltype override. ```python @property def pixeltype(self) -> CziPixelType ``` -------------------------------- ### Configure czifile Logging Source: https://github.com/cgohlke/czifile/blob/master/_autodocs/QUICK_REFERENCE.md Set the logging level for the czifile library or the root logger. Use ERROR to suppress warnings. ```python import czifile import logging # Enable debug logging czifile.logger().setLevel(logging.DEBUG) # Or configure root logger logging.basicConfig(level=logging.DEBUG) # Suppress warnings czifile.logger().setLevel(logging.ERROR) ``` -------------------------------- ### compression Source: https://github.com/cgohlke/czifile/blob/master/_autodocs/api-reference/cziimage.md Gets the compression type used for all subblocks in this image. Raises ValueError if subblocks have different compression types. ```APIDOC ## Property: compression ```python @property def compression(self) -> CziCompressionType ``` Compression type used for all subblocks in this image. Raises ValueError if subblocks have different compression types. ``` -------------------------------- ### Get Image View Name Source: https://github.com/cgohlke/czifile/blob/master/_autodocs/api-reference/cziimage.md Access the display name of the image view, which includes scene and selection information. ```python @property def name(self) -> str ``` -------------------------------- ### Write Attachment Content to Disk Source: https://github.com/cgohlke/czifile/blob/master/_autodocs/api-reference/segments.md Demonstrates how to iterate through attachments in a CZI file, print their details, and save their content to disk using the `write_file` method. ```python import czifile with czifile.CziFile('image.czi') as czi: for attachment in czi.attachments: print(f"Attachment: {attachment.filename}") print(f"Type: {attachment.content_file_type}") print(f"Size: {attachment.content_size} bytes") # Save to disk filepath = attachment.write_file('/tmp') print(f"Saved to: {filepath}") ``` -------------------------------- ### coords Source: https://github.com/cgohlke/czifile/blob/master/_autodocs/api-reference/cziimage.md Gets the physical coordinates for each dimension as numpy arrays. Includes dimension offsets, scales, and units from metadata if available. ```APIDOC ## Property: coords ```python @property def coords(self) -> dict[str, NDArray[Any]] ``` Physical coordinates for each dimension as numpy arrays. Includes dimension offsets, scales, and units from metadata if available. ``` -------------------------------- ### Context Manager Source: https://github.com/cgohlke/czifile/blob/master/_autodocs/api-reference/binaryfile.md BinaryFile instances can be used as context managers, which automatically call `close()` upon exiting the `with` block, ensuring resources are properly released. ```APIDOC ## Context Manager ### Description BinaryFile instances implement the context manager protocol, allowing for automatic resource management. When used with a `with` statement, the `close()` method is automatically invoked upon exiting the block, even if errors occur. ### Example ```python import czifile with czifile.BinaryFile('file.bin') as bf: # Use file pass # File is automatically closed here ``` ``` -------------------------------- ### Basic CZI File Operations with Manual Management Source: https://github.com/cgohlke/czifile/blob/master/_autodocs/api-reference/binaryfile.md Shows manual resource management for `czifile.CziFile` using a `try...finally` block to ensure the file is closed and resources are released. It also prints file size and memory mapping status. ```python import czifile # Manual resource management czi = czifile.CziFile('image.czi') try: image = czi.asarray() print(f"File size: {czi.filesize} bytes") print(f"Memory mapped: {czi.memmapped}") finally: czi.close() ``` -------------------------------- ### Get Scene S-Coordinates Source: https://github.com/cgohlke/czifile/blob/master/_autodocs/api-reference/cziscenes.md Retrieve a view of all available S-coordinate values in ascending order. Convert to a list to store or process them. ```python import czifile with czifile.CziFile('mosaic.czi') as czi: scene_coords = list(czi.scenes.keys()) print(f"Available scenes: {scene_coords}") ``` -------------------------------- ### bbox Source: https://github.com/cgohlke/czifile/blob/master/_autodocs/api-reference/cziimage.md Gets the bounding box as (x, y, width, height) in absolute pixel coordinates, or (0, 0, 0, 0) if no extent. ```APIDOC ## Property: bbox ```python @property def bbox(self) -> tuple[int, int, int, int] ``` Bounding box as `(x, y, width, height)` in absolute pixel coordinates, or `(0, 0, 0, 0)` if no extent. ``` -------------------------------- ### Load and Select Image Data Source: https://github.com/cgohlke/czifile/blob/master/README.rst Demonstrates loading a CZI file and selecting specific image data using various indexing and slicing methods. Shows integer and None selection for dimensions, and region of interest (ROI) selection. ```python 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' ``` -------------------------------- ### Get Total Number of Chunks Source: https://github.com/cgohlke/czifile/blob/master/_autodocs/api-reference/czimagechunks.md Use the `len()` function on a CziImageChunks object to retrieve the total number of chunks available for iteration. ```python import czifile with czifile.CziFile('image.czi') as czi: img = czi.scenes[0] chunks = img.chunks(dimension='Z') print(f"Total Z-chunks: {len(chunks)}") ``` -------------------------------- ### Access CZIFile Image Properties Source: https://github.com/cgohlke/czifile/blob/master/_autodocs/QUICK_REFERENCE.md Illustrates how to access various image properties such as shape, dimensions, data type, positioning, and metadata using a context manager. ```python with czifile.CziFile('image.czi') as czi: img = czi.scenes[0] # Structure img.shape # Tuple of dimension sizes img.dims # Tuple of dimension names img.sizes # Dict of dimension name -> size img.ndim # Number of dimensions img.size # Total number of pixels # Data type img.dtype # Numpy dtype img.pixeltype # CziPixelType enum # Positioning img.start # Start indices in each dimension img.bbox # (x, y, width, height) bounding box # Metadata img.coords # Physical coordinates per dimension img.coord_scales # Pixel sizes img.coord_units # Units (e.g., 'microns') img.mpp # Microns per pixel (X, Y) img.datetime # Acquisition start time img.channels # Channel metadata img.objective # Objective metadata ``` -------------------------------- ### Get Compression Type Source: https://github.com/cgohlke/czifile/blob/master/_autodocs/api-reference/cziimage.md Retrieve the compression type used for all subblocks within the image. Raises ValueError if subblocks have inconsistent compression types. ```python @property def compression(self) -> CziCompressionType ``` -------------------------------- ### Iterate Directory Entries Source: https://github.com/cgohlke/czifile/blob/master/README.rst Demonstrates iterating through directory entries of a CZI scene and accessing them as CziImage views. Each entry can be loaded as an array with specified dimensions. ```python with CziFile('Example.czi') as czi: for entry in czi.scenes[0].directory_entries: chunk = entry.asimage(czi) arr = chunk.asarray() assert arr.shape == (256, 256) ``` -------------------------------- ### Get Segment Data Source: https://github.com/cgohlke/czifile/blob/master/_autodocs/api-reference/segments.md Parses and returns the segment's data payload as the appropriate CziSegmentData subclass. This method is part of the CziSegment class. ```python def data(self) -> CziSegmentData: ``` -------------------------------- ### Get czifile Logger Instance Source: https://github.com/cgohlke/czifile/blob/master/_autodocs/api-reference/logger.md Retrieve the logger instance used by czifile. This logger is named 'czifile' and propagates to the root logger by default. ```python import czifile import logging # Get the czifile logger czi_logger = czifile.logger() # Set log level czi_logger.setLevel(logging.DEBUG) # Add a console handler handler = logging.StreamHandler() handler.setLevel(logging.DEBUG) formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') handler.setFormatter(formatter) czi_logger.addHandler(handler) # Now read a file with debug logging enabled with czifile.CziFile('image.czi') as czi: image = czi.asarray() ``` -------------------------------- ### FileNotFoundError Message Source: https://github.com/cgohlke/czifile/blob/master/_autodocs/errors.md This error indicates the specified CZI file could not be found. Verify the file path and existence. ```text FileNotFoundError: [Errno 2] No such file or directory: 'image.czi' ``` -------------------------------- ### Handle CZIFile Errors Source: https://github.com/cgohlke/czifile/blob/master/_autodocs/QUICK_REFERENCE.md Demonstrates how to catch specific exceptions like CziFileError, FileNotFoundError, ValueError, and KeyError when reading CZI files. ```python import czifile try: image = czifile.imread('image.czi') except czifile.CziFileError as e: print(f"Invalid CZI file: {e}") except FileNotFoundError: print("File not found") except ValueError as e: # Selection matches no subblocks, unknown dimension, etc. print(f"Invalid operation: {e}") except KeyError as e: # Scene not found print(f"Key not found: {e}") ``` -------------------------------- ### Multi-Dimensional Chunking with Axes Source: https://github.com/cgohlke/czifile/blob/master/_autodocs/api-reference/czimagechunks.md Iterate over multi-dimensional blocks of image data by specifying multiple axes. This example iterates over Z, Y, and X blocks. ```python import czifile with czifile.CziFile('volume_series.czi') as czi: img = czi.scenes[0] # Iterate over Z x Y x X blocks for block in img.chunks(axes=['Z', 'Y', 'X']): print(f"Block shape: {block.shape}") array = block.asarray() ``` -------------------------------- ### CziFile Source: https://github.com/cgohlke/czifile/blob/master/_autodocs/00_START_HERE.md Provides a context manager for reading CZI files with more control over metadata and scene access. ```APIDOC ## CziFile ### Description Provides a context manager for reading CZI files with more control over metadata and scene access. Allows for detailed inspection and extraction of specific parts of the CZI data. ### Signature `class czifile.CziFile(filename: str | PathLike, **kwargs)` ### Methods - **metadata(**asdict: bool = False**) -> dict | CziMetadata** Returns the CZI metadata. If `asdict` is True, returns a dictionary; otherwise, returns a `CziMetadata` object. - **scenes** A property that returns a list of scenes within the CZI file. - **img(scene: Scene, **kwargs)** Selects a specific scene and allows for dimension-based slicing. - **asarray(**scene: Scene | None = None**, ****kwargs) -> numpy.ndarray** Returns the image data as a NumPy array, optionally for a specified scene. ### Usage Example ```python with czifile.CziFile('image.czi') as czi: metadata = czi.metadata(asdict=True) img = czi.scenes[0] channel0 = img(C=0) z_plane = channel0(Z=10) data = z_plane.asarray() ``` ``` -------------------------------- ### levels Source: https://github.com/cgohlke/czifile/blob/master/_autodocs/api-reference/cziimage.md Accesses the pyramid levels of the image. Returns a list of CziImage instances, starting with level 0 (the current image), representing each pyramid level. ```APIDOC ## Property: levels ```python @property def levels(self) -> list[CziImage] ``` Pyramid levels starting with level 0 (this image). Returns a list of CziImage instances for each pyramid level. ``` -------------------------------- ### Accessing Metadata from CZI Files Source: https://github.com/cgohlke/czifile/blob/master/_autodocs/QUICK_REFERENCE.md Demonstrates how to access raw XML metadata, parsed dictionary metadata, XML elements, and image properties like shape, dimensions, and channels. ```python with czifile.CziFile('image.czi') as czi: # Raw XML metadata xml = czi.metadata() # Parsed as dict metadata = czi.metadata(asdict=True) # Parsed XML element root = czi.xml_element # Image properties image = czi.scenes[0] print(f"Shape: {image.shape}") print(f"Dims: {image.dims}") print(f"Dtype: {image.dtype}") print(f"Channels: {image.channels}") print(f"Objective: {image.objective}") print(f"MPP (microns per pixel): {image.mpp}") ``` -------------------------------- ### CziScenes Mapping Interface Usage Source: https://github.com/cgohlke/czifile/blob/master/_autodocs/api-reference/cziscenes.md Demonstrates basic usage of the CziScenes mapping interface, including checking the number of scenes, verifying scene existence, retrieving scene coordinates, and iterating through scenes to access their shapes. ```python import czifile with czifile.CziFile('mosaic.czi') as czi: scenes = czi.scenes # Check number of scenes num_scenes = len(scenes) print(f"Number of scenes: {num_scenes}") # Check if a scene exists if 0 in scenes: print("Scene 0 exists") # Get all scene S-coordinates scene_keys = list(scenes.keys()) print(f"Scene S-coordinates: {scene_keys}") # Iterate through all scenes for s_coord, scene_image in scenes.items(): print(f"Scene {s_coord}: shape {scene_image.shape}") ``` -------------------------------- ### Handle Multiple Dimensions in CZI Files Source: https://github.com/cgohlke/czifile/blob/master/_autodocs/INDEX.md Illustrates how to select specific dimensions (like channels, Z-planes, or time points) when reading CZI files and how to reorder dimensions. ```python # Select dimensions (absolute coordinates) image = czifile.imread( 'timeseries.czi', C=0, # Channel 0 Z=slice(5, 15), # Z planes 5-14 T=None # All time points ) # Reorder dimensions image = czifile.imread( 'image.czi', Z=None, # Make Z first T=None, # Make T second C=None # Make C third ) ``` -------------------------------- ### CziFileHeaderSegmentData Source: https://github.com/cgohlke/czifile/blob/master/_autodocs/api-reference/segments.md Represents the file header segment containing global CZI file metadata. It provides access to format version, GUIDs, and positions of other segments. ```APIDOC ## Class: CziFileHeaderSegmentData ### Description File header segment containing global CZI file metadata. ### Attributes - **major_version** (int) - File format major version - **minor_version** (int) - File format minor version - **reserved** (bytes) - Reserved bytes from file header - **primary_file_guid** (bytes) - GUID of primary file (16 bytes) - **file_guid** (bytes) - GUID of this file (16 bytes) - **update_pending** (bool) - Flag indicating file updates are pending - **directory_position** (int) - Absolute position of subblock directory segment or 0 - **metadata_position** (int) - Absolute position of metadata segment or 0 - **attachment_directory_position** (int) - Absolute position of attachment directory segment or 0 ### Example ```python import czifile with czifile.CziFile('image.czi') as czi: header = czi.header print(f"Format version: {header.major_version}.{header.minor_version}") print(f"File GUID: {header.file_guid.hex()}") print(f"Metadata at: {header.metadata_position}") ``` ``` -------------------------------- ### Get CZI Metadata Source: https://github.com/cgohlke/czifile/blob/master/_autodocs/api-reference/czifile.md Shows how to retrieve metadata from a CZI file, either as raw XML or as a parsed dictionary. Useful for inspecting image properties and information. ```python import czifile with czifile.CziFile('image.czi') as czi: # Get raw XML metadata xml = czi.metadata() print(xml) # Get parsed metadata as dictionary metadata = czi.metadata(asdict=True) print(metadata['ImageDocument']['Metadata']['Information']) ```