Skip to content

Input / Output

qim3d.io.Downloader

Provides access to the QIM online data repository and manages file downloads.

This utility allows users to easily fetch, download, and load sample datasets for testing, benchmarking, or educational purposes. It automatically handles local caching to avoid repeated downloads of the same file.

The Downloader acts as an interface to the QIM data repository.

Attributes:

Name Type Description
manifest_url str

URL of the dataset manifest.

timeout float

Timeout in seconds for fetching the manifest and looking up file sizes.

Methods:

Name Description
get_datasets

Returns the datasets, formats and sizes published in the manifest.

show_datasets

Prints a table of the datasets, their categories and sizes.

download_dataset

Downloads a volume and returns its local path.

load_dataset

Downloads a volume if needed and returns its image data.

refresh

Fetches the manifest again.

Syntax for downloading and loading a dataset: qim3d.io.Downloader().load_dataset("cowry-shell", format="zarr")

Overview of available data

See the current datasets and formats on the QIM data repository, or call get_datasets() to inspect them in Python.

Example

import qim3d

downloader = qim3d.io.Downloader()

# Browse available datasets
datasets = downloader.get_datasets()

# Download and load a sample
data = downloader.load_dataset("cowry-shell", format="zarr", scale="lowest")

qim3d.viz.slicer_orthogonal(data, colormap="magma")
cowry shell

Source code in qim3d/io/_downloader.py
class Downloader:
    """
    Provides access to the QIM online data repository and manages file downloads.

    This utility allows users to easily fetch, download, and load sample datasets for testing,
    benchmarking, or educational purposes. It automatically handles local caching to avoid
    repeated downloads of the same file.

    The `Downloader` acts as an interface to the [QIM data repository](https://data-repository.qim.dk/).

    Attributes:
        manifest_url (str): URL of the dataset manifest.
        timeout (float): Timeout in seconds for fetching the manifest and looking up file sizes.

    Methods:
        get_datasets(): Returns the datasets, formats and sizes published in the manifest.
        show_datasets(): Prints a table of the datasets, their categories and sizes.
        download_dataset(dataset_id, format, ...): Downloads a volume and returns its local path.
        load_dataset(dataset_id, format, ...): Downloads a volume if needed and returns its image data.
        refresh(): Fetches the manifest again.

    Syntax for downloading and loading a dataset:
    `qim3d.io.Downloader().load_dataset("cowry-shell", format="zarr")`

    ??? info "Overview of available data"
        See the current datasets and formats on the [QIM data repository](https://data-repository.qim.dk/),
        or call `get_datasets()` to inspect them in Python.

    Example:
        ```python
        import qim3d

        downloader = qim3d.io.Downloader()

        # Browse available datasets
        datasets = downloader.get_datasets()

        # Download and load a sample
        data = downloader.load_dataset("cowry-shell", format="zarr", scale="lowest")

        qim3d.viz.slicer_orthogonal(data, colormap="magma")
        ```
        ![cowry shell](../../assets/screenshots/cowry_shell_slicer.gif)
    """

    def __init__(
        self,
        manifest_url: str = _MANIFEST_URL,
        timeout: float = 10,
    ) -> None:
        if timeout <= 0:
            raise ValueError("timeout must be positive")
        self.manifest_url = manifest_url
        self.timeout = timeout
        self._datasets: list[dict] | None = None

    def refresh(self) -> None:
        """Fetch the manifest again, replacing the cached catalog on success."""
        self._datasets = _fetch_manifest(self.manifest_url, self.timeout)

    def _get_datasets(self) -> list[dict]:
        if self._datasets is None:
            self._datasets = _fetch_manifest(self.manifest_url, self.timeout)
        return self._datasets

    def get_datasets(self) -> list[dict[Any, Any]]:
        """Return a list of all available datasets.

        Each entry in a dataset's ``volumes`` has its ``format``, ``url`` and
        ``size_bytes`` (``None`` when the size is not published).
        """
        return deepcopy(self._get_datasets())

    def show_datasets(self) -> None:
        """Print a table of the datasets with their categories and volume sizes."""
        rows = [("ID", "Categories", "TIFF", "Zarr")]
        for dataset in self._get_datasets():
            sizes = {
                volume.get("format"): volume.get("size_bytes")
                for volume in dataset.get("volumes") or []
            }
            tiff, zarr = (
                sizeof(size) if type(size) is int and size > 0 else "-"
                for size in (sizes.get("tiff"), sizes.get("zarr"))
            )
            categories = ", ".join(map(str, dataset.get("categories") or []))
            rows.append((str(dataset.get("id")), categories, tiff, zarr))
        widths = [max(len(cell) for cell in column) for column in zip(*rows)]
        for row in rows:
            line = "  ".join(cell.ljust(width) for cell, width in zip(row, widths))
            print(line.rstrip())

    def _get_volume(
        self, dataset_id: str, volume_format: str
    ) -> tuple[str, str, int | None]:
        """Return the URL, file name and size in bytes (None if unknown) of a volume."""
        dataset = next(
            (item for item in self._get_datasets() if item.get("id") == dataset_id),
            None,
        )
        if dataset is None:
            raise LookupError(
                f"Dataset {dataset_id!r} was not found. "
                "Use get_datasets() to see available IDs."
            )
        volumes = dataset.get("volumes") or []
        volume = next(
            (item for item in volumes if item.get("format") == volume_format), None
        )
        if volume is None:
            available = ", ".join(
                str(item.get("format")) for item in volumes if item.get("url")
            )
            raise LookupError(
                f"Dataset {dataset_id!r} has no {volume_format!r} volume. "
                f"Available formats: {available or 'none'}."
            )
        url = volume.get("url")
        if isinstance(url, str):
            parsed = urlparse(url)
            filename = Path(parsed.path).name
            if (
                parsed.scheme in {"http", "https"}
                and parsed.netloc
                and filename not in {"", ".", ".."}
            ):
                size_bytes = volume.get("size_bytes")
                if type(size_bytes) is not int or size_bytes <= 0:
                    size_bytes = None
                return url, filename, size_bytes
        raise ValueError(
            f"Dataset {dataset_id!r} has no usable download URL for "
            f"format {volume_format!r}"
        )

    def download_dataset(
        self,
        dataset_id: str,
        *,
        format: Literal["tiff", "zarr"],
        output_dir: str | os.PathLike = ".",
        replace: bool = False,
    ) -> Path:
        """Download a manifest volume and return its local path.

        ``format`` is "tiff" or "zarr". The volume is stored under
        ``output_dir/dataset_id/``. An existing path is reused unless
        ``replace=True``, which downloads the volume again and replaces the old
        copy once the new download has finished. New downloads are staged so
        failures do not leave a partial final path or remove the old copy.
        """
        # The ID must be a single folder name, so it can't escape output_dir, for example "../coal-briquette"
        if (
            not isinstance(dataset_id, str)
            or dataset_id in {"", ".", ".."}
            or Path(dataset_id).name != dataset_id
        ):
            raise ValueError(f"Invalid dataset ID {dataset_id!r}")
        dataset_dir = Path(output_dir) / dataset_id

        url, filename, size_bytes = self._get_volume(dataset_id, format)
        destination = dataset_dir / filename
        if destination.exists() and not replace:
            _logger.info("Dataset volume already downloaded: %s", destination)
            return destination
        if destination.is_symlink() and not replace:
            raise FileNotFoundError(f"{destination} is a broken symbolic link")

        dataset_dir.mkdir(parents=True, exist_ok=True)
        with tempfile.TemporaryDirectory(
            prefix=".download-", dir=dataset_dir
        ) as staging:
            staged = Path(staging) / filename
            self._download_url(url, staged, format, size_bytes)
            if destination.exists() and not replace:
                return destination
            # Remove the old copy only now that the new one has downloaded
            if destination.is_dir() and not destination.is_symlink():
                shutil.rmtree(destination)
            elif destination.is_symlink() or destination.exists():
                destination.unlink()
            os.replace(staged, destination)
        return destination

    def load_dataset(
        self,
        dataset_id: str,
        *,
        format: Literal["tiff", "zarr"],
        output_dir: str | os.PathLike = ".",
        virtual_stack: bool = True,
        scale: int | Literal["lowest", "highest"] = 0,
        replace: bool = False,
    ) -> object:
        """Download a volume if needed, then return its image data.

        ``format`` is "tiff" or "zarr". ``virtual_stack=True`` uses lazy loading
        where supported. ``scale`` selects
        an OME-Zarr resolution (0, a coarser integer, "highest", or "lowest");
        other formats only accept the default scale of 0. ``replace=True``
        downloads the volume again even if it is already downloaded.
        """
        if format != "zarr" and scale not in (0, "highest"):
            raise ValueError("scale is only supported for OME-Zarr volumes")
        path = self.download_dataset(
            dataset_id, format=format, output_dir=output_dir, replace=replace
        )
        if format == "zarr":
            return qim3d.io.import_ome_zarr(path, scale=scale, load=not virtual_stack)
        return load(path=path, virtual_stack=virtual_stack)

    def _download_url(
        self,
        url: str,
        destination: Path,
        volume_format: str,
        size_bytes: int | None = None,
    ) -> None:
        """Download a volume to ``destination``.

        ``size_bytes`` is the expected size, used for logging and the progress bar.
        """
        size = f" ({sizeof(size_bytes)})" if size_bytes else ""
        if volume_format == "zarr":
            _logger.info(
                "Downloading Zarr store %s%s from %s", destination.name, size, url
            )
            try:
                download(url, output_dir=str(destination.parent))
            except (AssertionError, AttributeError) as err:
                # ome_zarr only asserts that the store could be opened
                raise FileNotFoundError(
                    f"No OME-Zarr store could be opened at {url}"
                ) from err
            return
        _logger.info("Downloading file %s%s from %s", destination.name, size, url)
        total = size_bytes
        if total is None:
            try:
                total = _get_file_size(url, self.timeout)
            except OSError:
                total = -1
        with tqdm(
            total=total if total > 0 else None,
            unit="B",
            unit_scale=True,
            unit_divisor=1024,
            ncols=80,
        ) as pbar:
            urllib.request.urlretrieve(
                url,
                destination,
                reporthook=lambda blocknum, block_size, _total_size: pbar.update(
                    blocknum * block_size - pbar.n
                ),
            )

