tlambert03 / nd2

Full-featured nd2 (Nikon NIS Elements) file reader for python. Outputs to numpy, dask, and xarray. Exhaustive metadata extraction
https://tlambert03.github.io/nd2
BSD 3-Clause "New" or "Revised" License
53 stars 15 forks source link

feat: Add `ND2File.binary_data` property - extract binary layers from file #108

Closed tlambert03 closed 1 year ago

tlambert03 commented 1 year ago

figured out how to decode the binary data in an nd2 file

Info below also present in the readme for anyone who stumbles on this PR:


The ND2File.binary_data property returns an nd2.BinaryLayers object representing all of the binary masks in the nd2 file.

A nd2.BinaryLayers object is a sequence of individual nd2.BinaryLayer objects (one for each binary layer found in the file). Each BinaryLayer in the sequence is a named tuple that has, among other things, a name attribute, and a data attribute that is list of numpy arrays (one for each frame in the experiment) or None if the binary layer had no data in that frame.

The most common use case will be to cast either the entire BinaryLayers object or an individual BinaryLayer to a numpy.ndarray:

>>> import nd2
>>> nd2file = nd2.ND2File('path/to/file.nd2')
>>> binary_layers = nd2file.binary_data

# The output array will have shape
# (n_binary_layers, *coord_shape, *frame_shape).
>>> np.asarray(binary_layers)

For example, if the data in the nd2 file has shape (nT, nZ, nC, nY, nX), and there are 4 binary layers, then the output of np.asarray(nd2file.binary_data) will have shape (4, nT, nZ, nY, nX). (Note that the nC dimension is not present in the output array, and the binary layers are always in the first axis).

You can also cast an individual BinaryLayer to a numpy array:

>>> binary_layer = binary_layers[0]
>>> np.asarray(binary_layer)