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]
|
|
scores |
NDArray[float64]
|
|
class_ids |
NDArray[int64]
|
|
profile |
Any
|
Georeferencing of the image (a :class: |
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 |
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: |
None
|
crs
|
Any
|
Coordinate reference system written as the collection's |
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 |
required |
tile_size
|
SizeLike
|
Tile side, or |
640
|
step_size
|
SizeLike | None
|
Stride, or |
None
|
batch_size
|
int
|
Tiles per batch. |
16
|
axes
|
Sequence[int]
|
The |
(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
|
|
NDArray[intp]
|
|
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
|
|
required |
scores
|
ArrayLike
|
|
required |
class_ids
|
ArrayLike
|
|
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
|
|
None
|
seam_margin
|
float
|
Pixels within which two cut boxes count as touching. |
2.0
|
Returns:
| Type | Description |
|---|---|
Detections
|
The merged :class: |
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 |
required |
model
|
Model
|
|
required |
tile_size
|
SizeLike
|
Tile side, or |
640
|
step_size
|
SizeLike | None
|
Stride. Defaults to 80% of |
None
|
batch_size
|
int
|
Tiles per model call. |
16
|
axes
|
Sequence[int]
|
The |
(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 |
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: |
None
|
Returns:
| Type | Description |
|---|---|
Detections
|
class: |