qim3d.io.Downloader.download_dataset

download_dataset(dataset_id, *, format, output_dir='.', replace=False)

Download a manifest volume and return its local path.

format is "tiff" or "zarr". The volume is stored under output_dir/dataset_id/. An existing path is reused unless replace=True, which downloads the volume again and replaces the old copy once the new download has finished. New downloads are staged so failures do not leave a partial final path or remove the old copy.

Source code in qim3d/io/_downloader.py
def download_dataset(
    self,
    dataset_id: str,
    *,
    format: Literal["tiff", "zarr"],
    output_dir: str | os.PathLike = ".",
    replace: bool = False,
) -> Path:
    """Download a manifest volume and return its local path.

    ``format`` is "tiff" or "zarr". The volume is stored under
    ``output_dir/dataset_id/``. An existing path is reused unless
    ``replace=True``, which downloads the volume again and replaces the old
    copy once the new download has finished. New downloads are staged so
    failures do not leave a partial final path or remove the old copy.
    """
    # The ID must be a single folder name, so it can't escape output_dir, for example "../coal-briquette"
    if (
        not isinstance(dataset_id, str)
        or dataset_id in {"", ".", ".."}
        or Path(dataset_id).name != dataset_id
    ):
        raise ValueError(f"Invalid dataset ID {dataset_id!r}")
    dataset_dir = Path(output_dir) / dataset_id

    url, filename, size_bytes = self._get_volume(dataset_id, format)
    destination = dataset_dir / filename
    if destination.exists() and not replace:
        _logger.info("Dataset volume already downloaded: %s", destination)
        return destination
    if destination.is_symlink() and not replace:
        raise FileNotFoundError(f"{destination} is a broken symbolic link")

    dataset_dir.mkdir(parents=True, exist_ok=True)
    with tempfile.TemporaryDirectory(
        prefix=".download-", dir=dataset_dir
    ) as staging:
        staged = Path(staging) / filename
        self._download_url(url, staged, format, size_bytes)
        if destination.exists() and not replace:
            return destination
        # Remove the old copy only now that the new one has downloaded
        if destination.is_dir() and not destination.is_symlink():
            shutil.rmtree(destination)
        elif destination.is_symlink() or destination.exists():
            destination.unlink()
        os.replace(staged, destination)
    return destination

