Skip to content

Image Stack

Source

Image stack protocol and implementations.

CziImageStack

A class for extracting patches from an image stack that is stored as a CZI file.

Parameters:

  • data_path (str or Path) –

    Path to the CZI file.

  • scene (int, default: None ) –

    Index of the scene to extract.

    A single CZI file can contain multiple "scenes", which are stored alongside each other at different coordinates in the image plane, often separated by empty space. Specifying this argument will read only the single scene with that index from the file. Think of it as cropping the CZI file to the region where that scene is located.

    If no scene index is specified, the entire image will be read. In case it contains multiple scenes, they will all be present in the resulting image. This is usually not desirable due to the empty space between them. In general, only omit this argument or set it to None if you know that your CZI file does not contain any scenes.

    The static function 🇵🇾meth:get_bounding_rectangles can be used to find out how many scenes a given file contains and what their bounding rectangles are.

    The scene can also be provided as part of data_path by appending an "@" followed by the scene index to the filename.

  • depth_axis (('none', 'Z', 'T'), default: "none" ) –

    Which axis to use as depth-axis for providing 3-D patches.

    • "none": Only provide 2-D patches. If a Z or T dimension is present in the data, they will be combined into the sample dimension S.
    • "Z": Use the Z-axis as depth-axis. If a T axis is present as well, it will be merged into the sample dimensions S.
    • "T": Use the T-axis as depth-axis. If a Z axis is present as well, it will be merged into the sample dimensions S.

Attributes:

  • source (Path) –

    Path to the CZI file, including the scene index if specified.

  • data_path (Path) –

    Path to the CZI file without scene index.

  • scene (int or None) –

    Index of the scene to extract, or None if not specified.

  • data_shape (Sequence[int]) –

    The shape of the data in the order (SC(Z)YX).

  • axes (str) –

    The axes in the CZI file corresponding to the dimensions in data_shape. The following values can occur:

    • "SCZYX" for 3-D volumes if depth_axis is "Z".
    • "SCTYX" for time-series if depth_axis is "T".
    • "SCYX" if depth_axis is "none".

    The axis S (sample) is the only one not mapping one-to-one to an axis in the CZI file but combines all remaining axes present in the file into one.

Examples:

Create an image stack for the first scene in a CZI file:

>>> stack = CziImageStack("path/to/file.czi", scene=0)

Alternatively, the scene index can also be provided as part of the filename. This is mainly intended for re-creating an image stack from the source property:

>>> stack = CziImageStack("path/to/file.czi@0")
>>> stack2 = CziImageStack(stack.source)

If the CZI file contains a third dimension (Z or T) and you want to perform 3-D denoising, you need to explicitly set depth_axis to "Z" or "T":

>>> stack_2d = CziImageStack("path/to/file.czi", scene=0)
>>> stack_2d.axes, stack_2d.data_shape
('SCYX', [40, 1, 512, 512])
>>> stack_3d = CziImageStack(
...     "path/to/file.czi", scene=0, depth_axis="Z"
... )
>>> stack_3d.axes, stack_3d.data_shape
('SCZYX', [4, 1, 10, 512, 512])

original_axes property

Original axes of the data.

Returns:

  • str

    Axis string before merging dimensions into the sample axis S.

original_data_shape property

Original shape of the data.

Returns:

  • tuple[int, ...]

    Shape before merging dimensions into the sample axis S.

source property

Path to the CZI file, including scene index in the filename if set.

Returns:

  • Path

    Path that can be used to recreate this image stack (e.g. file.czi@0).

__del__()

Close the CZI file handle when the instance is destroyed.

__getstate__()

Return state for pickling, excluding the non-picklable CZI reader.

Returns:

  • dict[str, Any]

    Instance dictionary without the CZI reader.

__init__(data_path, scene=None, depth_axis='none')

Constructor.

As a CZI file can contain multiple scenes, the scene to extract can be specified either as a separate argument scene or as part of the data_path by appending an "@" followed by the scene index to the filename (e.g. file.czi@0 for scene 0). If both are provided, a ValueError is raised.

Both T and Z axes can be used as depth axes for 3D denoising, other non spatial axes will be merged into the sample dimension S.

Parameters:

  • data_path (str or Path) –

    Path to the CZI file (optionally with @scene suffix).

  • scene (int or None, default: None ) –

    Scene index to load; see class docstring. Omit if encoded in path.

  • depth_axis (('none', 'Z', 'T'), default: "none" ) –

    Axis to use as depth for 3D patches.

Raises:

  • ImportError

    If the pylibCZIrw package is not installed.

  • ValueError

    If the scene index is specified both in the filename and as an argument.

