SAM3OrthoFeatureExtractor#
- class rapidtools.processing.SAM3OrthoFeatureExtractor(prompt: str, patch_size: float = 30.0, unit: str = 'feet', overlap_ratio: float | None = None, model_id: str = 'facebook/sam3', device: str = 'auto', batch_size: int = 4, load_in_4bit: bool = True, threshold: float = 0.5, mask_threshold: float = 0.5, max_missing_data_ratio: float = 0.95, merge_overlaps: bool | None = None, cancel_event: Event | None = None, raster_path: str | Path | None = None, neck_width_m: float | None = None, min_detection_rate: float | None = None, regularize: bool | None = None)[source]#
Bases:
objectPipeline component that uses local SAM 3 to discover real-world assets.
The extractor tiles a high-resolution orthomosaic raster into square patches of
patch_size(in real-world units), runs SAM 3 on each batch of patches with the given text prompt, and maps the resulting pixel masks back to WGS84 polygons. Because neighboring tiles overlap, the same object is frequently detected more than once.For most prompts a final
unary_unionmelts all detections that touch into a single geometry. That suits area features (roads, vegetation, water) but melts neighboring objects together: two houses whose masks meet, a house and its garage, cars parked side by side. Passmerge_overlaps=Falsefor objects: each object then becomes one asset, fused from all the tiles that saw it (seefuse_view_detections()). Two detections from different tiles are merged only when they agree inside the area both tiles covered, never two instances from the same tile, and the outline is the one most tiles agree on. Each asset carries the model’s meanconfidenceand the number of tiles (views) that detected it.Prompts that name buildings (
'building','house','structure'; seeis_building_prompt()) get building defaults for every setting left atNone: objects are kept separate, tiles overlap by half so that every building is seen whole by several of them,neck_width_m=1.0cuts masks that bleed across the gap between two roofs,min_detection_rate=0.3drops buildings most of the tiles that saw them did not detect, andregularize=Truegives the footprints straight, square walls withFootprintRegularizer. For the best outlines, refine the result on close-up crops withAerialImageryExtractorandBuildingRegularizer(the GUI does both). Buildings are found best with tiles of about 50 m.- Parameters:
prompt (str) – The text prompt describing the feature to extract (e.g.,
'building','swimming pool').patch_size (float, optional) – Edge length of each square scanning tile, expressed in
unit. Defaults to 30.0.unit (str, optional) – Spatial unit of
patch_size:'pixels','meters','feet','yards','kilometers'or'miles'. Defaults to'feet'.overlap_ratio (float | None, optional) – Fractional overlap between adjacent tiles (0.0 <= r < 1.0). Higher values reduce edge artifacts at the cost of more inference. Defaults to
None: 0.5 for building prompts, 0.15 otherwise.model_id (str, optional) – Hugging Face repository ID of the SAM 3 model. Defaults to
'facebook/sam3'.device (str, optional) – Compute device (
'cuda','cpu'or'auto'). Defaults to'auto'.batch_size (int, optional) – Number of tiles sent to the model per inference call. Defaults to 4.
load_in_4bit (bool, optional) – Whether to load the model with 4-bit quantization. Defaults to
True.threshold (float, optional) – Detection confidence threshold. Defaults to 0.5.
mask_threshold (float, optional) – Threshold for binarizing the predicted masks. Defaults to 0.5.
max_missing_data_ratio (float, optional) – Tiles whose nodata fraction exceeds this value are skipped. Defaults to 0.95.
merge_overlaps (bool | None, optional) –
Truedissolves all touching or overlapping detections into single polygons (area features).Falsefuses the views of each object into one asset withconfidenceandviewsattributes and keeps neighbors separate (buildings, countable objects). Defaults toNone:Falsefor building prompts,Trueotherwise.neck_width_m (float | None, optional) – With
merge_overlaps=False, a mask whose pieces are joined only by a strip narrower than this many meters is cut into those pieces before fusion.0only separates pieces that do not touch. Defaults toNone: 1.0 for building prompts kept separate, 0 otherwise.min_detection_rate (float | None, optional) – With
merge_overlaps=False, objects detected by fewer than this share of the tiles that had them whole in view are dropped, which removes detections that only one of several views produced. Defaults toNone: 0.3 for building prompts kept separate, 0 (keep all) otherwise.regularize (bool | None, optional) – Give the detected footprints straight, square walls with
FootprintRegularizer(which also makes them non-overlapping and drops those under 4 m^2). Defaults toNone:Truefor building prompts,Falseotherwise. PassFalsefor the raw mask outlines.cancel_event (Event | None, optional) – Cooperative cancellation flag checked before every tile. When set,
OperationCanceledis raised. Defaults toNone.
Settings left at
Nonefollow the prompt when the scan runs, so an extractor whosepromptis changed between scans (to reuse the loaded model) picks up the defaults of the new prompt;scan_settings()shows the values in effect.Example
Discover buildings in a Bing-derived orthomosaic and feed the result into a downstream pipeline:
>>> from rapidtools.core import BoundingBox >>> from rapidtools.processing import ( ... BingOrthomosaicExtractor, SAM3OrthoFeatureExtractor ... ) >>> region = BoundingBox(-118.15, 34.18, -118.14, 34.19) >>> tiff = BingOrthomosaicExtractor(zoom_level=19)(region, 'area.tiff') >>> extractor = SAM3OrthoFeatureExtractor( ... prompt='building', patch_size=50, unit='meters', batch_size=8 ... ) >>> extractor.scan_settings().regularize True >>> buildings = extractor(tiff) >>> buildings[0].attributes['asset_type'] 'building'
Methods
Scan the raster, extract features, and merge overlaps into a collection.
The scan settings in effect for the current prompt.
- scan_settings() ScanSettings[source]#
The scan settings in effect for the current prompt.
Settings set explicitly are returned as they are; those left at
Nonetake the defaults of the prompt (building defaults for building prompts, see the class description).- Returns:
ScanSettings – The overlap, merge, neck, detection-rate and regularization settings the next scan will use.
Example
>>> extractor = SAM3OrthoFeatureExtractor('house', patch_size=50, ... unit='meters') >>> s = extractor.scan_settings() >>> s.merge_overlaps, s.overlap_ratio, s.regularize (False, 0.5, True) >>> extractor.prompt = 'tree' >>> extractor.scan_settings().merge_overlaps True
- detect(raster_path: str | Path) PhysicalAssetCollection[source]#
Scan the raster, extract features, and merge overlaps into a collection.
- Parameters:
raster_path (str | Path) – Path to a GeoTIFF orthomosaic (any CRS understood by rasterio; output geometries are always WGS84).
- Returns:
PhysicalAssetCollection – One
PhysicalAssetper merged feature (or per object when objects are kept separate). Each asset carries the attributes'asset_type'(the prompt),'source_model'and'extraction_scale'; objects also carry'confidence'(mean SAM 3 score of the fused detections,Noneif the model reported none) and'views'(how many tiles detected the object). With regularization (the default for building prompts) the outlines have straight, square walls. The collection is empty if nothing was detected. Afterwardscanned_areaholds the ground the tiles covered (WGS84), whichAerialEvidenceneeds to tell “looked and found nothing” from “never looked”.- Raises:
OperationCanceled – If
cancel_eventis set between two tiles.FileNotFoundError – If
raster_pathdoes not exist.
Example
>>> extractor = SAM3OrthoFeatureExtractor(prompt='road') >>> roads = extractor('data/ortho.tif') >>> len(roads) 12