qim3d.io.Downloader.get_datasets

get_datasets()

Return a list of all available datasets.

Each entry in a dataset's volumes has its format, url and size_bytes (None when the size is not published).

Source code in qim3d/io/_downloader.py
def get_datasets(self) -> list[dict[Any, Any]]:
    """Return a list of all available datasets.

    Each entry in a dataset's ``volumes`` has its ``format``, ``url`` and
    ``size_bytes`` (``None`` when the size is not published).
    """
    return deepcopy(self._get_datasets())

qim3d.io.Downloader.load_dataset

load_dataset(dataset_id, *, format, output_dir='.', virtual_stack=True, scale=0, replace=False)

Download a volume if needed, then return its image data.

format is "tiff" or "zarr". virtual_stack=True uses lazy loading where supported. scale selects an OME-Zarr resolution (0, a coarser integer, "highest", or "lowest"); other formats only accept the default scale of 0. replace=True downloads the volume again even if it is already downloaded.

Source code in qim3d/io/_downloader.py
def load_dataset(
    self,
    dataset_id: str,
    *,
    format: Literal["tiff", "zarr"],
    output_dir: str | os.PathLike = ".",
    virtual_stack: bool = True,
    scale: int | Literal["lowest", "highest"] = 0,
    replace: bool = False,
) -> object:
    """Download a volume if needed, then return its image data.

    ``format`` is "tiff" or "zarr". ``virtual_stack=True`` uses lazy loading
    where supported. ``scale`` selects
    an OME-Zarr resolution (0, a coarser integer, "highest", or "lowest");
    other formats only accept the default scale of 0. ``replace=True``
    downloads the volume again even if it is already downloaded.
    """
    if format != "zarr" and scale not in (0, "highest"):
        raise ValueError("scale is only supported for OME-Zarr volumes")
    path = self.download_dataset(
        dataset_id, format=format, output_dir=output_dir, replace=replace
    )
    if format == "zarr":
        return qim3d.io.import_ome_zarr(path, scale=scale, load=not virtual_stack)
    return load(path=path, virtual_stack=virtual_stack)

qim3d.io.Downloader.refresh

refresh()

Fetch the manifest again, replacing the cached catalog on success.

Source code in qim3d/io/_downloader.py
def refresh(self) -> None:
    """Fetch the manifest again, replacing the cached catalog on success."""
    self._datasets = _fetch_manifest(self.manifest_url, self.timeout)

qim3d.io.Downloader.show_datasets

show_datasets()

Print a table of the datasets with their categories and volume sizes.

Source code in qim3d/io/_downloader.py
def show_datasets(self) -> None:
    """Print a table of the datasets with their categories and volume sizes."""
    rows = [("ID", "Categories", "TIFF", "Zarr")]
    for dataset in self._get_datasets():
        sizes = {
            volume.get("format"): volume.get("size_bytes")
            for volume in dataset.get("volumes") or []
        }
        tiff, zarr = (
            sizeof(size) if type(size) is int and size > 0 else "-"
            for size in (sizes.get("tiff"), sizes.get("zarr"))
        )
        categories = ", ".join(map(str, dataset.get("categories") or []))
        rows.append((str(dataset.get("id")), categories, tiff, zarr))
    widths = [max(len(cell) for cell in column) for column in zip(*rows)]
    for row in rows:
        line = "  ".join(cell.ljust(width) for cell, width in zip(row, widths))
        print(line.rstrip())

qim3d.io.convert

convert(input_path, output_path, chunk_shape=(64, 64, 64))

Convert a file to another format without loading the entire file into memory

Parameters:

Name Type Description Default
input_path str

path to the input file

required
output_path str

path to the output file

required
chunk_shape tuple

chunk size for the zarr file. Defaults to (64, 64, 64).

(64, 64, 64)
Source code in qim3d/io/_convert.py
def convert(
    input_path: str, output_path: str, chunk_shape: tuple = (64, 64, 64)
) -> None:
    """
    Convert a file to another format without loading the entire file into memory

    Args:
        input_path (str): path to the input file
        output_path (str): path to the output file
        chunk_shape (tuple, optional): chunk size for the zarr file. Defaults to (64, 64, 64).

    """
    converter = Convert(chunk_shape=chunk_shape)
    converter.convert(input_path, output_path)

qim3d.io.export_ome_zarr

export_ome_zarr(path, data, chunk_size=256, downsample_rate=2, order=1, replace=False, method='scaleZYXdask_coarsen', progress_bar=True, progress_bar_repeat_time='auto')

Exports 3D data to the OME-Zarr (NGFF) format with multi-scale pyramidal levels.

Generates a Next Generation File Format (NGFF) representation of the input volume. This format creates a multi-resolution pyramid (downsampled copies), allowing for efficient visualization and streaming of large datasets over networks or the cloud.

Key Features:

  • Chunking: Data is divided into small blocks (chunk_size) for efficient random access.
  • Pyramidal Levels: Automatically calculates and generates lower-resolution levels until the dataset fits within a single chunk.
  • Dask Integration: efficiently handles larger-than-memory datasets by processing chunks in parallel.

Parameters:

Name Type Description Default
path str or PathLike

The destination directory path. The directory will be created as a Zarr group. (E.g. "data.zarr").

required
data ndarray or Array

The 3D image volume to export.

required
chunk_size int

The size of the chunks (cubes) for storage (e.g., 256 creates 256x256x256 blocks). Smaller chunks improve access time for specific regions but increase file count.

256
downsample_rate int

The reduction factor between pyramid levels. A rate of 2 means each level is half the size of the previous one.

2
order int

The interpolation order for downsampling. 0 = Nearest Neighbor (faster) and 1 = Linear.

1
replace bool

If True, deletes the existing directory at path before writing. If False, raises an error if the directory exists.

False
method str

The downsampling strategy. "scaleZYXdask_coarsen" uses block averaging (faster, reduces noise). "scaleZYXdask" uses interpolation (slower, potentially sharper).

