diff --git a/CHANGELOG.md b/CHANGELOG.md
index 8dacce07..2fa4f490 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,11 @@
# Changelog
+## [Unreleased]
+
+### Features
+
+- `by_grid(..., anchor="roi")` tiles each region from its own pixel origin and applies the tail policy at that region's bounds ([#246](https://github.com/BioVisionCenter/ngio/issues/246)).
+
## [v1.1.5]
### Fixes
diff --git a/docs/getting_started/6_iterators.md b/docs/getting_started/6_iterators.md
index 8ea5cb2e..fe9790f5 100644
--- a/docs/getting_started/6_iterators.md
+++ b/docs/getting_started/6_iterators.md
@@ -237,6 +237,26 @@ shape otherwise, inspectable as `image.write_granularity` — which makes parall
writes collision-free by construction, so a parallel `map` runs as a single
fully-parallel wave.
+Use `anchor="roi"` to start a fresh grid in each field of view, well, or other
+region. With the default `anchor="image"`, the grid starts at the image origin
+and gets clipped to each region.
+
+```python
+tiles = (
+ SegmentationIterator(image, label)
+ .product(fov_table)
+ .by_grid(
+ size_y=100, size_x=100, stride_y=90, stride_x=90,
+ anchor="roi", tail="shift",
+ )
+ .with_stitch()
+)
+```
+
+Here `shift` keeps tiles full-size in each field of view that can fit one. The
+last tile on each axis may overlap its neighbour by more than the usual 10
+pixels. An open ROI bound uses the corresponding image bound.
+
diff --git a/src/ngio/iterators/_abstract_iterator.py b/src/ngio/iterators/_abstract_iterator.py
index 24720404..f71ed109 100644
--- a/src/ngio/iterators/_abstract_iterator.py
+++ b/src/ngio/iterators/_abstract_iterator.py
@@ -295,6 +295,7 @@ def by_grid(
stride_z: int | None = None,
stride_t: int | None = None,
tail: TailPolicy = "clip",
+ anchor: Literal["image", "roi"] = "image",
base_name: str = "",
) -> Self:
"""Tile the current ROIs with a regular grid.
@@ -318,6 +319,11 @@ def by_grid(
neighbour, so a writing iterator needs a merge or serial
execution; `"drop"` discards the tail and leaves that border
uncovered.
+ anchor: `"image"` (default) builds one grid over the reference image
+ and intersects it with the ROIs. `"roi"` starts a grid at each
+ ROI's pixel origin and applies `tail` to its extent. Open
+ bounds use the corresponding image bounds. With `tail="shift"`,
+ the last tile in each ROI can overlap more than the stride implies.
base_name: Prefix for the generated tile names.
Returns:
@@ -335,6 +341,7 @@ def by_grid(
stride_z=stride_z,
stride_t=stride_t,
tail=tail,
+ anchor=anchor,
base_name=base_name,
)
return self._new_from_rois(rois)
diff --git a/src/ngio/iterators/_rois_utils.py b/src/ngio/iterators/_rois_utils.py
index 8e60eb57..12305abd 100644
--- a/src/ngio/iterators/_rois_utils.py
+++ b/src/ngio/iterators/_rois_utils.py
@@ -1,9 +1,10 @@
import itertools
import math
-from collections.abc import Mapping
+from collections.abc import Iterator, Mapping
from typing import Literal
from ngio.common import Roi
+from ngio.common._roi import _join_roi_names
from ngio.images._abstract_image import AbstractImage
from ngio.utils import NgioValueError
@@ -183,27 +184,50 @@ def _axis_partition(axis_name: str, dim: int, num: int) -> list[tuple[int, int]]
return list(zip(starts, lengths, strict=True))
-def _intervals_to_rois(
- rois: list[Roi],
+def _grid_tiles(
ref_image: AbstractImage,
intervals: dict[str, list[tuple[int, int]]],
base_name: str,
-) -> list[Roi]:
- """Cross the per-axis intervals into named tiles, intersected with `rois`."""
- new_rois = []
+) -> Iterator[Roi]:
+ """Cross the per-axis pixel intervals into named world-space tiles."""
for combo in itertools.product(*(intervals[axis] for axis in _GRID_AXES)):
- starts = {
- axis: start for axis, (start, _) in zip(_GRID_AXES, combo, strict=True)
- }
- tile_name = "_".join(f"{axis}{starts[axis]}" for axis in _GRID_AXES)
+ slices = dict(zip(_GRID_AXES, combo, strict=True))
+ tile_name = "_".join(f"{axis}{start}" for axis, (start, _) in slices.items())
name = f"{base_name}_{tile_name}" if base_name else tile_name
- roi = Roi.from_values(
- name=name,
- slices=dict(zip(_GRID_AXES, combo, strict=True)),
- space="pixel",
+ yield Roi.from_values(name=name, slices=slices, space="pixel").to_world(
+ pixel_size=ref_image.pixel_size
)
- new_rois.append(roi.to_world(pixel_size=ref_image.pixel_size))
- return rois_product(rois, new_rois)
+
+
+def _grid_intervals(
+ ref_image: AbstractImage,
+ sizes: Mapping[str, int | None],
+ strides: Mapping[str, int | None],
+ tail: TailPolicy,
+ roi_px: Roi | None = None,
+) -> dict[str, list[tuple[int, int]]]:
+ """Tile each axis within the image or the ROI's readable pixel bounds."""
+ intervals = {}
+ for axis in _GRID_AXES:
+ dim = ref_image.dimensions.get(axis, default=1)
+ start, stop = 0, dim
+ if roi_px is not None and (bounds := roi_px.get(axis)) is not None:
+ # Use the same floor/ceil and clipping as array slicing.
+ if bounds.start is not None:
+ start = max(0, min(math.floor(bounds.start), dim))
+ if bounds.end is not None:
+ stop = max(0, min(math.ceil(bounds.end), dim))
+
+ extent = stop - start
+ size = sizes[axis]
+ if size is None:
+ size = extent
+ stride = strides[axis]
+ if stride is None:
+ stride = size
+ axis_tiles = _axis_intervals(axis, extent, size, stride, tail)
+ intervals[axis] = [(start + offset, length) for offset, length in axis_tiles]
+ return intervals
def by_grid(
@@ -219,6 +243,7 @@ def by_grid(
stride_z: int | None = None,
stride_t: int | None = None,
tail: TailPolicy = "clip",
+ anchor: Literal["image", "roi"] = "image",
base_name: str = "",
) -> list[Roi]:
"""Tile the ROIs with a regular grid of tiles.
@@ -227,23 +252,33 @@ def by_grid(
strides default to the sizes (adjacent, non-overlapping tiles); a stride
smaller than the size produces overlapping tiles. `tail` decides what
happens where the grid does not divide the axis — see `_axis_intervals`.
- The grid is intersected with the existing ROIs, so tiling composes with
- `product` and ROI tables.
+ Anchor the grid to the image and intersect it with the existing ROIs, or
+ anchor to each ROI and apply the tail policy at its own bounds.
"""
sizes = {"t": size_t, "z": size_z, "y": size_y, "x": size_x}
strides = {"t": stride_t, "z": stride_z, "y": stride_y, "x": stride_x}
- intervals: dict[str, list[tuple[int, int]]] = {}
- for axis in _GRID_AXES:
- dim = ref_image.dimensions.get(axis, default=1)
- size = sizes[axis]
- if size is None:
- size = dim
- stride = strides[axis]
- if stride is None:
- stride = size
- intervals[axis] = _axis_intervals(axis, dim, size, stride, tail)
- return _intervals_to_rois(rois, ref_image, intervals, base_name)
+ if anchor == "image":
+ intervals = _grid_intervals(ref_image, sizes, strides, tail)
+ return rois_product(rois, list(_grid_tiles(ref_image, intervals, base_name)))
+ if anchor != "roi":
+ raise NgioValueError(f"Grid anchor must be 'image' or 'roi', got {anchor!r}.")
+
+ names: set[str | None] = set()
+ tiles = []
+ for roi_index, roi in enumerate(rois, start=1):
+ roi_px = roi.to_pixel(pixel_size=ref_image.pixel_size)
+ intervals = _grid_intervals(ref_image, sizes, strides, tail, roi_px)
+ parent_slices = {s.axis_name: s for s in roi.slices}
+ for tile in _grid_tiles(ref_image, intervals, base_name):
+ name = _join_roi_names(roi.name, tile.name)
+ while name in names:
+ # Unnamed or identically named overlapping ROIs can share a tile origin.
+ name = f"{name}:roi{roi_index}"
+ names.add(name)
+ slices = parent_slices | {s.axis_name: s for s in tile.slices}
+ tiles.append(roi._updated(name=name, slices=tuple(slices.values())))
+ return tiles
def by_blocks(
@@ -269,7 +304,7 @@ def by_blocks(
)
for axis in _GRID_AXES
}
- return _intervals_to_rois(rois, ref_image, intervals, base_name)
+ return rois_product(rois, list(_grid_tiles(ref_image, intervals, base_name)))
def by_yx(rois: list[Roi], ref_image: AbstractImage) -> list[Roi]:
@@ -316,9 +351,8 @@ def by_storage_units(
in `ref_image`'s space. An axis present on `ref_image` but absent on
`grid_image` is left un-tiled (one tile spans it) — coarser, never unsafe.
- The tail policy is pinned to `"clip"`: shifting or balancing tiles would
- misalign them from the storage grid and defeat the point of storage
- tiling.
+ The tail policy and anchor are pinned to `"clip"` and `"image"` to
+ keep the tiles aligned to the storage grid.
"""
if grid_image is None:
chunk_size = ref_image.chunks
@@ -351,4 +385,5 @@ def by_storage_units(
stride_z=stride_z,
stride_t=stride_t,
tail="clip",
+ anchor="image",
)
diff --git a/tests/unit/iterators/test_by_grid.py b/tests/unit/iterators/test_by_grid.py
index 110928d3..2bd0cba0 100644
--- a/tests/unit/iterators/test_by_grid.py
+++ b/tests/unit/iterators/test_by_grid.py
@@ -5,16 +5,17 @@
from zarr.storage import MemoryStore
from ngio import create_ome_zarr_from_array
+from ngio.common import Roi
from ngio.iterators import SegmentationIterator
from ngio.iterators._rois_utils import _axis_intervals, _axis_partition
from ngio.utils import NgioValueError
-def _iterator(shape=(100, 100), chunks="auto"):
+def _iterator(shape=(100, 100), chunks="auto", pixelsize=1.0):
ome_zarr = create_ome_zarr_from_array(
store=MemoryStore(),
array=np.zeros(shape, dtype="uint8"),
- pixelsize=1.0,
+ pixelsize=pixelsize,
axes_names="yx",
levels=1,
chunks=chunks,
@@ -33,8 +34,10 @@ def _x_intervals(iterator):
def test_tail_clip_is_the_default():
- tiles = _iterator().by_grid(size_x=32)
+ iterator = _iterator()
+ tiles = iterator.by_grid(size_x=32)
assert _x_intervals(tiles) == [(0, 32), (32, 32), (64, 32), (96, 4)]
+ assert tiles.rois == iterator.by_grid(size_x=32, anchor="roi").rois
def test_tail_balance_resplits_the_last_two():
@@ -48,9 +51,10 @@ def test_tail_balance_with_odd_remainder():
assert _x_intervals(tiles) == [(0, 32), (32, 17), (49, 16)]
-def test_tail_balance_needs_adjacent_tiles():
+@pytest.mark.parametrize("anchor", ["image", "roi"])
+def test_tail_balance_needs_adjacent_tiles(anchor):
with pytest.raises(NgioValueError, match="balance"):
- _iterator().by_grid(size_x=32, stride_x=24, tail="balance")
+ _iterator().by_grid(size_x=32, stride_x=24, tail="balance", anchor=anchor)
def test_tail_shift_keeps_full_tiles():
@@ -82,6 +86,76 @@ def test_tail_drop_discards_the_partial_tile():
assert _x_intervals(tiles) == [(0, 32), (32, 32), (64, 32)]
+def test_roi_anchor_shifts_full_tiles_within_each_field():
+ regions = [
+ Roi.from_values(name=f"fov_{y}_{x}", slices={"y": (y, 500), "x": (x, 500)})
+ for y in (0, 500)
+ for x in (0, 500)
+ ]
+ iterator = _iterator(shape=(1000, 1000)).product(regions)
+ grid = {"size_x": 100, "size_y": 100, "stride_x": 90, "stride_y": 90}
+
+ image_tiles = iterator.by_grid(**grid)
+ assert image_tiles.rois == iterator.by_grid(**grid, anchor="image").rois
+ assert len(image_tiles.rois) == 169
+
+ tiles = iterator.by_grid(**grid, anchor="roi", tail="shift")
+ assert len(tiles.rois) == 144
+ for region in regions:
+ prefix = f"{region.name}:"
+ field_tiles = [roi for roi in tiles.rois if roi.get_name().startswith(prefix)]
+ assert len(field_tiles) == 36
+ for axis in ("y", "x"):
+ assert {(roi[axis].start, roi[axis].length) for roi in field_tiles} == {
+ (region[axis].start + start, 100)
+ for start in (0, 90, 180, 270, 360, 400)
+ }
+
+
+@pytest.mark.parametrize(
+ ("tail", "expected"),
+ [
+ ("clip", [(27, 32), (59, 32), (91, 1)]),
+ ("balance", [(27, 32), (59, 17), (76, 16)]),
+ ("shift", [(27, 32), (59, 32), (60, 32)]),
+ ("drop", [(27, 32), (59, 32)]),
+ ],
+)
+def test_roi_anchor_applies_tail_at_region_edge(tail, expected):
+ # The parent has no upper y bound, and its physical x bounds map to [27, 92).
+ region = Roi.from_values(name=None, slices={"y": (10.0, None), "x": (13.6, 32.2)})
+ iterator = _iterator(pixelsize=0.5).product([region])
+ tiles = iterator.by_grid(size_x=32, anchor="roi", tail=tail)
+ assert _x_intervals(tiles) == expected
+ assert {(roi["y"].start, roi["y"].length) for roi in tiles.rois} == {(10.0, 40.0)}
+
+
+@pytest.mark.parametrize("names", [("a", "b"), (None, None)])
+def test_roi_anchor_keeps_names_unique_for_overlapping_regions(names):
+ regions = [
+ Roi.from_values(name=name, slices={"y": (16, extent), "x": (16, extent)})
+ for name, extent in zip(names, (48, 64), strict=True)
+ ]
+ tiles = (
+ _iterator()
+ .product(regions)
+ .by_grid(size_y=32, size_x=32, anchor="roi", base_name="patch")
+ )
+ assert len({roi.name for roi in tiles.rois}) == len(tiles.rois) == 8
+ if names[0] is not None:
+ assert tiles.rois[0].name == "a:patch_t0_z0_y16_x16"
+ assert tiles.rois[4].name == "b:patch_t0_z0_y16_x16"
+
+
+@pytest.mark.parametrize("method", ["by_chunks", "by_write_units"])
+def test_storage_grid_stays_image_anchored_after_product(method):
+ region = Roi.from_values(name=None, slices={"y": (9, 47), "x": (11, 45)})
+ iterator = _iterator(shape=(64, 64), chunks=(32, 32)).product([region])
+ tiles = getattr(iterator, method)()
+ assert _x_intervals(tiles) == [(11, 21), (32, 24)]
+ assert not tiles.check_if_write_units_overlap()
+
+
def test_by_blocks_partitions_near_equally():
tiles = _iterator().by_blocks(num_x=3)
assert _x_intervals(tiles) == [(0, 34), (34, 33), (67, 33)]
diff --git a/tests/unit/iterators/test_masked_stitch.py b/tests/unit/iterators/test_masked_stitch.py
index 10b67a87..2a9e4547 100644
--- a/tests/unit/iterators/test_masked_stitch.py
+++ b/tests/unit/iterators/test_masked_stitch.py
@@ -88,13 +88,13 @@ def _masked_setup(store, *, touching=False, levels=1):
return ome_zarr, mask
-def _stitched_masked_iterator(ome_zarr, *, stitch=True, halo=6):
+def _stitched_masked_iterator(ome_zarr, *, stitch=True, halo=6, anchor="image"):
iterator = MaskedSegmentationIterator(
ome_zarr.get_masked_image(masking_label_name="organoids"),
ome_zarr.get_label("nuclei"),
axes_order="yx",
consolidation_mode="dask",
- ).by_grid(size_y=32, size_x=32)
+ ).by_grid(size_y=32, size_x=32, anchor=anchor)
if stitch:
iterator = iterator.with_stitch(None if stitch is True else stitch)
if halo:
@@ -145,10 +145,13 @@ def test_masked_stitch_never_merges_across_masks():
assert left != right, "objects of different masks were merged"
-def test_masked_garbage_extension_does_not_bridge_masks():
+@pytest.mark.parametrize("anchor", ["image", "roi"])
+def test_masked_garbage_extension_does_not_bridge_masks(anchor):
"""A func that labels the fill region must not union across masks."""
ome_zarr, mask = _masked_setup(MemoryStore(), touching=True)
- _stitched_masked_iterator(ome_zarr).map(_label_everything)
+ iterator = _stitched_masked_iterator(ome_zarr, anchor=anchor)
+ assert {roi.label for roi in iterator.rois} == {1, 2}
+ iterator.map(_label_everything)
written = ome_zarr.get_label("nuclei").get_as_numpy()
# One merged id per organoid, and the masks keep their pixels apart.