跳轉至

pyHisto.io (legacy)

To be deprecated

See Legacy modules. Ingestion is via tanoa OME-Zarr and histo.open_slide; the legacy CZI readers return BGR.

sort_tile_items_spatially

sort_tile_items_spatially(tile_items)

Sort (index, bbox) tile items in row-major (Y then X) order.

Reading tiles in spatial order shortens the average seek distance between consecutive reads on the underlying storage, since neighbouring tiles in the CZI mosaic tend to be stored close together on disk. This is a pure reordering with no effect on the resulting stitched image.

Args: tile_items: iterable of (index, bbox) tuples, where bbox is a dict with at least "x" and "y" keys (as produced by czi_read's tile_bboxes).

Returns: list of (index, bbox) tuples sorted by (y, x).

czi_read

czi_read(path, channel=-1, scene=0, skip=1, parallel=True, n_workers=None, verbose=False, batch_size=50, parallel_mode='thread', max_tiles=None, sort_tiles=True)

Read CZI file using manual tile loading method with aicspylibczi.

This function uses direct tile-by-tile loading required for certain CZI formats (especially Axioscan data).

Args: path: Path to the CZI file channel: Channel index (-1 for all channels) scene: Scene index (default: 0) skip: Skip parameter (currently unused) parallel: Whether to use parallel loading for tiled images (default: False) Uses threading to load tiles in parallel. For large images with many tiles, this may come with memory overhead and kill the loading process. n_workers: Number of worker threads/processes for parallel loading (default: min(CPU count, 8)) verbose: Whether to print debug information during tile loading (default: False) batch_size: Number of tiles to process per batch in parallel mode (default: 50) Each batch is processed by a single thread to minimize memory usage. parallel_mode: "thread" (default) or "process" backend for parallel loading max_tiles: Optional cap on the number of tiles to load (useful for debugging/tests) sort_tiles: Whether to read tiles in spatial (Y then X) order to reduce disk seek distance between consecutive reads (default: True). Purely an I/O ordering optimization; does not affect the output image.

Returns: numpy array with dimensions XYC

stream_czi_to_ome_zarr

stream_czi_to_ome_zarr(path, out_path, channel=-1, scene='auto', verbose=False, sort_tiles=True, scale_num_levels=4, scale_factor=2.0, zarr_format=3, chunk_shape=None, shard_shape=None, channel_names=None, channel_colors=None, parallel=True, n_workers=None, batch_size=None, max_pending_mb=1024)

Stream a CZI file directly into a multiresolution OME-Zarr, one mosaic tile at a time, without ever materializing the full stitched image in memory.

Unlike czi_read() + write_ome_zarr_multires() (which builds one large in-memory array first), this reads and writes each CZI tile individually via OMEZarrWriter.write_region(), keeping peak memory bounded to roughly one tile (plus its downsampled copies across pyramid levels) rather than the whole slide. This is the required ingestion path for whole slide images that don't fit in memory at full resolution -- e.g. a 795MB CZI can stitch out to an 80000x110000px array that alone needs 50GB+ of RAM, which non-streaming ingestion has been observed to OOM-kill on.

Sharding: by default, chunks are bundled into shards spanning the full channel/Z extent and a several-chunk XY block, so the resulting store has far fewer files than an unsharded layout (chunk_shape=1024 with shard_shape=4096 bundles 16 XY chunks per shard file). This specifically matters when the store is later read back over an SMB/Windows share (as this project's data commonly is, per the Kennedy network drives) -- per-file open overhead on large file counts is much higher there than on local Linux/Mac storage, so fewer/larger shard files read noticeably faster.

Args: path: input CZI file path. out_path: output .zarr directory path. Removed and recreated if it already exists. channel: Channel index (-1 for all channels). scene: Scene index, or "auto" (default) to pick the scene with the most mosaic tiles. Some CZI files (e.g. an Axioscan run that captured a small label/overview image alongside the actual slide scan) contain multiple scenes of wildly different size -- always using scene 0 silently processed the small overview instead of the real tissue on at least one real sample in this cohort (47 tiles vs. 3450 in the real scan), with no error, just a much smaller image and misleadingly low collagen quantification. verbose: print per-tile read failures. sort_tiles: read/write tiles in spatial (Y then X) order (see sort_tile_items_spatially). scale_num_levels: number of pyramid levels to generate. scale_factor: downsampling factor between consecutive pyramid levels. zarr_format: 2 or 3 (default 3). chunk_shape: per-array chunk shape in CZYX order (default derived from image size, capped at 1024 in Y/X). shard_shape: per-array shard shape in CZYX order (default derived from image size, capped at 4096 in Y/X -- see Sharding note above). channel_names: list of channel name strings. channel_colors: list of colors, one per channel ("#RRGGBB" hex strings, or bare hex ints). parallel: read tiles using multiple worker processes (default True). Only the (CPU-bound) tile read/decode step is parallelized -- all zarr writes stay on the main process/thread, since neighbouring tiles can share a shard file and concurrent unsynchronized writes to the same shard would race. n_workers: number of worker processes (default: min(cpu_count(), 8)). batch_size: tiles per worker task (default: auto-computed from the actual per-tile byte size so each batch is ~50MB, capped at 50 tiles -- each worker's CziFile handle is opened once and reused across all of its batches, so this mainly trades task-dispatch overhead against how finely max_pending_mb can bound in-flight memory). max_pending_mb: target ceiling, in MB, for tile data allowed to sit decoded-but-not-yet-written in memory at once. The real bound is (in-flight batches * batch_size * tile_bytes) -- sizing batches directly in bytes (rather than a fixed tile count) is what keeps this accurate across very different tile sizes. Concrete motivation: with the old fixed batch_size=50 and a 30MB/tile whole-slide image, up to 16 in-flight batches x 50 tiles x 30MB = ~24GB could be sitting in the main process's memory at once (confirmed on real data, reaching ~17GB in practice) -- easily enough to explain the OOM-kills this was previously chalked up to an uncharacterized "leak".

Returns: dict with keys "path", "shape" (level-0 CZYX shape), "dtype", "n_tiles".

tiff_read

tiff_read(path, channel=-1, scene=0, skip=1)

channel=-1 will take all channels, otherwise return a single channel result with 2D+1C size array

Args: path: Path to TIFF file channel: Channel index (-1 for all channels) scene: Scene index (default: 0) skip: Reserved for future use (currently unused)

get_czi_physical_pixel_size

get_czi_physical_pixel_size(path)

write_ome_zarr_multires

write_ome_zarr_multires(image, path, physical_pixel_sizes=None, channel_names=None, channel_colors=None, scale_num_levels=4, scale_factor=2.0, dimension_order='CZYX', zarr_format=3, shard_shape=None)

Write a multiresolution (pyramidal) OME-Zarr from an in-memory array.

Intended as the one-time CZI -> Zarr conversion step: once written, downstream processing (tissue masking on a low-res level, chunk-parallel deconvolution/ segmentation on an appropriate-res level) can read directly from this store instead of re-reading the original CZI tile-by-tile. Uses Zarr v3 by default; pass shard_shape to enable sharding for faster chunked/parallel reads.

Args: image: numpy array in dimension_order layout (default CZYX, i.e. a single Z/T plane with channel-first XY image data -- an XYC array from czi_read must be transposed to CYX before calling, e.g. image.transpose(2, 0, 1)[:, np.newaxis, :, :] for CZYX with Z=1). path: output .zarr directory path. Removed and recreated if it already exists. physical_pixel_sizes: bioio PhysicalPixelSizes (or compatible object with X/Y/Z attributes), used for the OME multiscale metadata. channel_names: list of channel name strings. channel_colors: list of colors, one per channel, as "#RRGGBB" hex strings (or bare hex ints, which are converted). scale_num_levels: number of pyramid levels to generate (level 0 = full res). scale_factor: downsampling factor between consecutive pyramid levels. dimension_order: dimension order of image (default "CZYX"). zarr_format: 2 or 3 (default 3). shard_shape: optional shard shape (same rank as level shapes) for Zarr v3 sharding.

Returns: path (str)

pyramidal_ome_tiff_write

pyramidal_ome_tiff_write(image, path, resX=1.0, resY=1.0, units='µm', tile_size=2048, channel_colors=None)

Pyramidal ome tiff write is only support in 2D + C data. Input dimension order has to be XYC

czi_dask_read

czi_dask_read(path, scene=0, order=None)

Wrapper function for BioImage dask reader, returns out-of-memory dask array