'scaleZYXdask_coarsen'
progress_bar bool

If True, displays a progress bar tracking the chunk writing process.

True
progress_bar_repeat_time str or int

Interval in seconds for updating the progress bar.

'auto'

Raises:

Type Description
ValueError

If path exists and replace=False.

ValueError

If downsample_rate <= 1.

Example
import qim3d

# Load a sample dataset
downloader = qim3d.io.Downloader()
data = downloader.load_dataset("escargot", format="zarr")

# Export to OME-Zarr with 2x downsampling per level
qim3d.io.export_ome_zarr("Escargot.zarr", data, chunk_size=128, downsample_rate=2)
Source code in qim3d/io/_ome_zarr.py
def export_ome_zarr(
    path: str | os.PathLike,
    data: np.ndarray | da.core.Array,
    chunk_size: int = 256,
    downsample_rate: int = 2,
    order: int = 1,
    replace: bool = False,
    method: str = "scaleZYXdask_coarsen",
    progress_bar: bool = True,
    progress_bar_repeat_time: str = "auto",
) -> None:
    """
    Exports 3D data to the OME-Zarr (NGFF) format with multi-scale pyramidal levels.

    Generates a **Next Generation File Format (NGFF)** representation of the input volume.
    This format creates a multi-resolution pyramid (downsampled copies), allowing for efficient
    visualization and streaming of large datasets over networks or the cloud.

    **Key Features:**

    * **Chunking:** Data is divided into small blocks (`chunk_size`) for efficient random access.
    * **Pyramidal Levels:** Automatically calculates and generates lower-resolution levels
      until the dataset fits within a single chunk.
    * **Dask Integration:** efficiently handles larger-than-memory datasets by processing chunks in parallel.

    Args:
        path (str or os.PathLike):
            The destination directory path. The directory will be created as a Zarr group. (E.g. `"data.zarr"`).
        data (numpy.ndarray or dask.array.Array):
            The 3D image volume to export.
        chunk_size (int, optional):
            The size of the chunks (cubes) for storage (e.g., `256` creates 256x256x256 blocks).
            Smaller chunks improve access time for specific regions but increase file count.
        downsample_rate (int, optional):
            The reduction factor between pyramid levels. A rate of `2` means each level is
            half the size of the previous one.
        order (int, optional):
            The interpolation order for downsampling. `0` = Nearest Neighbor (faster) and `1` = Linear.
        replace (bool, optional):
            If `True`, deletes the existing directory at `path` before writing.
            If `False`, raises an error if the directory exists.
        method (str, optional):
            The downsampling strategy.
            `"scaleZYXdask_coarsen"` uses block averaging (faster, reduces noise).
            `"scaleZYXdask"` uses interpolation (slower, potentially sharper).
        progress_bar (bool, optional):
            If `True`, displays a progress bar tracking the chunk writing process.
        progress_bar_repeat_time (str or int, optional):
            Interval in seconds for updating the progress bar.

    Raises:
        ValueError: If `path` exists and `replace=False`.
        ValueError: If `downsample_rate` <= 1.

    Example:
        ```python
        import qim3d

        # Load a sample dataset
        downloader = qim3d.io.Downloader()
        data = downloader.load_dataset("escargot", format="zarr")

        # Export to OME-Zarr with 2x downsampling per level
        qim3d.io.export_ome_zarr("Escargot.zarr", data, chunk_size=128, downsample_rate=2)
        ```
    """

    # Check if directory exists
    if os.path.exists(path):
        if replace:
            shutil.rmtree(path)
        else:
            raise ValueError(
                f"Directory {path} already exists. Use replace=True to overwrite."
            )

    # Check if downsample_rate is valid
    if downsample_rate <= 1:
        raise ValueError("Downsample rate must be greater than 1.")

    _logger.info(f"Exporting data to OME-Zarr format at {path}")

    # Get the number of scales
    min_dim = np.max(np.shape(data))
    nscales = math.ceil(math.log(min_dim / chunk_size) / math.log(downsample_rate))
    _logger.info(f"Number of scales: {nscales + 1}")

    # Create scaler
    scaler = OMEScaler(
        downscale=downsample_rate, max_layer=nscales, method=method, order=order
    )

    # write the image data
    os.mkdir(path)
    store = parse_url(path, mode="w").store
    root = zarr.group(store=store)

    # Check if we want to process using Dask
    if "dask" in method and not isinstance(data, da.Array):
        _logger.info("\nConverting input data to Dask array")
        data = da.from_array(data, chunks=(chunk_size, chunk_size, chunk_size))
        _logger.info(f" - shape...: {data.shape}\n - chunks..: {data.chunksize}\n")

    elif "dask" in method and isinstance(data, da.Array):
        _logger.info("\nInput data will be rechunked")
        data = data.rechunk((chunk_size, chunk_size, chunk_size))
        _logger.info(f" - shape...: {data.shape}\n - chunks..: {data.chunksize}\n")

    _logger.info("Calculating the multi-scale pyramid")

    # Generate multi-scale pyramid
    mip = scaler.func(data)

    _logger.info("Writing data to disk")
    kwargs = dict(
        pyramid=mip,
        group=root,
        fmt=CurrentFormat(),
        axes="zyx",
        name=None,
        compute=True,
        storage_options=dict(chunks=(chunk_size, chunk_size, chunk_size)),
    )
    if progress_bar:
        # Get number of chunks for each shape and sum them together
        n_chunks = sum(
            [
                np.prod(np.ceil(np.array(scaled_data.shape) / chunk_size))
                for scaled_data in mip
            ]
        )

        with OmeZarrExportProgressBar(
            path=path, n_chunks=n_chunks, reapeat_time=progress_bar_repeat_time
        ):
            write_multiscale(**kwargs)
    else:
        write_multiscale(**kwargs)

    _logger.info("\nAll done!")

    return

qim3d.io.import_ome_zarr

import_ome_zarr(path, scale=0, load=True)

Imports or reads image data from an OME-Zarr (NGFF) container.

Allows reading specific resolution levels from a multi-scale dataset. This is particularly useful for previewing large datasets by loading a coarse scale before fetching the full-resolution data.

Parameters:

