### Install LIF Support Manually Source: https://github.com/allencellmodeling/aicsimageio/blob/main/docs/index.md Install AICSImageIO with LIF format support. This requires manual installation due to GPL licensing and includes `readlif`. ```bash pip install aicsimageio readlif>=0.6.4 ``` -------------------------------- ### Install aicsimageio from source Source: https://github.com/allencellmodeling/aicsimageio/blob/main/docs/INSTALLATION.md Run this command after downloading or cloning the source code to perform the installation. ```console $ python setup.py install ``` -------------------------------- ### Install CZI Support Manually Source: https://github.com/allencellmodeling/aicsimageio/blob/main/docs/index.md Install AICSImageIO with CZI format support. This requires manual installation due to GPL licensing and includes `aicspylibczi` and `fsspec`. ```bash pip install aicsimageio aicspylibczi>=3.1.1 fsspec>=2022.8.0 ``` -------------------------------- ### Install project dependencies Source: https://github.com/allencellmodeling/aicsimageio/blob/main/docs/CONTRIBUTING.md Installs the project in editable mode with development dependencies. ```bash cd aicsimageio/ pip install -e ".[dev]" ``` -------------------------------- ### Install Extra Format Support (bfio) Source: https://github.com/allencellmodeling/aicsimageio/blob/main/docs/index.md Install AICSImageIO with bfio support for faster OME-TIFF reading using tile tags. ```bash pip install aicsimageio[bfio] ``` -------------------------------- ### Install Bio-Formats Support Manually Source: https://github.com/allencellmodeling/aicsimageio/blob/main/docs/index.md Install AICSImageIO with Bio-Formats support. This requires manual installation due to GPL licensing and includes `bioformats_jar`. Java and Maven are also required. ```bash pip install aicsimageio bioformats_jar ``` -------------------------------- ### Quickstart: Load Image if it Fits in Memory Source: https://github.com/allencellmodeling/aicsimageio/blob/main/docs/index.md Basic usage of AICSImageIO to load an image file when the entire image can fit into memory. Imports the AICSImage class. ```python from aicsimageio import AICSImage ``` -------------------------------- ### Install Extra Format Support (ND2) Source: https://github.com/allencellmodeling/aicsimageio/blob/main/docs/index.md Install AICSImageIO with support for the ND2 format. This requires the `[nd2]` extra. ```bash pip install aicsimageio[nd2] ``` -------------------------------- ### Install aicsimageio Pre-release Source: https://github.com/allencellmodeling/aicsimageio/blob/main/presentations/2021-dask-life-sciences/presentation.ipynb Installs the pre-release version of the aicsimageio library, which is recommended for use with newer features. ```bash pip install aicsimageio --pre ``` -------------------------------- ### Install AICSImageIO Development Head Source: https://github.com/allencellmodeling/aicsimageio/blob/main/docs/index.md Install the latest development version of AICSImageIO directly from its GitHub repository. ```bash pip install git+https://github.com/AllenCellModeling/aicsimageio.git ``` -------------------------------- ### Install All Openly Licensed Extra Formats Source: https://github.com/allencellmodeling/aicsimageio/blob/main/docs/index.md Install AICSImageIO with support for all additional openly licensed formats using the `[all]` extra. ```bash pip install aicsimageio[all] ``` -------------------------------- ### Install pre-commit hooks Source: https://github.com/allencellmodeling/aicsimageio/blob/main/docs/CONTRIBUTING.md Sets up automated linting checks before every commit. ```bash pip install pre-commit pre-commit install ``` -------------------------------- ### Install Bio-Formats Support via Conda Source: https://github.com/allencellmodeling/aicsimageio/blob/main/docs/index.md Install Bio-Formats support for AICSImageIO using Conda, which also installs necessary Java and Maven packages. ```bash conda install -c conda-forge bioformats_jar ``` -------------------------------- ### Install Multiple Extra Formats Source: https://github.com/allencellmodeling/aicsimageio/blob/main/docs/index.md Install AICSImageIO with support for multiple additional formats, such as base-imageio and ND2. ```bash pip install aicsimageio[base-imageio,nd2] ``` -------------------------------- ### Install aicsimageio via pip Source: https://github.com/allencellmodeling/aicsimageio/blob/main/docs/INSTALLATION.md Use this command to install the most recent stable release of the library. ```console $ pip install aicsimageio ``` -------------------------------- ### Install Extra Format Support (ND2) - Development Head Source: https://github.com/allencellmodeling/aicsimageio/blob/main/docs/index.md Install the development version of AICSImageIO with ND2 support. The package name is specified with the `@ git+...` syntax. ```bash pip install "aicsimageio[nd2] @ git+https://github.com/AllenCellModeling/aicsimageio.git" ``` -------------------------------- ### Install Extra Format Support (ND2) - Specific Tag Source: https://github.com/allencellmodeling/aicsimageio/blob/main/docs/index.md Install a specific tagged version of AICSImageIO with ND2 support. Use the `@tag_name` syntax. ```bash pip install "aicsimageio[nd2] @ git+https://github.com/AllenCellModeling/aicsimageio.git@v4.0.0.dev6" ``` -------------------------------- ### List and Change Scenes in AICSImage Source: https://context7.com/allencellmodeling/aicsimageio/llms.txt Demonstrates how to list available scenes, get the current scene, change scenes by name or index, and access scene data. Useful for multi-scene image files. ```python print(f"Available scenes: {img.scenes}") # ('Image:0', 'Image:1', 'Image:2') print(f"Current scene: {img.current_scene}") # 'Image:0' print(f"Current scene index: {img.current_scene_index}") # 0 # Change scene by name img.set_scene("Image:1") print(f"New current scene: {img.current_scene}") # 'Image:1' data_scene1 = img.data # Data from scene 1 # Change scene by index img.set_scene(2) print(f"Scene by index: {img.current_scene}") # 'Image:2' data_scene2 = img.data # Iterate through all scenes for scene_id in img.scenes: img.set_scene(scene_id) print(f"Scene {scene_id}: shape={img.shape}, channels={img.channel_names}") ``` ```python # Stack all scenes into single array stack = img.get_stack() # 6D numpy array with Scene as first dimension print(f"Stack shape: {stack.shape}") # (3, 1, 4, 20, 1024, 1024) # Dask stack for lazy loading dask_stack = img.get_dask_stack() # XArray stack with labels xarray_stack = img.get_xarray_stack() xarray_dask_stack = img.get_xarray_dask_stack() ``` -------------------------------- ### Single Tile Absolute Positioning Source: https://github.com/allencellmodeling/aicsimageio/blob/main/docs/index.md Helper functions are available on `AICSImage` and `Reader` objects for single tile positioning. `.mosaic_tile_dims` provides Y and X dimensions of a single tile, and `.get_mosaic_tile_position()` returns the start indices for a given tile. ```python img = AICSImage("very-large-mosaic.lif") img.mosaic_tile_dims # Returns a Dimensions object with just Y and X dim sizes img.mosaic_tile_dims.Y # 512 (for example) # Get the tile start indices (top left corner of tile) y_start_index, x_start_index = img.get_mosaic_tile_position(12) ``` -------------------------------- ### Scene Navigation Source: https://github.com/allencellmodeling/aicsimageio/blob/main/docs/index.md You can access and change the current scene of an AICSImage object. Use `.current_scene` to get the ID of the current scene, `.scenes` to list all available scene IDs, and `.set_scene()` to switch to a different scene by name or index. ```python # Get the id of the current operating scene img.current_scene # Get a list valid scene ids img.scenes # Change scene using name img.set_scene("Image:1") # Or by scene index img.set_scene(1) ``` -------------------------------- ### Read Images from Cloud Storage with fsspec Source: https://context7.com/allencellmodeling/aicsimageio/llms.txt Access images stored in cloud services like AWS S3 and Google Cloud Storage using fsspec. Requires installation of specific fsspec backends (e.g., s3fs, gcsfs). Supports anonymous and authenticated access. ```python from aicsimageio import AICSImage # Read from HTTP URL img = AICSImage("https://example.com/images/sample.tiff") data = img.data # Read from AWS S3 # Requires: pip install s3fs img = AICSImage("s3://my-bucket/path/to/image.ome.tiff") # With anonymous access for public buckets img = AICSImage( "s3://my-bucket/public/image.tiff", fs_kwargs={"anon": True} ) # With explicit credentials img = AICSImage( "s3://my-bucket/private/image.tiff", fs_kwargs={ "key": "YOUR_ACCESS_KEY", "secret": "YOUR_SECRET_KEY" } ) # Read from Google Cloud Storage # Requires: pip install gcsfs img = AICSImage("gcs://my-bucket/path/to/image.nd2") # With anonymous access img = AICSImage( "gcs://my-bucket/public/image.tiff", fs_kwargs={"token": "anon"} ) # All normal operations work with remote files print(f"Shape: {img.shape}") print(f"Channels: {img.channel_names}") lazy_data = img.dask_data # Efficient lazy loading from cloud subset = img.get_image_dask_data("ZYX", T=0, C=0) result = subset.compute() # Only transfers required data ``` -------------------------------- ### Clone the repository Source: https://github.com/allencellmodeling/aicsimageio/blob/main/docs/CONTRIBUTING.md Initial step to obtain a local copy of the project. ```bash git clone https://{your_name_here}@github.com/aicsimageio.git ``` -------------------------------- ### Run build and test suites Source: https://github.com/allencellmodeling/aicsimageio/blob/main/docs/CONTRIBUTING.md Commands to verify changes using local build tools and tox environments. ```bash make build ``` ```bash make build-with-remote ``` ```bash tox -e py ``` ```bash tox -e lif tox -e bfio tox -e czi ``` -------------------------------- ### Configure AWS and file paths Source: https://github.com/allencellmodeling/aicsimageio/blob/main/scripts/makezarr.ipynb Set up environment variables for AWS authentication and define target file paths. ```python # set up some initial vars to find our data and where to put it filepath = "my/path/to/data/file.tif" output_filename = "my_filename" output_bucket = "my_bucket" # aws config os.environ["AWS_PROFILE"] = "my_creds" os.environ["AWS_DEFAULT_REGION"] = "us-west-2" ``` -------------------------------- ### Download test resources Source: https://github.com/allencellmodeling/aicsimageio/blob/main/docs/CONTRIBUTING.md Downloads necessary files for running the test suite. ```bash python scripts/download_test_resources.py ``` -------------------------------- ### Initialize Dask Local Cluster and Client Source: https://github.com/allencellmodeling/aicsimageio/blob/main/presentations/2021-dask-life-sciences/presentation.ipynb Sets up a local Dask cluster and client for distributed computing. This is useful for accelerating computations. ```python from distributed import Client, LocalCluster cluster = LocalCluster() client = Client(cluster) ``` -------------------------------- ### Initialize submodules Source: https://github.com/allencellmodeling/aicsimageio/blob/main/docs/CONTRIBUTING.md Ensures all project submodules are correctly initialized and updated. ```bash git submodule update --init --recursive ``` -------------------------------- ### Execute Version Bump and Push Source: https://github.com/allencellmodeling/aicsimageio/blob/main/docs/CONTRIBUTING.md Apply the version change and push tags to trigger the automated PyPI release. ```bash bumpversion ${VERSION_CHANGE} git push git push --tags ``` -------------------------------- ### Clone aicsimageio source repository Source: https://github.com/allencellmodeling/aicsimageio/blob/main/docs/INSTALLATION.md Clone the repository and initialize submodules to work with the source code. ```console $ git clone git://github.com/AllenCellModeling/aicsimageio $ git submodule update --init --recursive ``` -------------------------------- ### Visualize data with nbvv Source: https://github.com/allencellmodeling/aicsimageio/blob/main/scripts/makezarr.ipynb Use nbvv to display the loaded OME-Zarr data volume. ```python import nbvv level = 1 levelxyscale = 2**(level+1) t = 0 readdata = node.data[level][t][0:2].compute() print(readdata.shape) nbvv.volshow(readdata, spacing=(img.physical_pixel_sizes.X*levelxyscale, img.physical_pixel_sizes.Y*levelxyscale, img.physical_pixel_sizes.Z)) ``` -------------------------------- ### Perform Dry Run Version Bump Source: https://github.com/allencellmodeling/aicsimageio/blob/main/docs/CONTRIBUTING.md Prepare the repository and verify version changes without applying them. ```bash git checkout main git stash git pull export VERSION_CHANGE=? # NOTE: Specify either major, minor, or patch bumpversion ${VERSION_CHANGE} --dry-run --verbose ``` -------------------------------- ### Initialize AICSImage and Access Readers Source: https://context7.com/allencellmodeling/aicsimageio/llms.txt Demonstrates loading images via glob patterns, accessing the underlying reader object, and listing supported file formats. ```python img = AICSImage("frames_*.tiff") reader = TiffGlobReader(["z_00.tiff", "z_01.tiff", "z_02.tiff"]) print(f"Combined shape: {reader.shape}") # Access underlying reader from AICSImage aics_img = AICSImage("my_file.czi") base_reader = aics_img.reader print(f"Base reader type: {type(base_reader).__name__}") # List all supported readers print(f"Supported readers: {AICSImage.SUPPORTED_READERS}") ``` -------------------------------- ### Work Directly with Reader for More Control Source: https://context7.com/allencellmodeling/aicsimageio/llms.txt Use specific readers like LifReader for more control over image data, especially for multi-dimensional images with tiles. ```python from aicsimageio.readers import CziReader, LifReader reader = LifReader("mosaic.lif") print(f"Reader dims with M: {reader.dims}") # Has M dimension for tiles tiles = reader.dask_data # Individual tiles as M dimension stitched = reader.mosaic_dask_data # Stitched mosaic ``` -------------------------------- ### Initialize Dask cluster Source: https://github.com/allencellmodeling/aicsimageio/blob/main/scripts/makezarr.ipynb Configure a local Dask cluster to enable parallel processing for image operations. ```python # allow for dask parallelism from distributed import LocalCluster, Client cluster = LocalCluster(n_workers=4, processes=True, threads_per_worker=1) client = Client(cluster) client ``` -------------------------------- ### Manage Physical Pixel Sizes Source: https://context7.com/allencellmodeling/aicsimageio/llms.txt Shows how to access, validate, and create physical pixel size metadata, and how to apply it when saving files with OmeTiffWriter. ```python from aicsimageio import AICSImage from aicsimageio.types import PhysicalPixelSizes img = AICSImage("calibrated.ome.tiff") # Access physical pixel sizes pps = img.physical_pixel_sizes print(f"Physical pixel sizes: {pps}") # PhysicalPixelSizes(Z=0.5, Y=0.108, X=0.108) # Access individual dimensions (in micrometers typically) print(f"Z step: {pps.Z} µm") # 0.5 µm print(f"Y pixel: {pps.Y} µm") # 0.108 µm print(f"X pixel: {pps.X} µm") # 0.108 µm # Handle missing values (None when not available) if pps.Z is not None: print(f"Z spacing: {pps.Z}") else: print("Z spacing not available in metadata") # Create custom PhysicalPixelSizes custom_pps = PhysicalPixelSizes(Z=1.0, Y=0.325, X=0.325) print(f"Custom: Z={custom_pps.Z}, Y={custom_pps.Y}, X={custom_pps.X}") # Use in writer from aicsimageio.writers import OmeTiffWriter import numpy as np data = np.random.rand(10, 512, 512) OmeTiffWriter.save( data, "output.ome.tiff", dim_order="ZYX", physical_pixel_sizes=PhysicalPixelSizes(Z=2.0, Y=0.65, X=0.65) ) ``` -------------------------------- ### Download aicsimageio tarball Source: https://github.com/allencellmodeling/aicsimageio/blob/main/docs/INSTALLATION.md Download the source code as a tarball from the GitHub repository. ```console $ curl -OL https://github.com/AllenCellModeling/aicsimageio/tarball/main ``` -------------------------------- ### Import AICSImageIO dependencies Source: https://github.com/allencellmodeling/aicsimageio/blob/main/scripts/makezarr.ipynb Required imports for handling image data, S3 storage, and OME-Zarr writing. ```python import os import s3fs from aicsimageio.writers import OmeZarrWriter from aicsimageio import AICSImage from aicsimageio.dimensions import DimensionNames, DEFAULT_CHUNK_DIMS import numpy ``` -------------------------------- ### Create a development branch Source: https://github.com/allencellmodeling/aicsimageio/blob/main/docs/CONTRIBUTING.md Creates a new branch for implementing features or bug fixes. ```bash git checkout -b {your_development_type}/short-description ``` -------------------------------- ### Manage Multi-Scene Images Source: https://context7.com/allencellmodeling/aicsimageio/llms.txt Handle files containing multiple scenes, common in microscopy formats. ```python from aicsimageio import AICSImage img = AICSImage("multi_position.czi") ``` -------------------------------- ### Commit and push changes Source: https://github.com/allencellmodeling/aicsimageio/blob/main/docs/CONTRIBUTING.md Standard git workflow for saving and uploading contributions. ```bash git add . git commit -m "Resolves gh-###. Your detailed description of your changes." git push origin {your_development_type}/short-description ``` -------------------------------- ### Normalize and Project Channel with Dask Source: https://github.com/allencellmodeling/aicsimageio/blob/main/presentations/2021-dask-life-sciences/presentation.ipynb Reads a TIFF image using dask-image, reshapes it, and then normalizes and projects each channel through the Z dimension. Requires dask and a norm_and_proj_channel function. ```python da_img = imread("../../aicsimageio/tests/resources/3d-cell-viewer.ome.tiff") da_img = da_img.reshape(74, 9, 1024, 1024) projs = [] for i in range(4): da_channel = da_img[:, i] projs.append(norm_and_proj_channel(da_channel)) da_projs = da.stack(projs) dask.optimize(da_projs)[0].visualize() ``` -------------------------------- ### Load Image Data into Memory Source: https://github.com/allencellmodeling/aicsimageio/blob/main/docs/index.md Use `.data` or `.xarray_data` to load the entire scene into memory. This is suitable for images that fit within available RAM. ```python from aicsimageio import AICSImage # Get an AICSImage object img = AICSImage("my_file.tiff") # selects the first scene found img.data # returns 5D TCZYX numpy array img.xarray_data # returns 5D TCZYX xarray data array backed by numpy img.dims # returns a Dimensions object img.dims.order # returns string "TCZYX" img.dims.X # returns size of X dimension img.shape # returns tuple of dimension sizes in TCZYX order img.get_image_data("CZYX", T=0) # returns 4D CZYX numpy array ``` -------------------------------- ### Metadata and Physical Pixel Size Reading Source: https://github.com/allencellmodeling/aicsimageio/blob/main/docs/index.md Access file metadata using the `.metadata` property. Channel names can be retrieved with `.channel_names`, and physical pixel sizes for Z, Y, and X dimensions are available via `.physical_pixel_sizes`. ```python from aicsimageio import AICSImage # Get an AICSImage object img = AICSImage("my_file.tiff") # selects the first scene found img.metadata # returns the metadata object for this file format (XML, JSON, etc.) img.channel_names # returns a list of string channel names found in the metadata img.physical_pixel_sizes.Z # returns the Z dimension pixel size as found in the metadata img.physical_pixel_sizes.Y # returns the Y dimension pixel size as found in the metadata img.physical_pixel_sizes.X # returns the X dimension pixel size as found in the metadata ``` -------------------------------- ### Index Image Data with Xarray Source: https://github.com/allencellmodeling/aicsimageio/blob/main/docs/index.md Use xarray for coordinate-based indexing when spatial-temporal metadata is available. ```python from aicsimageio import AICSImage # Get an AICSImage object img = AICSImage("my_file.ome.tiff") # Get the first ten seconds (not frames) first_ten_seconds = img.xarray_data.loc[:10] # returns an xarray.DataArray # Get the first ten major units (usually micrometers, not indices) in Z first_ten_mm_in_z = img.xarray_data.loc[:, :, :10] # Get the first ten major units (usually micrometers, not indices) in Y first_ten_mm_in_y = img.xarray_data.loc[:, :, :, :10] # Get the first ten major units (usually micrometers, not indices) in X first_ten_mm_in_x = img.xarray_data.loc[:, :, :, :, :10] ``` -------------------------------- ### Load and inspect image data Source: https://github.com/allencellmodeling/aicsimageio/blob/main/scripts/makezarr.ipynb Load an image with specific chunk dimensions and print metadata such as scenes and pixel sizes. ```python # load our image chunk_dims= [ DimensionNames.SpatialY, DimensionNames.SpatialX, DimensionNames.Samples, ] img = AICSImage(filepath, chunk_dims=chunk_dims) # print some data about the image we loaded scenes = img.scenes print(scenes) print(str(len(scenes))) print(img.channel_names) print(img.physical_pixel_sizes) ``` -------------------------------- ### Handle Mosaic Images with AICSImage Source: https://context7.com/allencellmodeling/aicsimageio/llms.txt Work with tiled mosaic images from formats like LIF and CZI. Demonstrates automatic stitching, accessing stitched data, disabling stitching to work with individual tiles, and retrieving tile metadata and positions. ```python from aicsimageio import AICSImage # Mosaic images are stitched automatically by default img = AICSImage("large_mosaic.lif") print(f"Stitched dimensions: {img.dims}") # # Access stitched data (uses lazy loading for efficiency) stitched = img.dask_data # Dask chunks fall on tile boundaries print(f"Stitched shape: {stitched.shape}") # Disable automatic stitching to work with individual tiles img_tiles = AICSImage("large_mosaic.lif", reconstruct_mosaic=False) print(f"Tile dimensions: {img_tiles.dims}") # # Access tile metadata tile_dims = img.mosaic_tile_dims print(f"Individual tile size: Y={tile_dims.Y}, X={tile_dims.X}") # Get position of specific tile (top-left corner) y_start, x_start = img.get_mosaic_tile_position(12) print(f"Tile 12 position: Y={y_start}, X={x_start}") # Get all tile positions all_positions = img.get_mosaic_tile_positions() for i, (y, x) in enumerate(all_positions[:5]): print(f"Tile {i}: Y={y}, X={x}") ``` -------------------------------- ### Testing Utilities for Image Containers Source: https://github.com/allencellmodeling/aicsimageio/blob/main/docs/CONTRIBUTING.md Functions provided for testing and validating data and metadata of image containers. ```python from aicsimageio.tests.image_container_test_utils import ( run_image_container_checks, run_multi_scene_image_read_checks, ) ``` -------------------------------- ### Read back OME-Zarr data Source: https://github.com/allencellmodeling/aicsimageio/blob/main/scripts/makezarr.ipynb Verify the written data by reading it back from S3 and inspecting the multiscale levels. ```python ############################################# # READ BACK ############################################# from ome_zarr.reader import Multiscales, Reader from ome_zarr.io import parse_url s3 = s3fs.S3FileSystem() mypath = f"s3://{output_bucket}/{output_filename}/{scenes[scene_indices[0]]}.zarr" reader = Reader(parse_url(mypath)) node = list(reader())[0] # levels print(len(node.data)) for i in range(len(node.data)): print(f"shape of level {i} : {node.data[i].shape}") ``` -------------------------------- ### Update submodules Source: https://github.com/allencellmodeling/aicsimageio/blob/main/docs/CONTRIBUTING.md Fetches and merges updates from the submodule repository. ```bash git submodule update --remote --merge ``` -------------------------------- ### Write multi-scene images to S3 Source: https://github.com/allencellmodeling/aicsimageio/blob/main/scripts/makezarr.ipynb Iterate through image scenes and write them to S3 in OME-Zarr format using a custom writer function. ```python # construct some per-channel lists to feed in to the writer. # hardcoding to 9 for now channel_colors = [0xff0000, 0x00ff00, 0x0000ff, 0xffff00, 0xff00ff, 0x00ffff, 0x880000, 0x008800, 0x000088] # initialize for writing direct to S3 s3 = s3fs.S3FileSystem(anon=False, config_kwargs={"connect_timeout": 60}) def write_scene(storeroot, scenename, sceneindex, img): print(scenename) print(storeroot) img.set_scene(sceneindex) pps = img.physical_pixel_sizes cn = img.channel_names data = img.get_image_dask_data("TCZYX") print(data.shape) writer = OmeZarrWriter(storeroot) writer.write_image( image_data=data, image_name=scenename, physical_pixel_sizes=pps, channel_names=cn, channel_colors=channel_colors, scale_num_levels=4, scale_factor=2.0, ) # here we are splitting multi-scene images into separate zarr images based on scene name scene_indices = range(len(img.scenes)) for i in scene_indices: scenename = img.scenes[i] scenename = scenename.replace(":","_") write_scene(f"s3://{output_bucket}/{output_filename}/{scenename}.zarr/", scenename, i, img) ``` -------------------------------- ### Perform Lazy Loading with Dask Arrays Source: https://context7.com/allencellmodeling/aicsimageio/llms.txt Use Dask arrays for out-of-core processing of large images that exceed available memory. ```python from aicsimageio import AICSImage img = AICSImage("large_file.czi") # Access as delayed dask array - no data loaded yet dask_data = img.dask_data # returns 5D TCZYX dask array print(f"Dask array shape: {dask_data.shape}") # Access as xarray with dask backing xarray_dask = img.xarray_dask_data # xarray.DataArray backed by dask # Get specific chunk lazily - only loads requested chunk lazy_t0 = img.get_image_dask_data("CZYX", T=0) # returns 4D dask array print(f"Lazy chunk shape: {lazy_t0.shape}") # Compute to load into memory when ready t0_data = lazy_t0.compute() # returns in-memory 4D numpy array print(f"Computed shape: {t0_data.shape}") # Compute with dask distributed for parallel processing from dask.distributed import Client client = Client() result = dask_data[0, :, 5, :, :].compute() # T=0, all channels, Z=5 ``` -------------------------------- ### Reader Selection and Custom Readers Source: https://context7.com/allencellmodeling/aicsimageio/llms.txt Control how image readers are selected or use specific readers directly for performance or to handle specific file types. Includes automatic detection, forcing a reader, and checking support. ```python from aicsimageio import AICSImage from aicsimageio.readers import ( TiffReader, OmeTiffReader, CziReader, LifReader, Nd2Reader, BioformatsReader, TiffGlobReader ) # Automatic reader detection img = AICSImage("my_file.tiff") print(f"Reader used: {type(img.reader).__name__}") # TiffReader or OmeTiffReader # Force specific reader (faster, skips detection) img = AICSImage("malformed.ome.tiff", reader=TiffReader) # Check if file is supported before loading from aicsimageio import AICSImage is_supported = AICSImage.determine_reader("unknown_file.xyz") # Use readers directly for more control reader = OmeTiffReader("my_file.ome.tiff") print(f"Scenes: {reader.scenes}") print(f"Dims: {reader.dims}") data = reader.data # Read multiple TIFF files as single image img = AICSImage(["frame_001.tiff", "frame_002.tiff", "frame_003.tiff"]) ``` -------------------------------- ### Chunk Image by Specific Dimensions Source: https://github.com/allencellmodeling/aicsimageio/blob/main/presentations/2021-dask-life-sciences/presentation.ipynb Initializes an AICSImage object and specifies chunking along 'TYX' dimensions for efficient processing of time-series, Z-stacks, and XY data. This reduces I/O operations by creating larger chunks. ```python AICSImage( "../../aicsimageio/tests/resources/image_stack_tpzc_50tp_2p_5z_3c_512k_1_MMStack_2-Pos000_000.ome.tif", chunk_dims="TYX", ).dask_data ``` -------------------------------- ### Mosaic Image Reading with Reader Object Source: https://github.com/allencellmodeling/aicsimageio/blob/main/docs/index.md The `Reader` object also provides access to mosaic data. `.dask_data` allows operations on individual tiles using the M dimension, while `.mosaic_dask_data` returns the stitched mosaic. ```python from aicsimageio.readers import LifReader reader = LifReader("ver-large-mosaic.lif") reader.dims.order # M, T, C, Z, tile size Y, tile size X, (S optional) reader.dask_data # normal operations, can use M dimension to select individual tiles reader.mosaic_dask_data # returns stitched mosaic - T, C, Z, big Y, big, X, (S optional) ``` -------------------------------- ### Write OME-TIFF Files with OmeTiffWriter Source: https://context7.com/allencellmodeling/aicsimageio/llms.txt Write images to OME-TIFF format with proper metadata. Supports simple conversions, saving numpy arrays with dimension order, and full metadata including channel names, colors, and physical sizes. ```python import numpy as np from aicsimageio import AICSImage from aicsimageio.writers import OmeTiffWriter from aicsimageio.types import PhysicalPixelSizes # Simple conversion from one format to another AICSImage("input.czi").save("output.ome.tiff") # Save numpy array with dimension order image = np.random.randint(0, 65535, (10, 3, 1024, 2048), dtype=np.uint16) OmeTiffWriter.save(image, "output.ome.tif", dim_order="ZCYX") # Save with full metadata image = np.random.rand(1, 3, 20, 512, 512).astype(np.float32) OmeTiffWriter.save( image, "annotated.ome.tiff", dim_order="TCZYX", channel_names=["DAPI", "GFP", "mCherry"], image_name="MyExperiment", physical_pixel_sizes=PhysicalPixelSizes(Z=0.5, Y=0.108, X=0.108), channel_colors=[[0, 0, 255], [0, 255, 0], [255, 0, 0]] # RGB colors ) # Save multi-scene images image0 = np.random.rand(3, 10, 1024, 2048).astype(np.float32) image1 = np.random.rand(3, 10, 512, 512).astype(np.float32) OmeTiffWriter.save( [image0, image1], "multi_scene.ome.tiff", dim_order="CZYX", # Applied to both images channel_names=[["C00", "C01", "C02"], ["C10", "C11", "C12"]], image_name=["Scene0", "Scene1"], physical_pixel_sizes=[ PhysicalPixelSizes(Z=None, Y=0.1, X=0.1), PhysicalPixelSizes(Z=None, Y=0.2, X=0.2) ] ) # Save with custom OME metadata from ome_types import OME ome = OmeTiffWriter.build_ome( data_shapes=[(1, 3, 20, 512, 512)], data_types=[np.float32], dimension_order=["TCZYX"], channel_names=[["DAPI", "GFP", "RFP"]], image_name=["MyImage"], physical_pixel_sizes=[PhysicalPixelSizes(Z=0.5, Y=0.1, X=0.1)] ) OmeTiffWriter.save(image, "custom_ome.ome.tiff", ome_xml=ome) ``` -------------------------------- ### Normalize and Project Channel Source: https://github.com/allencellmodeling/aicsimageio/blob/main/presentations/2021-dask-life-sciences/presentation.ipynb Performs percentile normalization and max projection on a Dask array channel. ```python import dask.array as da import dask def norm_and_proj_channel(data): # Get percentile norm by values min_px_val, max_px_val = da.percentile( data.flatten(), [50.0, 99.8], ).compute() # Norm normed = (data - min_px_val) / (max_px_val - min_px_val) # Clip any values outside of 0 and 1 clipped = da.clip(normed, 0, 1) # Scale them between 0 and 255 scaled = clipped * 255 # Create max project return scaled.max(axis=0) ``` -------------------------------- ### Normalize and Project Channel with AICSImage Source: https://github.com/allencellmodeling/aicsimageio/blob/main/presentations/2021-dask-life-sciences/presentation.ipynb Reads a TIFF image using AICSImage, iterates through specified channel names, extracts channel data as a Dask array, and then normalizes and projects each channel. Requires AICSImage and a norm_and_proj_channel function. ```python aics_img = AICSImage("../../aicsimageio/tests/resources/3d-cell-viewer.ome.tiff") projs = [] for i, channel_name in enumerate(aics_img.channel_names): if channel_name in ["DRAQ5", "EGFP", "Hoechst 33258", "TL Brightfield"]: # get 3d array in ZYX order with just the selected channels data aics_channel = aics_img.get_image_dask_data("ZYX", C=i) projs.append(norm_and_proj_channel(aics_channel)) aics_projs = da.stack(projs) dask.optimize(aics_projs)[0].visualize() ``` -------------------------------- ### XArray Coordinate-Based Indexing Source: https://context7.com/allencellmodeling/aicsimageio/llms.txt Utilize xarray integration for selecting image data based on physical coordinates (e.g., time, Z-depth, spatial dimensions) when metadata is available. Supports lazy loading with dask. ```python from aicsimageio import AICSImage img = AICSImage("calibrated_image.ome.tiff") # Get xarray DataArray with coordinate planes xr_data = img.xarray_data print(f"Dimensions: {xr_data.dims}") print(f"Coordinates: {dict(xr_data.coords)}") # Select by physical coordinates (not indices) # Get first 10 seconds of data first_10_sec = xr_data.loc[:10] # Get first 10 micrometers in Z first_10um_z = xr_data.loc[:, :, :10] # Get specific channel by name dapi_channel = xr_data.sel(C="DAPI") print(f"DAPI channel shape: {dapi_channel.shape}") # Combine selections subset = xr_data.loc[:5, :, :10, :100, :100] # T<5s, Z<10um, Y<100um, X<100um # Works with dask backing for lazy operations xr_dask = img.xarray_dask_data lazy_subset = xr_dask.loc[:10, :, :5] result = lazy_subset.compute() # Access coordinate values t_coords = xr_data.coords["T"].values # Time coordinates in seconds z_coords = xr_data.coords["Z"].values # Z coordinates in micrometers channel_names = xr_data.coords["C"].values # Channel names ``` -------------------------------- ### Read Remote Files with Cloud IO Source: https://github.com/allencellmodeling/aicsimageio/blob/main/docs/index.md Utilize fsspec to read images directly from remote object storage services like S3 or GCS. ```python from aicsimageio import AICSImage # Get an AICSImage object img = AICSImage("http://my-website.com/my_file.tiff") img = AICSImage("s3://my-bucket/my_file.tiff") img = AICSImage("gcs://my-bucket/my_file.tiff") # Or read with specific filesystem creation arguments img = AICSImage("s3://my-bucket/my_file.tiff", fs_kwargs=dict(anon=True)) img = AICSImage("gcs://my-bucket/my_file.tiff", fs_kwargs=dict(anon=True)) # All other normal operations work just fine ``` -------------------------------- ### Optional Reader Class Methods Source: https://github.com/allencellmodeling/aicsimageio/blob/main/docs/CONTRIBUTING.md These methods can be optionally implemented to add advanced features to custom Reader classes. ```python def _get_stitched_dask_mosaic(self, scene_index): # Stitch mosaic tiles from a delayed dask array raise NotImplementedError def _get_stitched_mosaic(self, scene_index): # Stitch mosaic tiles from an in-memory numpy array raise NotImplementedError def get_mosaic_tile_position(self, tile_index): # Get a specific mosaic tile's position from its tile index raise NotImplementedError @property def ome_metadata(self): # Return the format’s metadata type converted to OME metadata raise NotImplementedError @property def physical_pixel_sizes(self): # Return the spatial dimensions pixel sizes return (None, None, None) ``` -------------------------------- ### Load and Inspect Images with AICSImage Source: https://context7.com/allencellmodeling/aicsimageio/llms.txt The AICSImage class automatically detects file formats and provides access to image data, dimensions, and metadata. ```python from aicsimageio import AICSImage # Basic image loading - selects first scene automatically img = AICSImage("my_file.tiff") # Access image data as numpy array (loads entire scene into memory) data = img.data # returns 5D TCZYX numpy array print(f"Shape: {data.shape}, Dtype: {data.dtype}") # Access image properties print(f"Dimensions: {img.dims}") # print(f"Dimension order: {img.dims.order}") # "TCZYX" print(f"X size: {img.dims.X}") # 1024 print(f"Shape tuple: {img.shape}") # (1, 3, 10, 1024, 1024) # Access as xarray DataArray with coordinate labels xarray_data = img.xarray_data # 5D xarray.DataArray backed by numpy # Get metadata and channel information print(f"Channel names: {img.channel_names}") # ['DAPI', 'GFP', 'RFP'] print(f"Physical pixel sizes: {img.physical_pixel_sizes}") # PhysicalPixelSizes(Z=0.5, Y=0.1, X=0.1) print(f"Metadata: {img.metadata}") # Format-specific metadata object ``` -------------------------------- ### Read Image with Dask Source: https://github.com/allencellmodeling/aicsimageio/blob/main/presentations/2021-dask-life-sciences/presentation.ipynb Reads an OME-TIFF file into a Dask array using dask_image. ```python from dask_image.imread import imread da_img = imread("../../aicsimageio/tests/resources/3d-cell-viewer.ome.tiff") da_img ``` -------------------------------- ### Configure Matplotlib Colormap Source: https://github.com/allencellmodeling/aicsimageio/blob/main/presentations/2021-dask-life-sciences/presentation.ipynb Sets the global colormap for matplotlib plots. ```python from matplotlib.pyplot import imshow, set_cmap set_cmap("inferno") ``` -------------------------------- ### Required Reader Class Methods Source: https://github.com/allencellmodeling/aicsimageio/blob/main/docs/CONTRIBUTING.md Custom Reader classes must implement these methods to support image reading functionality. ```python def _is_supported_image(self, image_path): # Check if the custom Reader class can read the provided object pass @property def scenes(self): # Return the Tuple of all scene names pass def _read_delayed(self, scene_index): # Return an xarray.DataArray backed by a delayed dask.array.Array pass def _read_immediate(self, scene_index): # Return an xarray.DataArray backed by an in-memory numpy.ndarray pass ``` -------------------------------- ### Extract Image Slices with Dimension Selection Source: https://context7.com/allencellmodeling/aicsimageio/llms.txt Use get_image_data or get_image_dask_data to extract specific slices using various indexing methods. ```python from aicsimageio import AICSImage img = AICSImage("multi_channel_timelapse.ome.tiff") print(f"Full shape: {img.shape}") # (10, 4, 20, 1024, 1024) - T=10, C=4, Z=20 # Get specific index - returns 4D CZYX array for T=0 single_frame = img.get_image_data("CZYX", T=0) print(f"Single frame: {single_frame.shape}") # (4, 20, 1024, 1024) # Get specific Z slice - returns 4D TCYX array mid_z = img.get_image_data("TCYX", Z=10) print(f"Mid Z slice: {mid_z.shape}") # (10, 4, 1024, 1024) # Get multiple indices with list first_two_channels = img.get_image_data("TCZYX", C=[0, 1]) print(f"Two channels: {first_two_channels.shape}") # (10, 2, 20, 1024, 1024) # Get range of timepoints first_five_frames = img.get_image_data("TCZYX", T=range(5)) print(f"First 5 frames: {first_five_frames.shape}") # (5, 4, 20, 1024, 1024) # Get every other Z slice with slice notation every_other_z = img.get_image_data("TCZYX", Z=slice(0, -1, 2)) print(f"Every other Z: {every_other_z.shape}") # (10, 4, 10, 1024, 1024) # Combine multiple selections subset = img.get_image_data("ZYX", T=5, C=0) # Single timepoint and channel print(f"Single T/C subset: {subset.shape}") # (20, 1024, 1024) # Same operations available with dask for lazy loading lazy_subset = img.get_image_dask_data("CZYX", T=0, Z=range(5)) result = lazy_subset.compute() # Computes only when needed ``` -------------------------------- ### Access Metadata Source: https://github.com/allencellmodeling/aicsimageio/blob/main/presentations/2021-dask-life-sciences/presentation.ipynb Retrieves the OME metadata from an AICSImage object. ```python aics_img.metadata ``` -------------------------------- ### Delayed Image Reading with Dask Source: https://github.com/allencellmodeling/aicsimageio/blob/main/docs/index.md For images that do not fit into memory, use `.dask_data` or `.xarray_dask_data` for delayed loading. Data is only loaded into memory when `.compute()` is called on a Dask array. ```python from aicsimageio import AICSImage # Get an AICSImage object img = AICSImage("my_file.tiff") # selects the first scene found img.dask_data # returns 5D TCZYX dask array img.xarray_dask_data # returns 5D TCZYX xarray data array backed by dask array img.dims # returns a Dimensions object img.dims.order # returns string "TCZYX" img.dims.X # returns size of X dimension img.shape # returns tuple of dimension sizes in TCZYX order # Pull only a specific chunk in-memory lazy_t0 = img.get_image_dask_data("CZYX", T=0) # returns out-of-memory 4D dask array t0 = lazy_t0.compute() # returns in-memory 4D numpy array ``` -------------------------------- ### Save Images to OME-TIFF Source: https://github.com/allencellmodeling/aicsimageio/blob/main/docs/index.md Save images using the AICSImage save method or the OmeTiffWriter class for more granular control. ```python from aicsimageio import AICSImage AICSImage("my_file.czi").save("my_file.ome.tiff") ``` ```python import numpy as np from aicsimageio.writers import OmeTiffWriter image = np.random.rand(10, 3, 1024, 2048) OmeTiffWriter.save(image, "file.ome.tif", dim_order="ZCYX") ``` -------------------------------- ### Custom OME-TIFF Saving with OmeTiffWriter Source: https://github.com/allencellmodeling/aicsimageio/blob/main/README.md Save a NumPy array as an OME-TIFF with specified dimension order using OmeTiffWriter. This provides finer grain customization than the basic save method. ```python import numpy as np from aicsimageio.writers import OmeTiffWriter image = np.random.rand(10, 3, 1024, 2048) OmeTiffWriter.save(image, "file.ome.tif", dim_order="ZCYX") ``` -------------------------------- ### Access Channel Names Source: https://github.com/allencellmodeling/aicsimageio/blob/main/presentations/2021-dask-life-sciences/presentation.ipynb Retrieves the list of channel names from an AICSImage object. ```python aics_img.channel_names ``` -------------------------------- ### Cite AICSImageIO Source: https://github.com/allencellmodeling/aicsimageio/blob/main/docs/index.md BibTeX citation format for the AICSImageIO repository. ```bibtex @misc{aicsimageio, author = {Brown, Eva Maxfield and Toloudis, Dan and Sherman, Jamie and Swain-Bowden, Madison and Lambert, Talley and {AICSImageIO Contributors}}, title = {AICSImageIO: Image Reading, Metadata Conversion, and Image Writing for Microscopy Images in Pure Python}, year = {2021}, publisher = {GitHub}, url = {https://github.com/AllenCellModeling/aicsimageio} } ``` -------------------------------- ### Read Images Directly with imread Functions Source: https://context7.com/allencellmodeling/aicsimageio/llms.txt Convenience functions for quick image reading without creating an AICSImage object. Supports direct numpy array, dask array, and xarray DataArray formats. ```python from aicsimageio import imread, imread_dask, imread_xarray, imread_xarray_dask # Read image directly as numpy array data = imread("my_file.tiff") print(f"Shape: {data.shape}") # 5D TCZYX numpy array # Read specific scene scene2_data = imread("multi_scene.czi", scene_id="Image:2") # Read as dask array for large files lazy_data = imread_dask("very_large_file.ome.tiff") # Process lazily then compute result = lazy_data[0, 0, :, :, :].compute() # Read as xarray DataArray with coordinates xr_data = imread_xarray("my_file.ome.tiff") print(f"Coordinates: {list(xr_data.coords)}") # Select by coordinate values subset = xr_data.sel(C="DAPI") # Read as xarray backed by dask xr_dask = imread_xarray_dask("large_file.nd2", scene_id="Position_1") # Pass reader-specific arguments data = imread("my_file.czi", chunk_dims=["T", "Y", "X"]) ``` -------------------------------- ### Display Image with Matplotlib Source: https://github.com/allencellmodeling/aicsimageio/blob/main/presentations/2021-dask-life-sciences/presentation.ipynb Displays a single slice of a Dask array (presumably an image) using matplotlib's imshow function. ```python imshow(aics_projs[2]) ```