Skip to content
Edit this page

Images, slicing, utilities

Images

load_image

load_image(image: Any, device: device | str | None = None) -> torch.Tensor

Load a file path, PIL image, HWC NumPy array, or tensor as an RGB [3, H, W] tensor.

register_frame_buffer

register_frame_buffer(
    buffer: Any, device: device | str | None = None
) -> FrameBufferRegistration

Page-lock a contiguous writeable NumPy array or CPU tensor for faster CUDA uploads.

FrameBufferRegistration

FrameBufferRegistration(buffer: Any, tensor: Tensor | None, reason: str | None)

Handle for a host buffer page-locked by :func:register_frame_buffer.

unregister

unregister() -> None

Unlock the buffer (idempotent). Uploads from it take the plain copy afterwards.

Tile grid and slicing

calculate_slice_grid

calculate_slice_grid(
    image_width: int,
    image_height: int,
    slice_width: int = 512,
    slice_height: int = 512,
    overlap_width_ratio: float = 0.2,
    overlap_height_ratio: float = 0.2,
) -> list[SliceWindow]

Build row-major overlapping slice windows covering the canvas.

SliceWindow dataclass

SliceWindow(x1: int, y1: int, x2: int, y2: int)

A tile on the canvas, in pixel coordinates with exclusive x2/y2.

windows_to_tensor

windows_to_tensor(
    windows: list[SliceWindow], device: device | str | None = None
) -> torch.Tensor

Stack windows into an [N, 4] int64 tensor of (x1, y1, x2, y2).

yield_slice_batches

yield_slice_batches(
    image: Tensor,
    windows: Sequence[SliceWindow] | Tensor,
    slice_size: tuple[int, int],
    batch_size: int = 8,
    dtype: dtype | None = None,
    channels_last: bool = False,
) -> Iterator[SliceBatch]

Crop image into mini-batches of patches without leaving its device.

Only batch_size patches exist at a time, so peak memory stays bounded on 8K canvases.

Parameters:

Name Type Description Default
image Tensor

[C, H, W] or [1, C, H, W] tensor on any device.

required
windows Sequence[SliceWindow] | Tensor

Windows from :func:~easi.grid.calculate_slice_grid.

required
slice_size tuple[int, int]

(width, height) every patch is padded to.

required
batch_size int

Patches per yielded batch.

8
dtype dtype | None

Cast patches to this dtype; None keeps the image dtype.

None
channels_last bool

Return batches in torch.channels_last memory format.

False

SliceBatch

Bases: NamedTuple

images instance-attribute

images: Tensor

[B, C, slice_h, slice_w] patches; edge patches are zero-padded bottom/right.

windows instance-attribute

windows: Tensor

[B, 4] int64 canvas windows (x1, y1, x2, y2) of the patches.

start instance-attribute

start: int

Index of the first patch in the full window list (its tile id).

CanvasDetections

Bases: NamedTuple

boxes instance-attribute

boxes: Tensor

[M, 4] float32 xyxy in canvas pixels.

scores instance-attribute

scores: Tensor

[M] float32.

labels instance-attribute

labels: Tensor

[M] int64.

tile_ids instance-attribute

tile_ids: Tensor

[M] int64 index of the window each box came from.

truncation instance-attribute

truncation: Tensor

[M, 4] bool: box touches that (left, top, right, bottom) edge of its tile and the edge is interior to the canvas, i.e. the object may continue in a neighbouring tile.

to_canvas

to_canvas(
    predictions: Sequence[SlicePrediction],
    windows: Tensor,
    canvas_size: tuple[int, int],
    first_tile_id: int = 0,
    edge_tolerance: float = 2.0,
) -> CanvasDetections

Shift per-slice predictions to canvas coordinates and flag truncated boxes.

Boxes are clipped to their window, then shifted by the window origin. Boxes predicted entirely inside the zero padding become zero-area; :func:~easi.postprocess.fuse drops them, so this function adds no host sync.

Parameters:

Name Type Description Default
predictions Sequence[SlicePrediction]

One (boxes, scores, labels) tuple per window, in window order.

required
windows Tensor

[B, 4] windows matching predictions.

required
canvas_size tuple[int, int]

(width, height) of the full image.

required
first_tile_id int

Tile id of predictions[0], for batches after the first.

0
edge_tolerance float

Pixels within which a box counts as touching a tile edge.

2.0

concat_detections

concat_detections(parts: Sequence[CanvasDetections]) -> CanvasDetections

Concatenate detections from several batches.

Timing

StageTimer

StageTimer(device: device | str)

Accumulates time per named stage across one or more predict calls.

On CUDA, stages are bracketed with CUDA events. That adds no host syncs, so the measured run behaves like an untimed one; :meth:totals_ms syncs once at the end. Elsewhere, each stage synchronizes the device before and after and uses wall time, which serializes the pipeline slightly.

Example::

timer = StageTimer(image.device)
engine.predict(image, detector, timer=timer)
timer.totals_ms()  # {"slice": 1.2, "detect": 30.5, "shift": 0.4, "fuse": 2.1}

totals_ms

totals_ms() -> dict[str, float]

Milliseconds per stage, in first-seen order.

SAHI compatibility

get_sliced_prediction

get_sliced_prediction(
    image: Any,
    detection_model: Any,
    slice_height: int | None = None,
    slice_width: int | None = None,
    overlap_height_ratio: float = 0.2,
    overlap_width_ratio: float = 0.2,
    perform_standard_pred: bool = True,
    postprocess_type: str = "GREEDYNMM",
    postprocess_match_metric: str = "IOS",
    postprocess_match_threshold: float = 0.5,
    postprocess_class_agnostic: bool = False,
    verbose: int = 1,
    exclude_classes_by_name: list[str] | None = None,
    exclude_classes_by_id: list[int] | None = None,
    batch_size: int = 8,
    confidence_threshold: float | None = None,
    device: device | str | None = None,
    edge_cleanup: EdgeCleanup | bool = "balanced",
    **ignored: Any,
) -> Any

Sliced prediction with the sahi.predict.get_sliced_prediction signature.

Parameters:

Name Type Description Default
image Any

File path, PIL.Image, RGB HxWxC NumPy array, or [3, H, W] tensor.

required
detection_model Any

A :class:~easi.adapters.TorchDetector or a sahi UltralyticsDetectionModel.

required
device device | str | None

Where to run; defaults to the sahi model's device, else CUDA → MPS → CPU.

None
edge_cleanup EdgeCleanup | bool

Mode for removing cut fragment boxes at tile boundaries ("balanced", "aggressive", or "off").

'balanced'

Returns:

Type Description
Any

sahi.prediction.PredictionResult if sahi is installed, otherwise

Any

class:PredictionResult with the same object_prediction_list attributes.

Other arguments match sahi; see the module docstring for differences.