Name Type Description Default
path str or PathLike

The path to the OME-Zarr file (directory).

required
scale int or str

The resolution level to load. 0 is the full resolution (finest). Higher integers are progressively lower resolutions. Can also accept 'highest' (alias for 0) or 'lowest' (coarsest available scale).

0
load bool

If True, reads the data into memory as a numpy.ndarray. If False, returns a dask.array.Array for lazy loading/processing.

True

Returns:

Name Type Description
vol ndarray or Array

The requested image data.

  • numpy.ndarray: The full image data loaded into memory (if load=True).
  • dask.array.Array: A lazy-loaded Dask array connected to the Zarr store (if load=False).

Raises: ValueError: If the requested scale index exceeds the available levels in the dataset, or if no OME-Zarr image is found at path.

Example
import qim3d

# 1. Load the full resolution data into memory
data = qim3d.io.import_ome_zarr("Escargot.zarr", scale=0, load=True)

# 2. Lazy load the lowest resolution (thumbnail/preview)
preview_lazy = qim3d.io.import_ome_zarr("Escargot.zarr", scale='lowest', load=False)
print(preview_lazy.shape)
Source code in qim3d/io/_ome_zarr.py
def import_ome_zarr(
    path: str | os.PathLike,
    scale: int | Literal["lowest", "highest"] = 0,
    load: bool = True,
) -> np.ndarray:
    """
    Imports or reads image data from an OME-Zarr (NGFF) container.

    Allows reading specific resolution levels from a multi-scale dataset. This is particularly
    useful for previewing large datasets by loading a coarse scale before fetching the full-resolution data.

    Args:
        path (str or os.PathLike):
            The path to the OME-Zarr file (directory).
        scale (int or str, optional):
            The resolution level to load.
            `0` is the full resolution (finest). Higher integers are progressively lower resolutions.
            Can also accept `'highest'` (alias for 0) or `'lowest'` (coarsest available scale).
        load (bool, optional):
            If `True`, reads the data into memory as a `numpy.ndarray`.
            If `False`, returns a `dask.array.Array` for lazy loading/processing.

    Returns:
        vol (numpy.ndarray or dask.array.Array):
            The requested image data.

            * **numpy.ndarray**: The full image data loaded into memory (if `load=True`).
            * **dask.array.Array**: A lazy-loaded Dask array connected to the Zarr store (if `load=False`).
    Raises:
        ValueError: If the requested `scale` index exceeds the available levels in the dataset,
            or if no OME-Zarr image is found at `path`.

    Example:
        ```python
        import qim3d

        # 1. Load the full resolution data into memory
        data = qim3d.io.import_ome_zarr("Escargot.zarr", scale=0, load=True)

        # 2. Lazy load the lowest resolution (thumbnail/preview)
        preview_lazy = qim3d.io.import_ome_zarr("Escargot.zarr", scale='lowest', load=False)
        print(preview_lazy.shape)
        ```
    """

    # read the image data
    # store = parse_url(path, mode="r").store

    reader = Reader(parse_url(path))
    nodes = list(reader())
    if not nodes:
        raise ValueError(
            f"No OME-Zarr image found at {path}. If it was downloaded with "
            "ome-zarr 0.13 or 0.14, delete it and download it again."
        )
    image_node = nodes[0]
    dask_data = image_node.data

    _logger.info(f"Data contains {len(dask_data)} scales:")
    for i in np.arange(len(dask_data)):
        _logger.info(f"- Scale {i}: {dask_data[i].shape}")

    if scale == "highest":
        scale = 0

    if scale == "lowest":
        scale = len(dask_data) - 1

    if scale >= len(dask_data):
        raise ValueError(
            f"Scale {scale} does not exist in the data. Please choose a scale between 0 and {len(dask_data) - 1}."
        )

    _logger.info(f"\nLoading scale {scale} with shape {dask_data[scale].shape}")

    if load:
        vol = dask_data[scale].compute()
    else:
        vol = dask_data[scale]

    return vol

qim3d.io.load

load(path, virtual_stack=False, dataset_name=None, return_metadata=False, contains=None, force_load=False, dim_order=(2, 1, 0), progress_bar=False, display_memory_usage=False, raw_shape=None, raw_dtype=None, raw_byteorder='<', raw_offset_bytes=0, **kwargs)

General-purpose function to load, import, or read 3D data from various file formats.

Automatically identifies the file format based on the extension and uses the appropriate backend to open the file. It supports a wide range of standard bio-imaging and material science formats.

Supported Formats:

  • Images: TIFF (.tif, .tiff), PIL supported formats (.png, .jpg, etc.)
  • Volumes: DICOM (.dcm), NIfTI (.nii, .nii.gz)
  • HDF5-based: HDF5 (.h5), TXRM/TXM/XRM (.txrm, .txm)
  • Raw/Binary: VGI/VOL (.vgi), RAW (.raw)
  • Cloud/Chunked: Zarr (.zarr)
  • Stacks: Directories containing sequences of 2D images (TIFF or DICOM series).

Memory Management (Virtual Stack):

For datasets that are too large to fit into RAM, use virtual_stack=True. This enables lazy loading (or memory mapping), allowing you to inspect metadata (shape, data type) and slice specific sub-regions of the volume without reading the entire file into memory immediately.

Parameters:

Name Type Description Default
path str or PathLike

The path to the file or directory to load. If a directory is provided, the function attempts to load it as a stack of images (e.g., a DICOM series or TIFF sequence).

required
virtual_stack bool

If True, enables lazy loading. The data is not read into memory until explicitly accessed. Useful for inspecting large files.

False
dataset_name str

Used only for HDF5 files containing multiple datasets. Specifies which internal dataset to load.

None
return_metadata bool

If True, returns a tuple (data, metadata). Currently supported for HDF5, NIfTI, and TXRM/TXM/XRM files.

False
contains str

Used when loading a directory of files (Stack). Specifies a unique substring that must be present in the filenames (e.g., "slice_"). Identifying files by this string helps avoid loading unrelated files in the same folder.

None
force_load bool

Safety override. If the file size exceeds available system memory, a MemoryError is raised. Set this to True to convert the error into a warning and attempt loading anyway.

False
dim_order tuple

