diff --git a/README.md b/README.md index 641b3c3..64cd7bb 100644 --- a/README.md +++ b/README.md @@ -38,7 +38,8 @@ pip install bioio-conversion * **Features**: * Multi-scene export (`scenes=0`, list, or `None` = all) - * Flexible multiscale pyramid options (`level_shapes`, `num_levels`, `downsample_z`) + * Flexible multiscale pyramid options (`level_shapes`, `num_levels`, `downsample_z`, `downsample_filter`) + (`downsample_filter="linear"` is not for segmentations or label images) * Chunk-size tuning (`chunk_shape`, `memory_target`, `shard_shape`) * Metadata options (`channels`, `axes_names`, `axes_units`, `axes_types`, `physical_pixel_size`) * Output format (`zarr_format` = 2 or 3) @@ -253,6 +254,9 @@ bioio-convert SOURCE -d DESTINATION [options] (and optionally Z). * `--downsample-z`: when used with `--num-levels`, also halves the Z dimension at each level if a Z axis exists. +* `--downsample-filter`: `nearest` (default) or `linear`. **Do not use + `linear` for segmentations or label images**: interpolation creates label + values that are not in the data. **Chunking / sharding (advanced)** diff --git a/bioio_conversion/bin/ome_zarr_options.py b/bioio_conversion/bin/ome_zarr_options.py index 7e2af0f..9b91616 100644 --- a/bioio_conversion/bin/ome_zarr_options.py +++ b/bioio_conversion/bin/ome_zarr_options.py @@ -4,6 +4,7 @@ Callable, Dict, List, + Literal, Optional, Sequence, Tuple, @@ -39,6 +40,7 @@ class OmeZarrInitOptions(TypedDict, total=False): level_shapes: MultiResolutionShapeSpec num_levels: int downsample_z: bool + downsample_filter: Literal["nearest", "linear"] # chunking / sharding chunk_shape: MultiResolutionShapeSpec @@ -609,6 +611,16 @@ def _decorator(fn: F) -> F: "pyramid level when a Z axis exists." ), ), + click.option( + "--downsample-filter", + type=click.Choice(["nearest", "linear"], case_sensitive=False), + default=None, + help=( + "Filter used to downsample pyramid levels. 'nearest' is " + "the default. Do not use 'linear' for segmentations or " + "label images." + ), + ), click.option( "--level-shapes", type=IntTupleListType(), @@ -749,6 +761,9 @@ def build_ome_zarr_init_opts(**kwargs: Any) -> OmeZarrInitOptions: if downsample_z: init_opts["downsample_z"] = True + if kwargs.get("downsample_filter") is not None: + init_opts["downsample_filter"] = kwargs["downsample_filter"].lower() + # Chunk/shard: normalize per-level vs single tuple if kwargs.get("chunk_shape_per_level"): init_opts["chunk_shape"] = kwargs["chunk_shape_per_level"] diff --git a/bioio_conversion/converters/ome_zarr_converter.py b/bioio_conversion/converters/ome_zarr_converter.py index 3690bd6..0865aa2 100644 --- a/bioio_conversion/converters/ome_zarr_converter.py +++ b/bioio_conversion/converters/ome_zarr_converter.py @@ -3,7 +3,7 @@ import warnings from concurrent.futures import ProcessPoolExecutor from pathlib import Path -from typing import Any, Dict, List, Optional, Sequence, Tuple, Union +from typing import Any, Dict, List, Literal, Optional, Sequence, Tuple, Union import fsspec import numcodecs @@ -55,6 +55,7 @@ def _write_shard_process( src_bounds: _Bounds, dest_bounds: _Bounds, channel_order: Optional[Tuple[int, ...]] = None, + downsample_filter: Literal["nearest", "linear"] = "nearest", ) -> None: """ Read one shard from the source and write it to an already-initialized @@ -89,7 +90,7 @@ def _write_shard_process( ) # Attach to the store the parent already initialized and write this shard. - writer = OMEZarrWriter.open(store_path) + writer = OMEZarrWriter.open(store_path, downsample_filter=downsample_filter) writer.write_region(shard_data, dest_region) @@ -124,6 +125,7 @@ def __init__( physical_pixel_size: Optional[List[float]] = None, num_levels: Optional[int] = None, downsample_z: bool = False, + downsample_filter: Literal["nearest", "linear"] = "nearest", memory_target: Optional[int] = None, start_t_src: Optional[int] = None, start_t_dest: Optional[int] = None, @@ -214,6 +216,10 @@ def __init__( downsample_z : bool, default = False Also halve Z at each level when building the ``num_levels`` pyramid. Ignored if ``level_shapes`` is provided. + downsample_filter : Literal["nearest", "linear"], default = "nearest" + Filter used to downsample lower pyramid levels. Do not use + ``"linear"`` for segmentations or label images, since interpolation + creates label values that are not in the data. memory_target : Optional[int] Chunk budget in bytes. For ``zarr_format=3`` this is passed as ``chunk_limit_bytes`` to the auto-chunk/shard layout; for other @@ -288,6 +294,7 @@ def __init__( # Helpers self._helper_num_levels = num_levels self._helper_downsample_z = downsample_z + self._downsample_filter = downsample_filter # Chunk suggestion self._helper_memory_target_bytes = ( @@ -667,6 +674,7 @@ def _plan_and_dispatch_scene( "axes_units": self._infer_axes_units(axis_names), "physical_pixel_size": pps, "attributes": bioio_attrs, + "downsample_filter": self._downsample_filter, }.items() if v is not None }, @@ -699,6 +707,7 @@ def _plan_and_dispatch_scene( src_bounds, dest_bounds, channel_order, + self._downsample_filter, ) scene_futures.append(pool.submit(_write_shard_process, *task)) else: diff --git a/bioio_conversion/tests/converters/test_ome_zarr_converter.py b/bioio_conversion/tests/converters/test_ome_zarr_converter.py index 655adc2..711edd7 100644 --- a/bioio_conversion/tests/converters/test_ome_zarr_converter.py +++ b/bioio_conversion/tests/converters/test_ome_zarr_converter.py @@ -1,7 +1,7 @@ import os import pathlib import re -from typing import List, Optional, Tuple, Union +from typing import List, Literal, Optional, Tuple, Union import pytest from bioio import BioImage @@ -204,6 +204,35 @@ def test_zarr_resolution_levels( assert actual_shapes == expected_shapes +@pytest.mark.parametrize("zarr_format", [2, 3]) +def test_downsample_filter_linear_changes_lower_levels( + tmp_path: pathlib.Path, zarr_format: int +) -> None: + # Arrange + src_path = LOCAL_RESOURCES_DIR / "s_3_t_1_c_3_z_5.ome.tiff" + + # Act + filters: Tuple[Literal["nearest", "linear"], ...] = ("nearest", "linear") + for downsample_filter in filters: + OmeZarrConverter( + source=str(src_path), + destination=str(tmp_path), + name=downsample_filter, + scenes=0, + num_levels=2, + zarr_format=zarr_format, + downsample_filter=downsample_filter, + ).convert() + + # Assert + nearest = BioImage(str(tmp_path / "nearest_Image_0.ome.zarr")).reader + linear = BioImage(str(tmp_path / "linear_Image_0.ome.zarr")).reader + assert_array_equal(nearest.get_image_data("TCZYX"), linear.get_image_data("TCZYX")) + nearest.set_resolution_level(1) + linear.set_resolution_level(1) + assert not (nearest.get_image_data("TCZYX") == linear.get_image_data("TCZYX")).all() + + @pytest.mark.parametrize( "filename, explicit_shapes, expected_zarr_name", [ diff --git a/bioio_conversion/tests/test_conversion_cli.py b/bioio_conversion/tests/test_conversion_cli.py index 2a93dfb..676d286 100644 --- a/bioio_conversion/tests/test_conversion_cli.py +++ b/bioio_conversion/tests/test_conversion_cli.py @@ -134,6 +134,51 @@ def _provenance_block(store: pathlib.Path) -> dict: return json.load(fh)["attributes"][PROVENANCE_ATTR_KEY] +def test_cli_downsample_filter_rejects_unknown_value(tmp_path: pathlib.Path) -> None: + # Arrange + runner = CliRunner() + tiff = LOCAL_RESOURCES_DIR / "s_1_t_1_c_1_z_1.ome.tiff" + + # Act + result = runner.invoke( + main, + [str(tiff), "-d", str(tmp_path), "--downsample-filter", "bilinear"], + ) + + # Assert + assert result.exit_code != 0 + assert "--downsample-filter" in result.output + + +def test_cli_downsample_filter_linear(tmp_path: pathlib.Path) -> None: + # Arrange + runner = CliRunner() + tiff = LOCAL_RESOURCES_DIR / "s_3_t_1_c_3_z_5.ome.tiff" + + # Act + result = runner.invoke( + main, + [ + str(tiff), + "-d", + str(tmp_path), + "-n", + "lin", + "-s", + "0", + "--num-levels", + "2", + "--downsample-filter", + "linear", + ], + ) + + # Assert + assert result.exit_code == 0, result.output + reader = BioImage(str(tmp_path / "lin_Image_0.ome.zarr")).reader + assert len(reader.resolution_levels) == 2 + + def test_cli_include_provenance(tmp_path: pathlib.Path) -> None: """--include-provenance writes the provenance block and its sidecars.""" # Arrange diff --git a/pyproject.toml b/pyproject.toml index f2fe2d8..badef30 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -32,7 +32,7 @@ dynamic = ["version"] dependencies = [ "bioio>=3.0.0", "bioio-base>=3.4.0", - "bioio-ome-zarr>=3.6.0", + "bioio-ome-zarr>=4.1.0", "numpy>=1.24.0", "dask>=2021.10.0", "numcodecs>=0.10.0",