Skip to content

Nd2 module

This module documents the core Nd2Reader/Nd2Writer APIs. For the ND2File compatibility layer (Talley Lambert’s nd2 interface), see docs/nd2file.md.

Nd2Reader

Nd2Reader(file: FileLikeObject, *, chunker_kwargs: dict = {})

High-level class for accessing .nd2 data format. Especially attributes, metadata, properties, image, binary data as in NIS-Elements. This class relies on chunker classes (legacy JPEG2000 and modern ND2). The chunker classes are backed by stores abstracting the storage media (disk, memory).

Also see Quickstart for an example of how to use this class and how to read individual chunks, attributes, metadata and so on.

PARAMETER DESCRIPTION
file

Filename of the ND2 file.

TYPE: str | Path | Store | BinaryIO | memoryview

chunker_kwargs

Additional parameters for chunker.

TYPE: dict DEFAULT: {}

experiment property

experiment: ExperimentLevel | None

Attribute to get experiments in an .nd2 file.

See ExperimentLevel class for more information.

In order to create an instance of ExperimentLevel class, use ExperimentFactory class.

imageAttributes property

imageAttributes: ImageAttributes

Attribute to get attributes of an .nd2 file.

See ImageAttributes class for more information.

In order to create an instance of ImageAttributes class from simple parameters, use ImageAttributes.create method.

imageDataCalibration cached property

imageDataCalibration: tuple[float, float, float, float, float, float]

Returns 6D canonical data calibration (T in ms, 0, Z in um, Y in um, X in um, 0) 0 is for uncalibrated.

imageDataShape cached property

imageDataShape: tuple[int, int, int, int, int, int]

Returns 6D canonical data shape (T, M, Z, Y, X, C).

is3d cached property

is3d: bool

Returns True if the file contains valid z-stack, otherwise False.

is8bitRgb cached property

is8bitRgb: bool

Returns True if the file contains 8-bit RGB data, otherwise False.

isFloat cached property

isFloat: bool

Returns True if the file data is 32-bit float, otherwise False.

isMono cached property

isMono: bool

Returns True if the file contains only one component, otherwise False.

isRgb cached property

isRgb: bool

Returns True if the file contains RGB data, otherwise False.

pictureMetadata property

pictureMetadata: PictureMetadata

Attribute to get metadata of an .nd2 file.

See PictureMetadata class for more information.

In order to create an instance of PictureMetadata class, use MetadataFactory class.

results cached property

results: dict[str, ResultItem]

Returns a dictionary of all results in the accompanying .h5 file.

Each result potentially contains tabular results (tables, graphs, ...) and binary layers.

store property

store: Store

Returns the backing store (abstraction of the storage medium).

version property

version: tuple[int, int]

Returns the version of the .nd2 file as a tuple of two integers.

(1, 0) - JPEG2000 legacy file format (2, 0) - ND2 metadata stored in Variant as xml (3, 0) - ND2 metadata stored in LiteVariant as proprietary binary format

binaryRasterData

binaryRasterData(bin_id: int, seq_index: int, *, rect: tuple[int, int, int, int] | None = None, downsample_level: int = 0) -> NumpyArrayLike

Returns specific 2D binary data as numpy.ndarray.

PARAMETER DESCRIPTION
bin_id

Binary layer ID. Some files use 0 as a valid layer id.

TYPE: int

seq_index

Zero-based sequence index of the frame.

TYPE: int

rect

Rectangle (x, y, w, h) of the image (always in original resolution).

TYPE: tuple[int, int, int, int] | None DEFAULT: None

downsample_level