Used for .vol files. Defines the dimension order (Z, Y, X).

(2, 1, 0)
progress_bar bool

If True, displays a progress bar during loading (Linux/POSIX only).

False
display_memory_usage bool

If True, prints a report of memory usage after loading.

False
raw_shape tuple[int, int, int] | None

Shape of RAW volume in (X,Y,Z). Required for .raw files.

None
raw_dtype str | dtype | None

Datatype for RAW (e.g. "float32", "uint16"). Required for .raw files.

None
raw_byteorder str

Byte order for RAW. "<" little-endian, ">" big-endian. Default "<".

'<'
raw_offset_bytes int

Header offset in bytes for RAW (usually 0). Default 0.

0
**kwargs Any

Additional arguments passed to the underlying DataLoader class.

{}

Returns:

Name Type Description
vol ndarray, Virtual Stack Object, or tuple

The loaded data.

The specific type depends on the input parameters and file format:

  • numpy.ndarray: Standard in-memory array (if virtual_stack=False).
  • Virtual Stack Object: If virtual_stack=True, returns a lazy-loading object:
    • numpy.memmap (TIFF, VOL)
    • dask.array.Array (Zarr, TXRM)
    • h5py.Dataset (HDF5)
    • nibabel.arrayproxy.ArrayProxy (NIfTI)
  • tuple: (data, metadata) if return_metadata=True.

Raises:

Type Description
MemoryError

If the file is larger than available RAM and force_load=False.

ValueError

If the file format is not supported or the path is invalid.

Example
import qim3d

# 1. Simple load of a single 3D file
vol = qim3d.io.load("path/to/scan.tif")

# 2. Load a large file lazily (virtual stack) to check shape
vol_lazy = qim3d.io.load("path/to/huge_scan.h5", virtual_stack=True)
print(vol_lazy.shape)

# 3. Load a specific dataset from an HDF5 file
vol = qim3d.io.load("data.h5", dataset_name="reconstruction")
Loading from Tiff stack

Volumes can also be loaded from a series of .tiff files. The stack means that we have one file per slice.

import qim3d

# Generate volume
vol = qim3d.generate.volume(noise_scale = 0.015)

# Save as a .tiff stack
# The paremeter `basename` is used for the prefix of the files.
qim3d.io.save("data_directory", vol, basename="blob-slices", sliced_dim=0)

# Load the volume from the .tiff stack
# Here we use `contains` to check the files that have that string in their names
loaded_vol = qim3d.io.load("data_directory" , contains="blob-slices", progress_bar=True)
Source code in qim3d/io/_loading.py
def load(
    path: str | os.PathLike,
    virtual_stack: bool = False,
    dataset_name: str | None = None,
    return_metadata: bool = False,
    contains: bool = None,
    force_load: bool = False,
    dim_order: tuple = (2, 1, 0),
    progress_bar: bool = False,
    display_memory_usage: bool = False,
    raw_shape: tuple[int, int, int] | None = None,
    raw_dtype: str | np.dtype | None = None,
    raw_byteorder: str = "<",
    raw_offset_bytes: int = 0,
    **kwargs,
) -> np.ndarray:
    """
    General-purpose function to load, import, or read 3D data from various file formats.

    Automatically identifies the file format based on the extension and uses the appropriate backend to open the file.
    It supports a wide range of standard bio-imaging and material science formats.

    **Supported Formats:**

    * **Images:** TIFF (`.tif`, `.tiff`), PIL supported formats (`.png`, `.jpg`, etc.)
    * **Volumes:** DICOM (`.dcm`), NIfTI (`.nii`, `.nii.gz`)
    * **HDF5-based:** HDF5 (`.h5`), TXRM/TXM/XRM (`.txrm`, `.txm`)
    * **Raw/Binary:** VGI/VOL (`.vgi`), RAW (`.raw`)
    * **Cloud/Chunked:** Zarr (`.zarr`)
    * **Stacks:** Directories containing sequences of 2D images (TIFF or DICOM series).

    **Memory Management (Virtual Stack):**

    For datasets that are too large to fit into RAM, use `virtual_stack=True`. This enables
    **lazy loading** (or memory mapping), allowing you to inspect metadata (shape, data type)
    and slice specific sub-regions of the volume without reading the entire file into memory immediately.

    Args:
        path (str or os.PathLike):
            The path to the file or directory to load. If a directory is provided, the function
            attempts to load it as a stack of images (e.g., a DICOM series or TIFF sequence).
        virtual_stack (bool, optional):
            If `True`, enables lazy loading. The data is not read into memory until explicitly accessed.
            Useful for inspecting large files.
        dataset_name (str, optional):
            Used only for HDF5 files containing multiple datasets. Specifies which internal dataset
            to load.
        return_metadata (bool, optional):
            If `True`, returns a tuple `(data, metadata)`. Currently supported for HDF5, NIfTI,
            and TXRM/TXM/XRM files.
        contains (str, optional):
            Used when loading a directory of files (Stack). Specifies a unique substring that must
            be present in the filenames (e.g., "slice_"). Identifying files by this string helps
            avoid loading unrelated files in the same folder.
        force_load (bool, optional):
            Safety override. If the file size exceeds available system memory, a `MemoryError`
            is raised. Set this to `True` to convert the error into a warning and attempt loading anyway.
        dim_order (tuple, optional):
            Used for `.vol` files. Defines the dimension order (Z, Y, X).
        progress_bar (bool, optional):
            If `True`, displays a progress bar during loading (Linux/POSIX only).
        display_memory_usage (bool, optional):
            If `True`, prints a report of memory usage after loading.
        raw_shape (tuple[int,int,int] | None, optional):
            Shape of RAW volume in (X,Y,Z). Required for .raw files.
        raw_dtype (str | np.dtype | None, optional):
            Datatype for RAW (e.g. "float32", "uint16"). Required for .raw files.
        raw_byteorder (str, optional):
            Byte order for RAW. "<" little-endian, ">" big-endian. Default "<".
        raw_offset_bytes (int, optional):
            Header offset in bytes for RAW (usually 0). Default 0.
        **kwargs (Any):
            Additional arguments passed to the underlying `DataLoader` class.

    Returns:
        vol (ndarray, Virtual Stack Object, or tuple):
            The loaded data.

            The specific type depends on the input parameters and file format:

            * **numpy.ndarray**: Standard in-memory array (if `virtual_stack=False`).
            * **Virtual Stack Object**: If `virtual_stack=True`, returns a lazy-loading object:
                * `numpy.memmap` (TIFF, VOL)
                * `dask.array.Array` (Zarr, TXRM)
                * `h5py.Dataset` (HDF5)
                * `nibabel.arrayproxy.ArrayProxy` (NIfTI)
            * **tuple**: `(data, metadata)` if `return_metadata=True`.

    Raises:
        MemoryError: If the file is larger than available RAM and `force_load=False`.
        ValueError: If the file format is not supported or the path is invalid.

    Example:
        ```python
        import qim3d

        # 1. Simple load of a single 3D file
        vol = qim3d.io.load("path/to/scan.tif")

        # 2. Load a large file lazily (virtual stack) to check shape
        vol_lazy = qim3d.io.load("path/to/huge_scan.h5", virtual_stack=True)
        print(vol_lazy.shape)

        # 3. Load a specific dataset from an HDF5 file
        vol = qim3d.io.load("data.h5", dataset_name="reconstruction")
        ```

    Example: Loading from Tiff stack
        Volumes can also be loaded from a series of `.tiff` files. The stack means that we have one file per slice.

        ```python
        import qim3d

        # Generate volume
        vol = qim3d.generate.volume(noise_scale = 0.015)

        # Save as a .tiff stack
        # The paremeter `basename` is used for the prefix of the files.
        qim3d.io.save("data_directory", vol, basename="blob-slices", sliced_dim=0)

        # Load the volume from the .tiff stack
        # Here we use `contains` to check the files that have that string in their names
        loaded_vol = qim3d.io.load("data_directory" , contains="blob-slices", progress_bar=True)
        ```
    """

    loader = DataLoader(
        virtual_stack=virtual_stack,
        dataset_name=dataset_name,
        return_metadata=return_metadata,
        contains=contains,
        force_load=force_load,
        dim_order=dim_order,
        raw_shape=raw_shape,
        raw_dtype=raw_dtype,
        raw_byteorder=raw_byteorder,
        raw_offset_bytes=raw_offset_bytes,
        **kwargs,
    )

    if progress_bar and os.name == "posix":
        with FileLoadingProgressBar(path):
            data = loader.load(path)
    else:
        data = loader.load(path)

    def log_memory_info(data: np.ndarray) -> None:
        mem = Memory()
        _logger.info(
            "Volume using %s of memory\n",
            sizeof(data[0].nbytes if isinstance(data, tuple) else data.nbytes),
        )
        mem.report()

    if return_metadata and not isinstance(data, tuple):
        _logger.warning("The file format does not contain metadata")

    if not virtual_stack:
        if display_memory_usage:
            log_memory_info(data)
    else:
        # Only log if file type is not a np.ndarray, i.e., it is some kind of memmap object
        if not isinstance(
            type(data[0]) if isinstance(data, tuple) else type(data), np.ndarray
        ):
            _logger.info("Using virtual stack")
        else:
            _logger.warning("Virtual stack is not supported for this file format")
            if display_memory_usage:
                log_memory_info(data)

    return data

