2. I/O#
Functions to help with loading and saving data.
- mbo_utilities.save_as(scan, savedir: PathLike, planes: list | tuple = None, metadata: dict = None, overwrite: bool = True, append_str: str = '', ext: str = '.tiff', order: list | tuple = None, trim_edge: list | tuple = (0, 0, 0, 0), fix_phase: bool = False, summary: bool = False)[source]#
Save scan data to the specified directory in the desired format.
- Parameters:
- scanscanreader.ScanMultiROI
An object representing scan data. Must have attributes such as num_channels, num_frames, fields, and rois, and support indexing for retrieving frame data.
- savediros.PathLike
Path to the directory where the data will be saved.
- planesint, list, or tuple, optional
Plane indices to save. If None, all planes are saved. Default is None.
- trim_edgelist, optional
Number of pixels to trim on each W x H edge. (Left, Right, Top, Bottom). Default is (0,0,0,0).
- metadatadict, optional
Additional metadata to update the scan object’s metadata. Default is None.
- overwritebool, optional
Whether to overwrite existing files. Default is True.
- append_strstr, optional
String to append to the file name. Default is ‘’.
- extstr, optional
File extension for the saved data. Supported options are .tiff, .zarr and .h5. Default is ‘.tiff’.
- orderlist or tuple, optional
A list or tuple specifying the desired order of planes. If provided, the number of elements in order must match the number of planes. Default is None.
- fix_phasebool, optional
Whether to fix scan-phase (x/y) alignment. Default is False.
- summarybool, optional
Whether to save updated vmin/vmax in metadata. Experimental. Default is False.
- Raises:
- ValueError
If an unsupported file extension is provided.
- mbo_utilities.get_files(base_dir, str_contains='', max_depth=1, sort_ascending=True, exclude_dirs=None) list | Path [source]#
Recursively search for files in a specified directory whose names contain a given substring, limiting the search to a maximum subdirectory depth. Optionally, the resulting list of file paths is sorted in ascending order using numeric parts of the filenames when available.
- Parameters:
- base_dirstr or Path
The base directory where the search begins. This path is expanded (e.g., ‘~’ is resolved) and converted to an absolute path.
- str_containsstr, optional
A substring that must be present in a file’s name for it to be included in the result. If empty, all files are matched.
- max_depthint, optional
The maximum number of subdirectory levels (relative to the base directory) to search. Defaults to 1. If set to 0, it is automatically reset to 1.
- sort_ascendingbool, optional
If True (default), the matched file paths are sorted in ascending alphanumeric order. The sort key extracts numeric parts from filenames so that, for example, “file2” comes before “file10”.
- exclude_dirsiterable of str or Path, optional
An iterable of directories to exclude from the resulting list of file paths. By default will exclude “.venv/”, “__pycache__/”, “.git” and “.github”].
- Returns:
- list of str
A list of full file paths (as strings) for files within the base directory (and its subdirectories up to the specified depth) that contain the provided substring.
- Raises:
- FileNotFoundError
If the base directory does not exist.
- NotADirectoryError
If the specified base_dir is not a directory.
Examples
>>> import mbo_utilities as mbo >>> # Get all files that contain "ops.npy" in their names by searching up to 3 levels deep: >>> ops_files = mbo.get_files("path/to/files", "ops.npy", max_depth=3) >>> # Get only files containing "tif" in the current directory (max_depth=1): >>> tif_files = mbo.get_files("path/to/files", "tif")
- mbo_utilities.npy_to_dask(files, name='', axis=1, astype=None)[source]#
Creates a Dask array that lazily stacks multiple .npy files along a specified axis without fully loading them into memory.
- Parameters:
- fileslist of str or Path
A list of file paths pointing to .npy files containing array data. Each file must have the same shape except possibly along the concatenation axis.
- namestr, optional
A string to be appended to a base name (“from-npy-stack-”) to label the resulting Dask array. Default is an empty string.
- axisint, optional
The axis along which to stack/concatenate the arrays from the provided files. Default is 1.
- astypenumpy.dtype, optional
If provided, the resulting Dask array will be cast to this data type. Otherwise, the data type is inferred from the first file.
- Returns:
- dask.array.Array
Examples
>>> # https://www.fastplotlib.org/ >>> import fastplotlib as fpl >>> import mbo_utilities as mbo >>> files = mbo.get_files("path/to/images/", 'fused', 3) # suite3D output >>> arr = npy_to_dask(files, name="stack", axis=1) >>> print(arr.shape) (nz, nt, ny, nx ) >>> # Optionally, cast the array to float32 >>> arr = npy_to_dask(files, axis=1, astype=np.float32) >>> fpl.ImageWidget(arr.transpose(1, 0, 2, 3)).show()
- mbo_utilities.zstack_from_files(files: list, proj='mean')[source]#
Creates a Z-Stack image by applying a projection to each TIFF file in the provided list and stacking the results into a NumPy array.
- Parameters:
- fileslist of str or Path
A list of file paths to TIFF images. Files whose extensions are not ‘.tif’ or ‘.tiff’ are ignored.
- projstr, optional
The type of projection to apply to each TIFF image. Valid options are ‘mean’, ‘max’, and ‘std’. Default is ‘mean’.
- Returns:
- numpy.ndarray
A stacked array of projected images with the new dimension corresponding to the file order. For example, for N input files, the output shape will be (N, height, width).
- Raises:
- ValueError
If an unsupported projection type is provided.
Examples
>>> import mbo_utilities as mbo >>> files = mbo.get_files("/path/to/files", "tif") >>> z_stack = mbo.zstack_from_files(files, proj="max") >>> z_stack.shape # (3, height, width)