feat(detection): support windowed GeoTIFF reads in InferenceSlicer (#2281)
InferenceSlicer can now accept an open rasterio-style dataset and read each tile via a windowed read instead of loading the whole image into memory, enabling tiled inference on multi-GB aerial/drone GeoTIFFs. Detection is duck-typed so rasterio stays an optional dependency (supervision[geotiff]) and the library imports no rasterio symbols. Adds CRS projected validation and tests. Closes #2027. - Add threading.Lock around raster.read() in _run_callback to prevent data race when thread_workers > 1 shares a DatasetReader (GDAL releases GIL inside GDALRasterIO — reads are genuinely concurrent C code) - Return TypeGuard[WindowedRasterDataset] from _is_windowed_raster; TYPE_CHECKING guard imports typing_extensions for Python 3.9 compat - Add @runtime_checkable to WindowedRasterDataset Protocol; crs typed as object|None; guard .is_projected via getattr(..., True) - Extract _get_resolution_wh and _apply_overlap_filter helpers from __call__ to bring cyclomatic complexity under PLR0912 limit (16 → ~4) - Widen callback type to Callable[[NDArray[Any]], Detections] to accept any dtype (uint16 raster tiles are not NDArray[uint8]) - Add Raises section to __call__ docstring for geographic CRS ValueError - Add one-line summary to move_detections docstring - Export WindowedRasterDataset from sv.__init__ - Move changelog entry from 0.29.1 (released) to UnReleased - Add comment explaining rasterio>=1.3 lower bound in pyproject.toml - Restructure tests: class grouping, parametrize CRS cases, add docstrings; add compact_masks, thread_workers>1, single-band, single-tile test cases --------- Co-authored-by: madhavcodez <madhavcodez@users.noreply.github.com> Co-authored-by: Jirka Borovec <6035284+Borda@users.noreply.github.com> Co-authored-by: claude[bot] <209825114+claude[bot]@users.noreply.github.com> Co-authored-by: Codex <codex@openai.com> Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
This commit is contained in:
co-authored by
madhavcodez
Jirka Borovec
claude[bot]
Codex
pre-commit-ci[bot]
parent
14f6f245c8
commit
a179d9120f
@@ -9,6 +9,8 @@ date_modified: 2026-06-16
|
||||
|
||||
- Added [#2275](https://github.com/roboflow/supervision/pull/2275): `show_progress: bool = False` parameter to all `sv.DetectionDataset` load and save methods — `from_coco`, `from_yolo`, `from_pascal_voc`, `as_coco`, `as_yolo`, `as_pascal_voc`, and `save_dataset_images`. When `True`, a `tqdm.auto` progress bar is shown (works in terminal and Jupyter). Defaults to `False` for full backward compatibility; no new dependencies.
|
||||
|
||||
- Added [#2027](https://github.com/roboflow/supervision/issues/2027): [`sv.InferenceSlicer`](https://supervision.roboflow.com/latest/detection/tools/inference_slicer/#supervision.detection.tools.inference_slicer.InferenceSlicer) now accepts an open rasterio-style dataset in addition to in-memory images. Each tile is read lazily via a windowed read instead of loading the whole image, enabling tiled inference on multi-GB aerial/drone GeoTIFFs without running out of memory. Detection is duck-typed, so `rasterio` stays an optional dependency installable via `pip install "supervision[geotiff]"` and the core library imports no rasterio symbols. A geographic (non-projected) CRS raises `ValueError`.
|
||||
|
||||
### 0.29.1 <small>Jun 23, 2026</small>
|
||||
|
||||
- Added [#2338](https://github.com/roboflow/supervision/pull/2338): [`sv.KeyPoints.with_nms`](https://supervision.roboflow.com/latest/keypoint/core/#supervision.key_points.core.KeyPoints.with_nms) — non-maximum suppression for keypoint detections. Derives axis-aligned bounding boxes from valid (non-zero and visible) keypoints and applies `box_non_max_suppression`. Requires `detection_confidence`; supports class-aware and class-agnostic modes via `threshold`, `class_agnostic`, and `overlap_metric`.
|
||||
|
||||
@@ -4,4 +4,45 @@ comments: true
|
||||
|
||||
# InferenceSlicer
|
||||
|
||||
## GeoTIFF Datasets
|
||||
|
||||
Install the optional GeoTIFF dependencies before running this example:
|
||||
|
||||
```bash
|
||||
pip install "supervision[geotiff]"
|
||||
wget -O RGB.byte.tif https://raw.githubusercontent.com/rasterio/rasterio/main/tests/data/RGB.byte.tif
|
||||
```
|
||||
|
||||
`InferenceSlicer` can read an open `rasterio` dataset window-by-window. This keeps large GeoTIFFs out of memory while passing each tile to the callback as an `(H, W, C)` NumPy array.
|
||||
|
||||
```python
|
||||
import numpy as np
|
||||
import rasterio
|
||||
import supervision as sv
|
||||
|
||||
|
||||
def callback(tile: np.ndarray) -> sv.Detections:
|
||||
h, w = tile.shape[:2]
|
||||
return sv.Detections(
|
||||
xyxy=np.array([[w * 0.25, h * 0.25, w * 0.75, h * 0.75]], dtype=float),
|
||||
confidence=np.array([0.9]),
|
||||
class_id=np.array([0]),
|
||||
)
|
||||
|
||||
|
||||
slicer = sv.InferenceSlicer(
|
||||
callback=callback,
|
||||
slice_wh=(256, 256),
|
||||
overlap_wh=(64, 64),
|
||||
overlap_filter=sv.OverlapFilter.NONE,
|
||||
)
|
||||
|
||||
with rasterio.open("RGB.byte.tif") as dataset:
|
||||
detections = slicer(dataset)
|
||||
|
||||
print(len(detections))
|
||||
```
|
||||
|
||||
GeoTIFF inputs must use a projected coordinate reference system. Reproject geographic rasters before passing them to `InferenceSlicer`.
|
||||
|
||||
:::supervision.detection.tools.inference_slicer.InferenceSlicer
|
||||
|
||||
@@ -59,6 +59,9 @@ dependencies = [
|
||||
"scipy>=1.10",
|
||||
"tqdm>=4.62.3"
|
||||
]
|
||||
optional-dependencies.geotiff = [
|
||||
"rasterio>=1.3", # 1.3 introduced stable window-read API and CRS.is_projected
|
||||
]
|
||||
optional-dependencies.metrics = [
|
||||
"pandas>=2",
|
||||
]
|
||||
|
||||
@@ -52,7 +52,10 @@ from supervision.detection.line_zone import (
|
||||
LineZoneAnnotatorMulticlass,
|
||||
)
|
||||
from supervision.detection.tools.csv_sink import CSVSink
|
||||
from supervision.detection.tools.inference_slicer import InferenceSlicer
|
||||
from supervision.detection.tools.inference_slicer import (
|
||||
InferenceSlicer,
|
||||
WindowedRasterDataset,
|
||||
)
|
||||
from supervision.detection.tools.json_sink import JSONSink
|
||||
from supervision.detection.tools.polygon_zone import PolygonZone, PolygonZoneAnnotator
|
||||
from supervision.detection.tools.smoother import DetectionsSmoother
|
||||
@@ -218,6 +221,7 @@ __all__ = [
|
||||
"VertexLabelAnnotator",
|
||||
"VideoInfo",
|
||||
"VideoSink",
|
||||
"WindowedRasterDataset",
|
||||
"approximate_polygon",
|
||||
"box_iou",
|
||||
"box_iou_batch",
|
||||
|
||||
@@ -4,7 +4,10 @@ import threading
|
||||
import warnings
|
||||
from collections.abc import Callable
|
||||
from concurrent.futures import ThreadPoolExecutor, as_completed
|
||||
from typing import Any
|
||||
from typing import TYPE_CHECKING, Any, Protocol, runtime_checkable
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from typing_extensions import TypeGuard
|
||||
|
||||
import numpy as np
|
||||
import numpy.typing as npt
|
||||
@@ -20,12 +23,43 @@ from supervision.utils.image import crop_image, get_image_resolution_wh
|
||||
from supervision.utils.internal import SupervisionWarnings
|
||||
|
||||
|
||||
@runtime_checkable
|
||||
class WindowedRasterDataset(Protocol):
|
||||
"""Structural type for a rasterio-style dataset read window-by-window.
|
||||
|
||||
Matched structurally by `_is_windowed_raster` rather than by import so
|
||||
`rasterio` stays an optional dependency — any object exposing these members
|
||||
works. `rasterio.io.DatasetReader` satisfies this protocol.
|
||||
"""
|
||||
|
||||
width: int
|
||||
height: int
|
||||
crs: object | None
|
||||
|
||||
def read(self, window: Any) -> npt.NDArray[Any]: ...
|
||||
|
||||
|
||||
def _is_windowed_raster(image: object) -> TypeGuard[WindowedRasterDataset]:
|
||||
"""Duck-type check for a rasterio-style dataset that supports windowed reads.
|
||||
|
||||
Avoids importing rasterio so it remains an optional dependency. numpy arrays
|
||||
and PIL images do not expose this combination of attributes.
|
||||
"""
|
||||
return (
|
||||
callable(getattr(image, "read", None))
|
||||
and hasattr(image, "crs")
|
||||
and hasattr(image, "width")
|
||||
and hasattr(image, "height")
|
||||
)
|
||||
|
||||
|
||||
def move_detections(
|
||||
detections: Detections,
|
||||
offset: npt.NDArray[Any],
|
||||
resolution_wh: tuple[int, int] | None = None,
|
||||
) -> Detections:
|
||||
"""
|
||||
"""Translate detections by a pixel offset, repositioning boxes and masks.
|
||||
|
||||
Args:
|
||||
detections: Detections object to be moved.
|
||||
offset: An array of shape `(2,)` containing offset values in the
|
||||
@@ -88,7 +122,10 @@ class InferenceSlicer:
|
||||
bounding boxes (OBB), Supervision probes additional slices until a
|
||||
non-empty result is found, then falls back to sequential processing
|
||||
for all remaining slices to avoid thread-safety issues in common OBB
|
||||
inference backends. Note: the first slice always runs synchronously
|
||||
inference backends. When passing a rasterio-style dataset, tile reads
|
||||
are serialized via an internal lock regardless of this setting —
|
||||
model inference runs in parallel, but ``raster.read()`` is protected.
|
||||
Note: the first slice always runs synchronously
|
||||
regardless of this setting, so for grids with few slices
|
||||
(e.g. two-slice images) effective parallelism is reduced.
|
||||
compact_masks: If ``True``, dense ``(N, H, W)`` boolean mask
|
||||
@@ -138,6 +175,24 @@ class InferenceSlicer:
|
||||
image = Image.open("example.png")
|
||||
detections = slicer(image)
|
||||
```
|
||||
|
||||
```python
|
||||
import rasterio
|
||||
import supervision as sv
|
||||
|
||||
def callback(tile): # tile is (H, W, C); select/convert bands as needed
|
||||
...
|
||||
|
||||
slicer = sv.InferenceSlicer(callback, slice_wh=640, overlap_wh=100)
|
||||
|
||||
with rasterio.open("large_orthomosaic.tif") as dataset:
|
||||
detections = slicer(dataset)
|
||||
```
|
||||
|
||||
Passing an open rasterio dataset reads each tile lazily via a windowed
|
||||
read, so multi-GB GeoTIFFs never need to be loaded into memory at once.
|
||||
`rasterio` is an optional dependency installable via
|
||||
`pip install "supervision[geotiff]"`.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
@@ -167,15 +222,16 @@ class InferenceSlicer:
|
||||
self.iou_threshold = iou_threshold
|
||||
self.overlap_metric = OverlapMetric.from_value(overlap_metric)
|
||||
self.overlap_filter = OverlapFilter.from_value(overlap_filter)
|
||||
self.callback: Callable[[ImageType], Detections] = callback
|
||||
self.callback: Callable[[npt.NDArray[Any]], Detections] = callback
|
||||
self.thread_workers = thread_workers
|
||||
self.compact_masks = compact_masks
|
||||
self._out_of_slice_bounds_warned: bool = False
|
||||
self._out_of_slice_bounds_lock = threading.Lock()
|
||||
self._obb_thread_workers_warned: bool = False
|
||||
self._obb_thread_workers_lock = threading.Lock()
|
||||
self._raster_read_lock = threading.Lock()
|
||||
|
||||
def __call__(self, image: ImageType) -> Detections:
|
||||
def __call__(self, image: ImageType | WindowedRasterDataset) -> Detections:
|
||||
"""
|
||||
Perform tiled inference on the full image and return merged detections.
|
||||
|
||||
@@ -188,13 +244,25 @@ class InferenceSlicer:
|
||||
once per slicer instance.
|
||||
|
||||
Args:
|
||||
image: The full image to run inference on.
|
||||
image: The full image to run inference on. In addition to in-memory
|
||||
images (NumPy arrays or PIL images), this also accepts an open
|
||||
rasterio-style dataset. When a dataset is provided, each tile is
|
||||
read lazily via a windowed read instead of loading the whole image
|
||||
into memory, enabling tiled inference on multi-GB GeoTIFFs. Tiles
|
||||
read from a dataset preserve the source dtype (e.g. ``uint16`` for
|
||||
16-bit sensors) and keep every band; convert or select bands to
|
||||
the dtype/channels your model expects inside the callback.
|
||||
|
||||
Returns:
|
||||
Merged detections across all slices.
|
||||
|
||||
Raises:
|
||||
ValueError: If ``image`` is a rasterio-style dataset whose CRS is
|
||||
geographic (non-projected). Reproject to a projected CRS
|
||||
(e.g. with ``gdalwarp``) before calling.
|
||||
"""
|
||||
detections_list: list[Detections] = []
|
||||
resolution_wh = get_image_resolution_wh(image)
|
||||
resolution_wh = self._get_resolution_wh(image)
|
||||
|
||||
offsets = self._generate_offset(
|
||||
resolution_wh=resolution_wh,
|
||||
@@ -253,6 +321,26 @@ class InferenceSlicer:
|
||||
detections_list.append(future.result())
|
||||
|
||||
merged = Detections.merge(detections_list=detections_list)
|
||||
return self._apply_overlap_filter(merged)
|
||||
|
||||
def _get_resolution_wh(
|
||||
self, image: ImageType | WindowedRasterDataset
|
||||
) -> tuple[int, int]:
|
||||
"""Return ``(width, height)`` for the image, validating CRS for rasters."""
|
||||
if _is_windowed_raster(image):
|
||||
crs = image.crs
|
||||
if crs is not None and not getattr(crs, "is_projected", True):
|
||||
raise ValueError(
|
||||
"InferenceSlicer requires a projected coordinate reference "
|
||||
"system for pixel-space tiled inference on a raster dataset. "
|
||||
f"The provided dataset uses a geographic CRS ({crs}). Reproject "
|
||||
"it to a projected CRS (e.g. with `gdalwarp`) before slicing."
|
||||
)
|
||||
return (image.width, image.height)
|
||||
return get_image_resolution_wh(image)
|
||||
|
||||
def _apply_overlap_filter(self, merged: Detections) -> Detections:
|
||||
"""Apply the configured overlap filter strategy to merged detections."""
|
||||
if self.overlap_filter == OverlapFilter.NONE:
|
||||
return merged
|
||||
if self.overlap_filter == OverlapFilter.NON_MAX_SUPPRESSION:
|
||||
@@ -265,14 +353,15 @@ class InferenceSlicer:
|
||||
threshold=self.iou_threshold,
|
||||
overlap_metric=self.overlap_metric,
|
||||
)
|
||||
|
||||
warnings.warn(
|
||||
f"Invalid overlap filter strategy: {self.overlap_filter}",
|
||||
category=SupervisionWarnings,
|
||||
)
|
||||
return merged
|
||||
|
||||
def _run_callback(self, image: ImageType, offset: npt.NDArray[Any]) -> Detections:
|
||||
def _run_callback(
|
||||
self, image: ImageType | WindowedRasterDataset, offset: npt.NDArray[Any]
|
||||
) -> Detections:
|
||||
"""
|
||||
Run detection callback on a sliced portion of the image and adjust coordinates.
|
||||
|
||||
@@ -284,7 +373,20 @@ class InferenceSlicer:
|
||||
Returns:
|
||||
Detections adjusted to the full image coordinate system.
|
||||
"""
|
||||
image_slice = crop_image(image=image, xyxy=offset)
|
||||
if _is_windowed_raster(image):
|
||||
x_min, y_min, x_max, y_max = (int(v) for v in offset)
|
||||
# rasterio tuple window: ((row_start, row_stop), (col_start, col_stop))
|
||||
window = ((y_min, y_max), (x_min, x_max))
|
||||
with self._raster_read_lock:
|
||||
bands = image.read(window=window) # shape (channels, height, width)
|
||||
image_slice = np.ascontiguousarray(
|
||||
np.transpose(bands, (1, 2, 0))
|
||||
) # -> (H, W, C)
|
||||
resolution_wh = (image.width, image.height)
|
||||
else:
|
||||
image_slice = crop_image(image=image, xyxy=offset)
|
||||
resolution_wh = get_image_resolution_wh(image)
|
||||
|
||||
detections = self.callback(image_slice)
|
||||
|
||||
if (
|
||||
@@ -299,7 +401,6 @@ class InferenceSlicer:
|
||||
image_shape=(slice_h, slice_w),
|
||||
)
|
||||
|
||||
resolution_wh = get_image_resolution_wh(image)
|
||||
# Fast-path: skip locking and bounds checking when the warning has already
|
||||
# been emitted or when there are no detections to inspect.
|
||||
needs_warning_check = (
|
||||
|
||||
@@ -0,0 +1,348 @@
|
||||
"""Tests for windowed GeoTIFF reads in InferenceSlicer."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import threading
|
||||
import time
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
|
||||
from supervision.detection.core import Detections
|
||||
from supervision.detection.tools.inference_slicer import InferenceSlicer
|
||||
|
||||
|
||||
class _FakeCRS:
|
||||
"""Minimal rasterio-style CRS stub exposing only `is_projected`."""
|
||||
|
||||
def __init__(self, is_projected: bool):
|
||||
self.is_projected = is_projected
|
||||
|
||||
def __repr__(self) -> str:
|
||||
kind = "projected" if self.is_projected else "geographic"
|
||||
return f"_FakeCRS({kind})"
|
||||
|
||||
|
||||
class _FakeRasterDataset:
|
||||
"""Lightweight rasterio-style dataset supporting windowed reads.
|
||||
|
||||
Mimics the duck-typed interface that ``InferenceSlicer`` relies on without
|
||||
requiring ``rasterio`` to be installed.
|
||||
"""
|
||||
|
||||
def __init__(self, image_hwc: np.ndarray, crs: object | None = None):
|
||||
self._image = image_hwc # numpy (H, W, C)
|
||||
self.height, self.width = image_hwc.shape[:2]
|
||||
self.crs = crs # None or object with .is_projected
|
||||
|
||||
def read(self, window: tuple[tuple[int, int], tuple[int, int]]) -> np.ndarray:
|
||||
(row_start, row_stop), (col_start, col_stop) = window
|
||||
crop = self._image[row_start:row_stop, col_start:col_stop, :]
|
||||
return np.transpose(crop, (2, 0, 1)) # (C, H, W) like rasterio
|
||||
|
||||
|
||||
class _ConcurrencyCheckDataset:
|
||||
"""Dataset that tracks peak concurrent reads to verify read serialization."""
|
||||
|
||||
def __init__(self, image_hwc: np.ndarray):
|
||||
self._image = image_hwc
|
||||
self.height, self.width = image_hwc.shape[:2]
|
||||
self.crs = None
|
||||
self._lock = threading.Lock()
|
||||
self._active = 0
|
||||
self.peak_concurrent = 0
|
||||
|
||||
def read(self, window: tuple[tuple[int, int], tuple[int, int]]) -> np.ndarray:
|
||||
with self._lock:
|
||||
self._active += 1
|
||||
self.peak_concurrent = max(self.peak_concurrent, self._active)
|
||||
time.sleep(0.002) # amplify race window so concurrent reads are detectable
|
||||
(row_start, row_stop), (col_start, col_stop) = window
|
||||
crop = self._image[row_start:row_stop, col_start:col_stop, :]
|
||||
result = np.transpose(crop, (2, 0, 1))
|
||||
with self._lock:
|
||||
self._active -= 1
|
||||
return result
|
||||
|
||||
|
||||
def _fixed_detection_callback(_: np.ndarray) -> Detections:
|
||||
"""Return a constant detection for every tile."""
|
||||
return Detections(
|
||||
xyxy=np.array([[0, 0, 10, 10]], dtype=float),
|
||||
confidence=np.array([0.9]),
|
||||
class_id=np.array([0]),
|
||||
)
|
||||
|
||||
|
||||
def _sortable(detections: Detections) -> np.ndarray:
|
||||
"""Sort detection boxes so two runs can be compared order-independently."""
|
||||
return np.array(
|
||||
sorted(detections.xyxy.tolist()),
|
||||
dtype=float,
|
||||
)
|
||||
|
||||
|
||||
class TestInferenceSlicerGeoTIFF:
|
||||
def test_windowed_raster_matches_in_memory_array(self) -> None:
|
||||
"""Raster and array paths produce identical merged detections."""
|
||||
# Arrange
|
||||
rng = np.random.default_rng(42)
|
||||
image = rng.integers(0, 255, size=(256, 256, 3), dtype=np.uint8)
|
||||
dataset = _FakeRasterDataset(image, crs=_FakeCRS(is_projected=True))
|
||||
slicer = InferenceSlicer(
|
||||
callback=_fixed_detection_callback,
|
||||
slice_wh=128,
|
||||
overlap_wh=0,
|
||||
)
|
||||
|
||||
# Act
|
||||
detections_array = slicer(image)
|
||||
detections_raster = slicer(dataset)
|
||||
|
||||
# Assert
|
||||
assert np.array_equal(_sortable(detections_array), _sortable(detections_raster))
|
||||
|
||||
def test_windowed_raster_reads_correct_window_content(self) -> None:
|
||||
"""The windowed read returns the same pixels crop_image would for each tile."""
|
||||
# Arrange
|
||||
rng = np.random.default_rng(7)
|
||||
image = rng.integers(0, 255, size=(128, 192, 3), dtype=np.uint8)
|
||||
dataset = _FakeRasterDataset(image)
|
||||
|
||||
seen_array_tiles: list[np.ndarray] = []
|
||||
seen_raster_tiles: list[np.ndarray] = []
|
||||
|
||||
def recording_callback(sink: list[np.ndarray]):
|
||||
def callback(tile: np.ndarray) -> Detections:
|
||||
sink.append(tile.copy())
|
||||
return Detections.empty()
|
||||
|
||||
return callback
|
||||
|
||||
slicer_array = InferenceSlicer(
|
||||
callback=recording_callback(seen_array_tiles),
|
||||
slice_wh=64,
|
||||
overlap_wh=0,
|
||||
)
|
||||
slicer_raster = InferenceSlicer(
|
||||
callback=recording_callback(seen_raster_tiles),
|
||||
slice_wh=64,
|
||||
overlap_wh=0,
|
||||
)
|
||||
|
||||
# Act
|
||||
slicer_array(image)
|
||||
slicer_raster(dataset)
|
||||
|
||||
# Assert
|
||||
assert len(seen_array_tiles) == len(seen_raster_tiles)
|
||||
for array_tile, raster_tile in zip(seen_array_tiles, seen_raster_tiles):
|
||||
assert np.array_equal(array_tile, raster_tile)
|
||||
|
||||
def test_windowed_raster_matches_in_memory_array_with_overlap(self) -> None:
|
||||
"""Overlapping tiles read identical windows for both array and raster inputs."""
|
||||
# Arrange
|
||||
rng = np.random.default_rng(99)
|
||||
image = rng.integers(0, 255, size=(200, 220, 3), dtype=np.uint8)
|
||||
dataset = _FakeRasterDataset(image)
|
||||
|
||||
seen_array_tiles: list[np.ndarray] = []
|
||||
seen_raster_tiles: list[np.ndarray] = []
|
||||
|
||||
def recording_callback(sink: list[np.ndarray]):
|
||||
def callback(tile: np.ndarray) -> Detections:
|
||||
sink.append(tile.copy())
|
||||
return Detections.empty()
|
||||
|
||||
return callback
|
||||
|
||||
slicer_array = InferenceSlicer(
|
||||
callback=recording_callback(seen_array_tiles),
|
||||
slice_wh=96,
|
||||
overlap_wh=32,
|
||||
)
|
||||
slicer_raster = InferenceSlicer(
|
||||
callback=recording_callback(seen_raster_tiles),
|
||||
slice_wh=96,
|
||||
overlap_wh=32,
|
||||
)
|
||||
|
||||
# Act
|
||||
slicer_array(image)
|
||||
slicer_raster(dataset)
|
||||
|
||||
# Assert
|
||||
assert len(seen_array_tiles) == len(seen_raster_tiles) > 1
|
||||
for array_tile, raster_tile in zip(seen_array_tiles, seen_raster_tiles):
|
||||
assert np.array_equal(array_tile, raster_tile)
|
||||
|
||||
def test_windowed_raster_preserves_band_dtype(self) -> None:
|
||||
"""Tiles read from a dataset keep the source dtype (e.g. uint16)."""
|
||||
# Arrange
|
||||
rng = np.random.default_rng(5)
|
||||
image = rng.integers(0, 4000, size=(128, 128, 3), dtype=np.uint16)
|
||||
dataset = _FakeRasterDataset(image)
|
||||
|
||||
seen: list[np.ndarray] = []
|
||||
|
||||
def callback(tile: np.ndarray) -> Detections:
|
||||
seen.append(tile)
|
||||
return Detections.empty()
|
||||
|
||||
slicer = InferenceSlicer(callback=callback, slice_wh=64, overlap_wh=0)
|
||||
|
||||
# Act
|
||||
slicer(dataset)
|
||||
|
||||
# Assert
|
||||
assert seen
|
||||
assert all(tile.dtype == np.uint16 for tile in seen)
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"crs",
|
||||
[
|
||||
pytest.param(None, id="no-crs"),
|
||||
pytest.param(_FakeCRS(is_projected=True), id="projected-crs"),
|
||||
],
|
||||
)
|
||||
def test_crs_allows_slicing(self, crs: object | None) -> None:
|
||||
"""None CRS and projected CRS both allow slicing without error."""
|
||||
image = np.zeros((128, 128, 3), dtype=np.uint8)
|
||||
dataset = _FakeRasterDataset(image, crs=crs)
|
||||
slicer = InferenceSlicer(
|
||||
callback=_fixed_detection_callback,
|
||||
slice_wh=64,
|
||||
overlap_wh=0,
|
||||
)
|
||||
|
||||
detections = slicer(dataset)
|
||||
|
||||
assert len(detections) == 4
|
||||
|
||||
def test_geographic_crs_raises(self) -> None:
|
||||
"""Dataset with a geographic (non-projected) CRS raises ValueError."""
|
||||
image = np.zeros((128, 128, 3), dtype=np.uint8)
|
||||
dataset = _FakeRasterDataset(image, crs=_FakeCRS(is_projected=False))
|
||||
slicer = InferenceSlicer(
|
||||
callback=_fixed_detection_callback,
|
||||
slice_wh=64,
|
||||
overlap_wh=0,
|
||||
)
|
||||
|
||||
with pytest.raises(ValueError, match="projected coordinate reference"):
|
||||
slicer(dataset)
|
||||
|
||||
def test_single_band_raster_produces_hwc1_tiles(self) -> None:
|
||||
"""Single-band raster tiles arrive at the callback as (H, W, 1) arrays."""
|
||||
image = np.zeros((128, 128, 1), dtype=np.uint8)
|
||||
dataset = _FakeRasterDataset(image)
|
||||
|
||||
seen: list[np.ndarray] = []
|
||||
|
||||
def callback(tile: np.ndarray) -> Detections:
|
||||
seen.append(tile)
|
||||
return Detections.empty()
|
||||
|
||||
slicer = InferenceSlicer(callback=callback, slice_wh=64, overlap_wh=0)
|
||||
|
||||
slicer(dataset)
|
||||
|
||||
assert seen
|
||||
assert all(tile.ndim == 3 and tile.shape[2] == 1 for tile in seen)
|
||||
|
||||
def test_raster_smaller_than_slice_produces_single_tile(self) -> None:
|
||||
"""Raster smaller than slice_wh is processed as exactly one tile."""
|
||||
image = np.zeros((48, 64, 3), dtype=np.uint8)
|
||||
dataset = _FakeRasterDataset(image)
|
||||
|
||||
tile_count: list[int] = [0]
|
||||
|
||||
def callback(tile: np.ndarray) -> Detections:
|
||||
tile_count[0] += 1
|
||||
return Detections.empty()
|
||||
|
||||
slicer = InferenceSlicer(callback=callback, slice_wh=128, overlap_wh=0)
|
||||
|
||||
slicer(dataset)
|
||||
|
||||
assert tile_count[0] == 1
|
||||
|
||||
def test_compact_masks_with_windowed_raster(self) -> None:
|
||||
"""compact_masks=True correctly moves and compresses masks from raster tiles."""
|
||||
rng = np.random.default_rng(17)
|
||||
image = rng.integers(0, 255, size=(128, 128, 3), dtype=np.uint8)
|
||||
dataset = _FakeRasterDataset(image)
|
||||
|
||||
def masked_callback(tile: np.ndarray) -> Detections:
|
||||
h, w = tile.shape[:2]
|
||||
mask = np.zeros((1, h, w), dtype=bool)
|
||||
mask[0, : h // 2, : w // 2] = True
|
||||
return Detections(
|
||||
xyxy=np.array([[0, 0, w // 2, h // 2]], dtype=float),
|
||||
confidence=np.array([0.9]),
|
||||
class_id=np.array([0]),
|
||||
mask=mask,
|
||||
)
|
||||
|
||||
slicer = InferenceSlicer(
|
||||
callback=masked_callback,
|
||||
slice_wh=64,
|
||||
overlap_wh=0,
|
||||
compact_masks=True,
|
||||
)
|
||||
|
||||
detections = slicer(dataset)
|
||||
|
||||
assert len(detections) > 0
|
||||
|
||||
def test_thread_workers_with_raster_serializes_reads(self) -> None:
|
||||
"""Raster reads are serialized even when thread_workers > 1."""
|
||||
rng = np.random.default_rng(3)
|
||||
image = rng.integers(0, 255, size=(256, 256, 3), dtype=np.uint8)
|
||||
dataset = _ConcurrencyCheckDataset(image)
|
||||
|
||||
slicer = InferenceSlicer(
|
||||
callback=_fixed_detection_callback,
|
||||
slice_wh=64,
|
||||
overlap_wh=0,
|
||||
thread_workers=4,
|
||||
)
|
||||
|
||||
slicer(dataset)
|
||||
|
||||
assert dataset.peak_concurrent == 1
|
||||
|
||||
def test_real_rasterio_memoryfile_integration(self) -> None:
|
||||
"""Real rasterio MemoryFile produces same detections as the array path."""
|
||||
pytest.importorskip("rasterio")
|
||||
from rasterio.io import MemoryFile
|
||||
|
||||
# Arrange
|
||||
rng = np.random.default_rng(123)
|
||||
image = rng.integers(0, 255, size=(128, 128, 3), dtype=np.uint8)
|
||||
bands = np.transpose(image, (2, 0, 1)) # (C, H, W)
|
||||
|
||||
slicer = InferenceSlicer(
|
||||
callback=_fixed_detection_callback,
|
||||
slice_wh=64,
|
||||
overlap_wh=0,
|
||||
)
|
||||
detections_array = slicer(image)
|
||||
|
||||
profile = {
|
||||
"driver": "GTiff",
|
||||
"height": image.shape[0],
|
||||
"width": image.shape[1],
|
||||
"count": image.shape[2],
|
||||
"dtype": image.dtype,
|
||||
}
|
||||
|
||||
# Act
|
||||
with MemoryFile() as memfile:
|
||||
with memfile.open(**profile) as dst:
|
||||
dst.write(bands)
|
||||
with memfile.open() as dataset:
|
||||
detections_raster = slicer(dataset)
|
||||
|
||||
# Assert
|
||||
assert np.array_equal(_sortable(detections_array), _sortable(detections_raster))
|
||||
Reference in New Issue
Block a user