qim3d.io.load_mesh

load_mesh(filename)

Imports or loads a 3D surface mesh from a file.

Reads geometry data from standard mesh formats and returns a PyGEL3D Manifold object. This is useful for analyzing surface structures, isosurfaces, or exported models.

Supported Formats:

  • OBJ (.obj) - Wavefront Object
  • PLY (.ply) - Polygon File Format
  • OFF (.off) - Object File Format
  • X3D (.x3d) - Extensible 3D

Parameters:

Name Type Description Default
filename str or PathLike

The path to the mesh file to load.

required

Returns:

Name Type Description
mesh Manifold or None

A PyGEL3D object containing the mesh geometry (vertices, faces, edges). Returns None if loading fails.

Example
import qim3d

# Load a mesh file
mesh = qim3d.io.load_mesh("path/to/model.obj")

# Check number of vertices
print(len(mesh.vertices()))
Source code in qim3d/io/_loading.py
def load_mesh(filename: str) -> hmesh.Manifold:
    """
    Imports or loads a 3D surface mesh from a file.

    Reads geometry data from standard mesh formats and returns a PyGEL3D Manifold object.
    This is useful for analyzing surface structures, isosurfaces, or exported models.

    **Supported Formats:**

    * **OBJ** (`.obj`) - Wavefront Object
    * **PLY** (`.ply`) - Polygon File Format
    * **OFF** (`.off`) - Object File Format
    * **X3D** (`.x3d`) - Extensible 3D

    Args:
        filename (str or os.PathLike):
            The path to the mesh file to load.

    Returns:
        mesh (Manifold or None):
            A PyGEL3D object containing the mesh geometry (vertices, faces, edges).
            Returns `None` if loading fails.

    Example:
        ```python
        import qim3d

        # Load a mesh file
        mesh = qim3d.io.load_mesh("path/to/model.obj")

        # Check number of vertices
        print(len(mesh.vertices()))
        ```
    """
    mesh = hmesh.load(filename)

    return mesh

qim3d.io.save

save(path, data, replace=False, compression=False, basename=None, sliced_dim=0, chunk_shape='auto', **kwargs)

General-purpose function to save, export, or write 3D data to disk.

Automatically detects the desired file format based on the filename extension. Supports saving entire volumes as single files or exporting them as a sequence of 2D slices (stack).

Supported Formats:

  • Images: TIFF (.tif), standard image formats (.png, .jpg, .bmp, etc.)
  • Volumes: TIFF (.tif), NIfTI (.nii, .nii.gz), HDF5 (.h5)
  • Cloud/Chunked: Zarr (.zarr)
  • Medical: DICOM (.dcm) - Saves as a series if a directory is provided.

Parameters:

Name Type Description Default
path str or PathLike

The destination path. Can be a filename (e.g., volume.tif) or a directory (e.g., slices/) if saving a stack.

required
data ndarray or Array

The 2D or 3D image data to be saved.

required
replace bool

