Skip to content

Tiled prediction

plakakia.predict

Tiled inference: run any detector on tiles and merge the boxes on the full image.

Small objects (insects, cells, cars in a satellite scene) vanish when a large image is resized to a detector's input size. :func:predict_tiled keeps the native resolution: it cuts the image into overlapping tiles, runs the model on batches of tiles, moves every box back to image coordinates and merges the duplicates, all in one call.

The model is any callable. It receives a batch of tiles, stacked along a new first axis, of the same array type as the image, and returns one (boxes, scores, class_ids) triple per tile, with boxes (x1, y1, x2, y2) in tile pixels. NumPy arrays, PyTorch or CuPy tensors (on any device) and lists all work, both as input and as output.

import numpy as np def bright_spots(batch): # a toy "detector": one box per tile around its max ... out = [] ... for tile in batch: ... y, x = np.unravel_index(tile.argmax(), tile.shape) ... out.append(([[x - 2, y - 2, x + 3, y + 3]], [float(tile.max())], [0])) ... return out image = np.zeros((300, 400), dtype=np.uint8) image[150, 200] = 255 dets = predict_tiled(image, bright_spots, tile_size=128, score_threshold=1) len(dets), dets.boxes.tolist() (1, [[198.0, 148.0, 203.0, 153.0]])

TileResult module-attribute

TileResult = tuple[Any, Any, Any]

(boxes (N, 4), scores (N,), class_ids (N,)) for one tile, in any array type.

Model module-attribute

Model = Callable[[Any], Sequence[TileResult]]

A batch of tiles in, one :data:TileResult per tile out.

Detections dataclass

Detections(
    boxes: NDArray[float64] = (
        lambda: np.zeros((0, 4), dtype=np.float64)
    )(),
    scores: NDArray[float64] = (lambda: np.zeros(0))(),
    class_ids: NDArray[int64] = (
        lambda: np.zeros(0, dtype=np.int64)
    )(),
    profile: Any = None,
)

Boxes on the full image, with scores and class ids.

Attributes:

Name Type Description
boxes NDArray[float64]

(N, 4) float (x1, y1, x2, y2) in image pixels.

scores NDArray[float64]

(N,) confidence scores, sorted from high to low after a merge.

class_ids NDArray[int64]

(N,) integer class ids.

profile Any

Georeferencing of the image (a :class:plakakia.io.GeoProfile), if known. It lets :meth:to_geojson place the boxes on a map.

map_polygons

map_polygons(
    transform: Any = None,
) -> npt.NDArray[np.float64]

Box corners in map coordinates, (N, 5, 2) closed rings.

Parameters:

Name Type Description Default
transform Any

An affine transform from (col, row) pixels to map coordinates (a rasterio/affine Affine, or its 6 coefficients (a, b, c, d, e, f)). Defaults to the transform of :attr:profile.

None

to_geojson

to_geojson(
    transform: Any = None,
    *,
    crs: Any = None,
    class_names: Sequence[str]
    | dict[int, str]
    | None = None,
) -> dict[str, Any]

A GeoJSON FeatureCollection with one polygon per box.

Without a transform or :attr:profile, coordinates stay in pixels, which is still handy for viewers that read GeoJSON.

Parameters:

Name Type Description Default
transform Any

See :meth:map_polygons. Defaults to the profile's transform.

None
crs Any

Coordinate reference system written as the collection's crs member (read by QGIS and GDAL). Defaults to the profile's CRS.

None
class_names Sequence[str] | dict[int, str] | None

Names for the class ids, added to each feature's properties.

None
Example

dets = Detections([[0, 0, 10, 5]], [0.9], [1]) feature = dets.to_geojson(class_names=["car", "truck"])["features"].pop() feature["properties"]

tile_batches

tile_batches(
    image: Any,
    tile_size: SizeLike = 640,
    step_size: SizeLike | None = None,
    *,
    batch_size: int = 16,
    axes: Sequence[int] = (0, 1),
    cover_edges: bool = True,
) -> Iterator[tuple[Any, npt.NDArray[np.intp]]]

Yield batches of tiles and their (x1, y1, x2, y2) coordinates.

Only one batch is in memory at a time, and the tiles keep the image's array type: a PyTorch or CuPy image on a GPU gives batches on the same GPU.

Parameters:

Name Type Description Default
image Any

Any array with .shape and slicing (NumPy, PyTorch, CuPy, ...).

required
tile_size SizeLike

Tile side, or (height, width). Clamped to the image size.

640
step_size SizeLike | None

Stride, or (height, width). Defaults to 80% of the tile (20% overlap).

None
batch_size int

Tiles per batch.

16
axes Sequence[int]

The (y, x) axes of image, e.g. (1, 2) for (bands, H, W).