__setstate__(state)

Restore state after unpickling and reopen the CZI file.

Parameters:

  • state (dict[str, Any]) –

    State from __getstate__.

Returns:

  • None

    No return value; instance state is updated in place.

extract_patch(sample_idx, channels, coords, patch_size)

Extract a patch for a given sample and channels within the image stack.

Parameters:

  • sample_idx (int) –

    Sample index.

  • channels (sequence of int or None) –

    Channel indices to extract. If None, all channels will be extracted.

  • coords (sequence of int) –

    Spatial coordinates of the top-left corner of the patch.

  • patch_size (sequence of int) –

    Size of the patch in each spatial dimension.

Returns:

  • ndarray

    A patch of the image data from a particular sample with dimensions C(Z)YX.

get_bounding_rectangles(czi) classmethod

Get the bounding rectangles of all scenes in a CZI file.

Parameters:

  • czi (Path or str or CziReader) –

    Path to the CZI file or an already opened file as CziReader object.

Returns:

  • dict[int | None, Rectangle]

    A dictionary mapping scene indices to their bounding rectangles in the format (x, y, w, h). If no scenes are present in the CZI file, the returned dictionary will have only one entry with key None, whose bounding rectangle covers the entire image.

FileImageStack

ImageStack implementation for file-backed data.

This implementation is aimed at representing a single file from a set of multi-file datasets, where the entire dataset cannot be loaded into memory at once.

Parameters:

  • source (Path) –

    Path to the file.

  • axes (str) –

    Axis order (e.g. STCZYX).

  • data_shape (tuple of int) –

    Shape in SC(Z)YX order.

  • data_dtype (DTypeLike) –

    Type of the data.

  • read_func (ReadFunc) –

    Function to read the file into an array.

  • read_kwargs (dict or Any, default: None ) –

    Extra keyword arguments for read_func.

  • original_data_shape (tuple of int or None, default: None ) –

    Shape in original axis order.

Notes

The data will not be loaded until the load method is called. The close method can be used to remove the internal reference to the data.

is_loaded property

True if the file has been loaded into memory.

Returns:

  • bool

    True if the file has been loaded into memory, False otherwise.

original_axes property

Original axes of the data.

Returns:

  • str

    Axis order string (e.g. STCZYX).

original_data_shape property

Original shape of the data.

Returns:

  • tuple of int

    Shape in original axis order.

__init__(source, axes, data_shape, data_dtype, read_func, read_kwargs=None, original_data_shape=None)

Constructor.

This implementation is aimed at representing a single file from a set of multi-file datasets, where the entire dataset cannot be loaded into memory at once. The data is therefore only loaded when the load method is called, and internal reference is deleted upon calling the close method.

Parameters:

  • source (Path) –

    Path to the file.

  • axes (str) –

    Axis order (e.g. STCZYX).

  • data_shape (tuple of int) –

    Shape in SC(Z)YX order after transformation.

  • data_dtype (DTypeLike) –

    Type of the data.

  • read_func (ReadFunc) –

    Function to read the file into an array.

  • read_kwargs (dict or Any, default: None ) –

    Extra keyword arguments passed to read_func.

  • original_data_shape (tuple of int or None, default: None ) –

    Shape in original axis order before transformation.

close()

Remove the internal reference to the data to clear up memory.

extract_patch(sample_idx, channels, coords, patch_size)

Extract a patch for a given sample and channels within the image stack.

Parameters:

  • sample_idx (int) –

    Sample index.

  • channels (sequence of int or None) –

    Channel indices to extract. If None, all channels will be extracted.

  • coords (sequence of int) –

    Spatial coordinates of the top-left corner of the patch.

  • patch_size (sequence of int) –

    Size of the patch in each spatial dimension.

Returns:

  • ndarray

    A patch of the image data from a particular sample with dimensions C(Z)YX.

from_tiff(path, axes) classmethod

Construct the ImageStack from a TIFF file.

Parameters:

  • path (Path) –

    Path to the TIFF file.

  • axes (str) –

    The original axes of the data, must be a subset of STCZYX.

Returns:

  • Self

    The ImageStack with the underlying data being from a TIFF file.

load()

Load the data stored in a file.

ImageStack

Bases: Protocol

An interface for extracting patches from an image stack.

Attributes:

data_dtype property

Data type of the image data.

data_shape property

Shape of the image data (SC(Z)YX).

original_axes property

Original axes of the data.

original_data_shape property

Original shape of the data.

source property

Source of the image data.

extract_patch(sample_idx, channels, coords, patch_size)

Extract a patch for a given sample and channels within the image stack.

