Tiled segmentation engine with seam-aware merging and global relabeling
Source:R/tile_engine.R
segmenter_tile_engine.RdRuns a complete tiled segmentation workflow on a large `SpatRaster`: (1) tile to disk with overlap, (2) segment each tile to disk with globally unique IDs, (3) detect seam adjacencies, (4) compute per-segment means from tiles, (5) merge adjacent seam segments by similarity, (6) apply merges streamingly, and (7) relabel all segments globally to consecutive IDs.
Usage
segmenter_tile_engine(
x,
segment_fun,
seg_args,
tile_size = 2048,
buffer = 64,
seam_thr = 0.8,
out_file = "final_seg.tif",
tile_dir = tempdir(),
cleanup_tiles = FALSE,
cleanup_seg_tiles = FALSE,
verbose = TRUE
)Arguments
- x
A `SpatRaster` to segment (single- or multi-band).
- segment_fun
A function implementing segmentation on a single tile. Must accept a `SpatRaster` as first argument and return a 1-layer integer segmentation raster.
- seg_args
A named list of additional arguments passed to `segment_fun`.
- tile_size
Integer. Tile size in pixels (rows/cols) excluding buffer.
- buffer
Integer. Overlap (in pixels) added around each tile.
- seam_thr
Numeric scalar. Threshold for merging seam-adjacent segments. Applied to Euclidean distance between per-segment mean feature vectors.
- out_file
Character. Output file path for the final segmentation.
- tile_dir
Character. Directory used for intermediate tile products.
- cleanup_tiles
Logical. If `TRUE`, remove the raw image tiles after segmentation.
- cleanup_seg_tiles
Logical. If `TRUE`, remove segmented tile files once the final output is produced.
- verbose
Logical. If `TRUE`, print progress messages.
Value
A file-backed `SpatRaster` pointing to `out_file`, containing a 1-layer integer segmentation with globally consecutive IDs.
Details
This function is intended as a robust, memory-safe orchestration layer for classical OBIA workflows where full-scene segmentation is infeasible in RAM.
See vignette("tiled-segmentation-workflow") for an end-to-end explanation
of the tiling and seam-merge framework.
**Seam-aware merging.** Seam adjacencies are extracted only from the overlap zone (buffer) of each tile to identify segment labels that touch across tile borders. Segment means are computed from the original image values using tile-wise streaming (no VRT reads). Adjacent segments are merged when their mean vectors are within `seam_thr`, using transitive closure (union-find).
**Fast path when no merges are needed.** If no seam adjacencies are found (or if all candidate adjacencies are invalid due to missing means), the function mosaics the segmented tiles directly to `out_file` without merging.
**Streaming-safe output.** Before applying the merge map, the segmented tile mosaic is materialized to a real file-backed raster to ensure stable block reads/writes. Merging and final relabeling are performed using streaming reads/writes to support large rasters.