Determines downsampling d = 2^downsample_level that produces lower level frames of size (w // d, h // d).

TYPE: int DEFAULT: 0

chunk

chunk(name: bytes | str) -> bytes | memoryview | None

Returns data for specific chunk name

PARAMETER DESCRIPTION
name

Name of the chunk to retrieve.

TYPE: bytes | str

Notes

This is a thin passthrough to the underlying chunker and may be removed in a future API cleanup.

crestDeepSimRawData

crestDeepSimRawData(seqindex: int, component_index: int) -> tuple[NumpyArrayLike, str, str, tuple[float, float], tuple[int, int], tuple[int, int]]

This method retrieves deepSIM data for a specific sequence index and component.

The data is returned as a tuple containing deepSIM data (see Returns section below).

Warning

Even if file contains deepSIM data, not all channels or sequence indices must have deepSim data, use crestDeepSimRawDataIndices() method to see all valid indices for deepSIM data.

Reading all deepSIM data can be done using following code:

file = "deepSIM.nd2"

with limnd2.Nd2Reader(file) as nd2:
    results = {}
    for indices in nd2.crestDeepSimRawDataIndices():
        results[indices] = nd2.crestDeepSimRawData(*indices)

    for i, r in results.items():
        print(f"Input indices: sequence index: {i[0]}, component index: {i[1]}")
        print("    Final image: (shape)", r[0].shape)
        print("    Calibration key:", r[1])
        print("    Calibration data: (length of XML)", len(r[2]))
        print("    PSF: (set, default)", r[3])
        print("    Iter: (set, default)", r[4])
        print("    ROI offsets: (x, y)", r[5])

See example output
Input indices: sequence index: 0, component index: 0
    Final image: (shape) (65, 1024, 1024)
    Calibration key: zoom60000_na1400_ex561_pitch15000_size1500_im65_tm0
    Calibration data: (length of XML) 880341
    PSF: (set, default) (2.0, 2.0)
    Iter: (set, default) (25, 25)
    ROI offsets: (x, y) (0, 0)
Input indices: sequence index: 0, component index: 1
    Final image: (shape) (65, 1024, 1024)
    Calibration key: zoom60000_na1400_ex488_pitch15000_size1500_im65_tm0
    Calibration data: (length of XML) 884538
    PSF: (set, default) (2.0, 2.0)
    Iter: (set, default) (25, 25)
    ROI offsets: (x, y) (0, 0)
Input indices: sequence index: 1, component index: 0
    Final image: (shape) (65, 1024, 1024)
...
PARAMETER DESCRIPTION
seqindex

The index of the sequence for which the deepSIM data is being retrieved.

TYPE: int

component_index

The index of the component for which the deepSIM data is requested.

TYPE: str

RETURNS DESCRIPTION
ndarray

A 3D array of deepSIM image data with shape (channel_count, height, width).

str

A string that contains the significant calibration data in compressed form, for example zoom60000_na1400_ex561_pitch15000_size1500_im65_tm0.

str

DeepSIM data detailed outcome in XML Format as string.

tuple[float, float]

PSF values (used, default). Depends on the objective used.

tuple[int, int]

Number of iterations for reconstruction (used, default).

tuple[int, int]

ROI width and height listed in ndarray (x, y).

RAISES DESCRIPTION
NameNotInChunkmapError

If chunk with given sequence and component index is missing.

crestDeepSimRawDataIndices

crestDeepSimRawDataIndices() -> list[tuple[int, int]]

Returns all valid indices for deepSIM data in the .nd2 file.

Indices are returned as tuples of (sequence_index, component_index) in a list.

See crestDeepSimRawData() method that uses those indices to retrieve deepSIM data.

delayedImageData

delayedImageData(*, tiling: tuple[int, int] | None = None) -> Any

Returns 6D canonical data shape (T, M, Z, Y, X, C) dask array with delayed chunks.

PARAMETER DESCRIPTION
tiling

Optional frame tiling x, y.

TYPE: tuple[int, int] | None DEFAULT: None

dimensionSizes

dimensionSizes(skipSpectralLoop=True) -> dict[str, int]

Returns a dictionary with dimension names as keys and their sizes as values.

TODO: consider replacing it with fixed order tuple

generateLoopIndexes

generateLoopIndexes(*, named: bool = False, dimnames: list[str] | None = None) -> list

Generates indexes for all loops in the experiment.

TODO: consider using fixed order tuples [T, M, Z]

image

image(seq_index: int, *, rect: tuple[int, int, int, int] | None = None, downsample_level: int = 0) -> NumpyArrayLike

Returns specific 2D image frame as numpy.ndarray.

PARAMETER DESCRIPTION
seq_index

Zero-based sequence index of the frame.

TYPE: int

rect

Rectangle (x, y, w, h) specifying a portion of the resulting image.

TYPE: tuple[int, int, int, int] | None DEFAULT: None

downsample_level

Determines downsampling d = 2^downsample_level that produces lower level frames of size (w // d, h // d).

TYPE: int DEFAULT: 0

resultSizeOnDisk

resultSizeOnDisk(result_name: str) -> int | None

Returns size of the result.

to_ome_zarr

to_ome_zarr(path: str | Path, *, min_layer_size: int = 1024, chunks: tuple[int, int, int, int, int] = (1, 1, 1, 512, 512), shard_shape: tuple[int, int, int, int, int] | None = None, position: int | None = None, use_dask: bool | None = None, progress_callback: Callable[[int, int, str], None] | None = None, include_binaries: bool = False, include_well_info: bool = True, overwrite: bool = False) -> str | Path

Export this ND2 file to OME-Zarr.

Multipoint/XY positions are written as separate image groups. Each group stores a conventional 5D OME-NGFF array with axes t, c, z, y, x.

Nd2Writer

Nd2Writer(file: FileLikeObject, *, append: bool | None = None, chunker_kwargs: dict = {})

ND2 file writer.

Supports encoding of all image attributes, most commonly used experiments and most of image metadata. Wellplate support is available through dedicated writer helpers (setWellplateDesc, setWellplateFrameInfo, setWellplate) that write raw wellplate chunks. Writing binary layers, ROIs and generic custom text/data chunks is still not covered by high-level APIs.

Info

Data is written in chunks, so you can write data in any order you want, image data however can only be written after image attributes are set, if you write same chunk multiple times, all chunks will be saved, however only the last one will be used.

Tip

As explained in Quickstart, image data can only be written after image attributes are set, but if you want to write image data into .nd2 file without knowing how many frames there is (for example with continuous writing), you can pass ImageAttributes instance when creating .nd2 using custom chunker argument as shown below.

Setting ImageAttributes this way will not store them in .nd2 file and you still have to store them at some point, however you can do so after you know how many frames there is.

Example os using chunker arguments to set image attributes
attributes = limnd2.attributes.ImageAttributes.create(
    width = WIDTH,
    height = HEIGHT,
    component_count = COMPONENT_COUNT,
    bits = BITS,
    sequence_count = ...  # will be set later
)

with limnd2.Nd2Writer("outfile.nd2", chunker_kwargs={"with_image_attributes": attributes}) as nd2:
    # you can now set image data without setting attributes

See Quickstart for an example of how to use this class and how to write individual chunks.

PARAMETER DESCRIPTION
file

Filename of the ND2 file.

TYPE: str | Path | Store | BinaryIO | memoryview

chunker_kwargs

Additional parameters for chunker.

TYPE: dict DEFAULT: {}

experiment property writable

experiment: ExperimentLevel | None

Attribute to get or set experiments in an .nd2 file.

See ExperimentLevel class for more information.

In order to create an instance of ExperimentLevel class, use ExperimentFactory class.

imageAttributes property writable

imageAttributes: ImageAttributes

Attribute to get or set attributes of an .nd2 file.

See ImageAttributes class for more information.

In order to create an instance of ImageAttributes class from simple parameters, use ImageAttributes.create method.

pictureMetadata property writable

pictureMetadata: PictureMetadata

Attribute to get or set metadata of an .nd2 file.

See PictureMetadata class for more information.

In order to create an instance of PictureMetadata class, use MetadataFactory class.

finalize

finalize() -> None

Explicitly finalize the file, this is not needed if you use with statement.

setImage

setImage(seq_index: int, data: NumpyArrayLike) -> None

Set image data using specified frame index.

Warning

You must manually keep track of the frame index and make sure that you are not overwriting the same frame multiple times and that images are written sequentially.

setWellplate

setWellplate(*, desc: WellplateDesc | dict[str, Any] | None = None, frame_info: WellplateFrameInfo | list[dict[str, Any] | Any] | None = None) -> None

Convenience helper for writing both wellplate descriptor and frame info chunks.

setWellplateDesc

setWellplateDesc(desc: WellplateDesc | dict[str, Any]) -> None

Write wellplate descriptor chunk (CustomData|WellPlateDesc_0!).

setWellplateFrameInfo

setWellplateFrameInfo(frame_info: WellplateFrameInfo | list[dict[str, Any] | Any]) -> None

Write wellplate frame info chunk (CustomData|WellPlateFrameInfoZJSON!).