Parameters:

  • sample_idx (int) –

    Sample index.

  • channels (sequence of int or None) –

    Channel indices to extract. If None, all channels will be extracted.

  • coords (sequence of int) –

    Spatial coordinates of the top-left corner of the patch.

  • patch_size (sequence of int) –

    Size of the patch in each spatial dimension.

Returns:

  • ndarray

    A patch of the image data from a particular sample with dimensions C(Z)YX.

InMemoryImageStack

ImageStack with data already loaded in memory.

Parameters:

  • source (Path or array) –

    Origin of the data, either a path to a file or the string "array" for numpy arrays.

  • data (ndarray) –

    Array with axes SC(Z)YX.

  • original_axes (str or None, default: None ) –

    Axis in original order.

  • original_data_shape (tuple of int or None, default: None ) –

    Shape in original axis order.

original_axes property

Original axes of the data.

Returns:

  • str

    Axis order string.

original_data_shape property

Original shape of the data.

Returns:

  • tuple of int

    Shape in original axis order.

__init__(source, data, original_axes=None, original_data_shape=None)

Constructor.

Parameters:

  • source (Path or array) –

    Origin of the data, either a path to a file or the string "array" for numpy arrays.

  • data (ndarray) –

    Array with axes SC(Z)YX.

  • original_axes (str or None, default: None ) –

    Axis in original order.

  • original_data_shape (tuple of int or None, default: None ) –

    Shape in original axis order.

extract_patch(sample_idx, channels, coords, patch_size)

Extract a patch for a given sample and channels within the image stack.

Parameters:

  • sample_idx (int) –

    Sample index.

  • channels (sequence of int or None) –

    Channel indices to extract. If None, all channels will be extracted.

  • coords (sequence of int) –

    Spatial coordinates of the top-left corner of the patch.

  • patch_size (sequence of int) –

    Size of the patch in each spatial dimension.

Returns:

  • ndarray

    A patch of the image data from a particular sample with dimensions C(Z)YX.

from_array(data, axes) classmethod

Construct an in-memory stack from an array.

Parameters:

  • data (ndarray) –

    Array (any axis order).

  • axes (str) –

    Axis order of the data.

Returns:

  • Self

    In-memory stack.

from_custom_file_type(path, axes, read_func, **read_kwargs) classmethod

Build an in-memory stack from a custom file type.

Parameters:

  • path (Path) –

    Path to file.

  • axes (str) –

    Axis order of the data.

  • read_func (ReadFunc) –

    Function to read the file.

  • **read_kwargs (Any, default: {} ) –

    Additional keyword arguments passed to read_func.

Returns:

  • Self

    In-memory stack.

from_tiff(path, axes) classmethod

Build an in-memory stack from a TIFF file.

Parameters:

  • path (Path) –

    Path to TIFF file.

  • axes (str) –

    Axis order of the data.

Returns:

  • Self

    In-memory stack.

ZarrImageStack

ImageStack backed by a zarr array.

Parameters:

  • group (Group) –

    Zarr group containing the array.

  • data_path (str) –

    Path to the array within the group.

  • axes (str) –

    Axis order (e.g. STCZYX).

chunks property

Chunk size per dimension.

Returns:

data_dtype property

Data type of the array.

Returns:

  • DTypeLike

    Type of the data.

original_axes property

Original axes of the data.

Returns:

  • str

    Axis order string.

original_data_shape property

Original shape of the data.

Returns:

  • tuple of int

    Shape in original axis order.

shards property

Shard size per dimension.

Returns:

  • Sequence[int] or None

    Shard size per dimension, or None.

source property

Source URI of the zarr array.

Local zarr URIs starts with the file:// descriptor, and include the path to the zarr file and internal path to the specific array. Source URIs are used during prediction to disk to build destination paths.

Returns:

  • str

    Source URI.

__init__(group, data_path, axes)

Constructor.

Parameters:

  • group (Group) –

    Zarr group containing the array.

  • data_path (str) –

    Path to the array within the group.

  • axes (str) –

    Axis order (e.g. STCZYX).

extract_patch(sample_idx, channels, coords, patch_size)

Extract a patch for a given sample and channels within the image stack.

Parameters:

  • sample_idx (int) –

    Sample index.

  • channels (sequence of int or None) –

    Channel indices to extract. If None, all channels will be extracted.

  • coords (sequence of int) –

    Spatial coordinates of the top-left corner of the patch.

  • patch_size (sequence of int) –

    Size of the patch in each spatial dimension.

Returns:

  • ndarray

    A patch of the image data from a particular sample with dimensions C(Z)YX.