If True, overwrites the file if it already exists. If False, raises a FileExistsError to prevent accidental data loss.

False
compression bool

If True, applies lossless compression (e.g., Deflate for HDF5/TIFF) to reduce file size.

False
basename str

Used when saving a 3D volume as a stack of 2D files. Defines the common prefix for the filenames (e.g., basename="slice" results in slice_000.tif, slice_001.tif).

None
sliced_dim int

The dimension along which to slice the volume when saving as a stack. Usually 0 (Z-axis).

0
**kwargs Any

Additional arguments passed to the specific backend saver.

{}

Raises:

Type Description
FileExistsError

If replace=False and the destination already exists.

ValueError

If the file extension is not supported.

Example
import qim3d
import numpy as np

# Generate sample data
vol = qim3d.generate.volume(noise_scale=0.015)

# 1. Save as a single 3D TIFF file
qim3d.io.save("output_volume.tif", vol)

# 2. Save as an HDF5 file with compression
qim3d.io.save("output_volume.h5", vol, compression=True)
Saving as a Stack of Slices

To save a 3D volume as individual 2D images (e.g., for inspection in standard image viewers), provide a directory path and a basename.

import qim3d

vol = qim3d.generate.volume()

# Save as slice_000.tif, slice_001.tif, etc. inside the 'slices' folder
qim3d.io.save("slices_folder", vol, basename="slice", sliced_dim=0)
Source code in qim3d/io/_saving.py
def save(
    path: str | os.PathLike,
    data: np.ndarray,
    replace: bool = False,
    compression: bool = False,
    basename: bool = None,
    sliced_dim: int = 0,
    chunk_shape: str = "auto",
    **kwargs,
) -> None:
    """
    General-purpose function to save, export, or write 3D data to disk.

    Automatically detects the desired file format based on the filename extension.
    Supports saving entire volumes as single files or exporting them as a sequence
    of 2D slices (stack).

    **Supported Formats:**

    * **Images:** TIFF (`.tif`), standard image formats (`.png`, `.jpg`, `.bmp`, etc.)
    * **Volumes:** TIFF (`.tif`), NIfTI (`.nii`, `.nii.gz`), HDF5 (`.h5`)
    * **Cloud/Chunked:** Zarr (`.zarr`)
    * **Medical:** DICOM (`.dcm`) - *Saves as a series if a directory is provided.*

    Args:
        path (str or os.PathLike):
            The destination path. Can be a filename (e.g., `volume.tif`) or a directory
            (e.g., `slices/`) if saving a stack.
        data (numpy.ndarray or dask.array.Array):
            The 2D or 3D image data to be saved.
        replace (bool, optional):
            If `True`, overwrites the file if it already exists. If `False`, raises a
            `FileExistsError` to prevent accidental data loss.
        compression (bool, optional):
            If `True`, applies lossless compression (e.g., Deflate for HDF5/TIFF) to reduce file size.
        basename (str, optional):
            Used when saving a 3D volume as a stack of 2D files. Defines the common prefix
            for the filenames (e.g., `basename="slice"` results in `slice_000.tif`, `slice_001.tif`).
        sliced_dim (int, optional):
            The dimension along which to slice the volume when saving as a stack.
            Usually `0` (Z-axis).
        **kwargs (Any):
            Additional arguments passed to the specific backend saver.


    Raises:
        FileExistsError: If `replace=False` and the destination already exists.
        ValueError: If the file extension is not supported.

    Example:
        ```python
        import qim3d
        import numpy as np

        # Generate sample data
        vol = qim3d.generate.volume(noise_scale=0.015)

        # 1. Save as a single 3D TIFF file
        qim3d.io.save("output_volume.tif", vol)

        # 2. Save as an HDF5 file with compression
        qim3d.io.save("output_volume.h5", vol, compression=True)
        ```

    Example: Saving as a Stack of Slices
        To save a 3D volume as individual 2D images (e.g., for inspection in standard image viewers),
        provide a directory `path` and a `basename`.

        ```python
        import qim3d

        vol = qim3d.generate.volume()

        # Save as slice_000.tif, slice_001.tif, etc. inside the 'slices' folder
        qim3d.io.save("slices_folder", vol, basename="slice", sliced_dim=0)
        ```

    """

    DataSaver(
        replace=replace,
        compression=compression,
        basename=basename,
        sliced_dim=sliced_dim,
        chunk_shape=chunk_shape,
        **kwargs,
    ).save(path, data)

qim3d.io.save_mesh

save_mesh(filename, mesh)

Exports or saves a 3D surface mesh to a file.

Writes the geometry of a PyGEL3D Manifold object to disk. The output format is determined automatically by the filename extension.

Supported Formats:

  • OBJ (.obj)
  • OFF (.off)
  • X3D (.x3d)

Parameters:

Name Type Description Default
filename str or PathLike

The destination path. The extension determines the format.

required
mesh Manifold

The mesh object containing the geometry to be saved.

required
Example
import qim3d

# Generate a volume and extract a mesh (isosurface)
vol = qim3d.generate.volume(noise_scale=0.05)
mesh = qim3d.mesh.from_volume(vol)

# Save the mesh to an OBJ file
qim3d.io.save_mesh("surface.obj", mesh)
Source code in qim3d/io/_saving.py
def save_mesh(filename: str, mesh: hmesh.Manifold) -> None:
    """
    Exports or saves a 3D surface mesh to a file.

    Writes the geometry of a PyGEL3D Manifold object to disk. The output format is
    determined automatically by the filename extension.

    **Supported Formats:**

    * **OBJ** (`.obj`)
    * **OFF** (`.off`)
    * **X3D** (`.x3d`)

    Args:
        filename (str or os.PathLike):
            The destination path. The extension determines the format.
        mesh (hmesh.Manifold):
            The mesh object containing the geometry to be saved.

    Example:
        ```python
        import qim3d

        # Generate a volume and extract a mesh (isosurface)
        vol = qim3d.generate.volume(noise_scale=0.05)
        mesh = qim3d.mesh.from_volume(vol)

        # Save the mesh to an OBJ file
        qim3d.io.save_mesh("surface.obj", mesh)
        ```

    """
    # Export the mesh to the specified filename
    hmesh.save(filename, mesh)