(0, 1)
cover_edges bool

Add tiles aligned to the right/bottom borders so every pixel is seen by the model.

True

Yields:

Type Description
Any

(batch, coords): the tiles stacked along a new first axis, and the

NDArray[intp]

(B, 4) NumPy coordinates of each tile.

Example

image = np.zeros((100, 150, 3), dtype=np.uint8) shapes = [b.shape for b, _ in tile_batches(image, 64, 64, batch_size=4)] shapes [(4, 64, 64, 3), (2, 64, 64, 3)]

merge_detections

merge_detections(
    boxes: ArrayLike,
    scores: ArrayLike,
    class_ids: ArrayLike,
    *,
    iou_threshold: float = 0.5,
    class_agnostic: bool = False,
    seam: ArrayLike | None = None,
    seam_margin: float = 2.0,
) -> Detections

Remove duplicate boxes with NMS, and fuse boxes cut by tile seams.

Parameters:

Name Type Description Default
boxes ArrayLike

(N, 4) (x1, y1, x2, y2) on the full image.

required
scores ArrayLike

(N,) confidence scores.

required
class_ids ArrayLike

(N,) class ids. Boxes of different classes never merge unless class_agnostic.

required
iou_threshold float

Boxes overlapping a better box by more than this IoU are dropped.

0.5
class_agnostic bool

Merge across classes.

False
seam ArrayLike | None

(N,) booleans, true for boxes that touch an inner tile border (so they may be the cut-off part of a larger object). Such a box is fused into a box that contains it (intersection over the smaller box above iou_threshold), and two cut boxes that meet at a seam are fused into one. The fused box is the union of the parts, with the best score.

None
seam_margin float

Pixels within which two cut boxes count as touching.

2.0

Returns:

Type Description
Detections

The merged :class:Detections, sorted by score.

Example

merged = merge_detections( ... [[0, 0, 10, 10], [1, 1, 10, 10], [20, 0, 30, 10]], [0.9, 0.8, 0.7], [0, 0, 0] ... ) merged.boxes.tolist(), merged.scores.tolist() ([[0.0, 0.0, 10.0, 10.0], [20.0, 0.0, 30.0, 10.0]], [0.9, 0.7])

predict_tiled

predict_tiled(
    image: Any,
    model: Model,
    tile_size: SizeLike = 640,
    step_size: SizeLike | None = None,
    *,
    batch_size: int = 16,
    axes: Sequence[int] = (0, 1),
    cover_edges: bool = True,
    full_image: bool | int = False,
    score_threshold: float = 0.0,
    iou_threshold: float = 0.5,
    class_agnostic: bool = False,
    fuse_seams: bool = True,
    seam_margin: float = 2.0,
    profile: Any = None,
) -> Detections

Detect objects on a large image, tile by tile, and merge the boxes.

The image is cut into overlapping tiles at native resolution, the model runs on batches of tiles, every box is moved from tile to image coordinates, and duplicates are merged with class-aware NMS. Boxes cut by a tile border are fused with the rest of their object (see :func:merge_detections).

Parameters:

Name Type Description Default
image Any

The full image: a NumPy array, or a PyTorch/CuPy tensor (tiles stay on its device). Any layout: use axes to say where (y, x) are.

required
model Model

model(batch) -> [(boxes, scores, class_ids), ...]: one result per tile of the batch, boxes (x1, y1, x2, y2) in tile pixels. Any array type.

required
tile_size SizeLike

Tile side, or (height, width). Use your model's input size.

640
step_size SizeLike | None

Stride. Defaults to 80% of tile_size (20% overlap).

None
batch_size int

Tiles per model call.

16
axes Sequence[int]

The (y, x) axes of image: (0, 1) for (H, W, C), (1, 2) for (C, H, W) tensors and GeoTIFFs.

(0, 1)
cover_edges bool

Add tiles aligned to the right/bottom borders, so objects at the image border are not missed.

True
full_image bool | int

Also run the model once on the whole image, downscaled so that its longest side is max(tile_size) (or this many pixels if an int). It finds objects larger than a tile. NumPy images only.

False
score_threshold float

Drop boxes scoring below this before merging.

0.0
iou_threshold float

IoU above which overlapping boxes of a class are duplicates.

0.5
class_agnostic bool

Merge overlapping boxes across classes.

False
fuse_seams bool

Fuse boxes cut by a tile border with the rest of their object.

True
seam_margin float

Pixels from a tile border within which a box counts as cut.

2.0
profile Any

The image's :class:plakakia.io.GeoProfile (from :func:plakakia.io.read_geotiff). Stored on the result, so :meth:Detections.to_geojson returns map coordinates.

None

Returns:

Type Description
Detections

class:Detections on the full image, sorted by score.