MapillaryFeatureExtractor#
- class rapidtools.processing.MapillaryFeatureExtractor(classes: Sequence[str], access_token: str | Path | None = None, region: BoundingBox | PolygonRegion | None = None, start_date: str = '', end_date: str = '', filter_rapid_only: bool = True, detection_source: str | Mapping[str, str] = 'auto', localization_method: str = 'auto', geometry: str = 'auto', min_observations: int = 1, frame_spacing_m: float = 0.0, camera_height_m: float = 2.4, min_object_width_m: float | None = None, assumed_depth_m: float = 10.0, reid: bool = False, label_mapper: Any = None, asset_type: str | None = None, id_prefix: str = 'street', save_directory: str | Path = 'street_detections', max_workers: int = 10, cancel_event: Event | None = None, client: MapillaryClient | None = None, **options: Any)[source]#
Bases:
objectDiscover objects along a Mapillary survey and place them on the ground.
The extractor lists every image in a region (optionally only RAPID Facility uploads within a date window), reads Mapillary’s segmentation detections for the requested classes as metadata, estimates where each detected object stands from the camera pose and the detection’s position in the frame, and merges repeated sightings into one asset per object. Objects seen from two or more camera positions are triangulated; single sightings fall back to the one-view estimate and are labeled as such.
Detections of the collection vehicle itself recur at the same place in every frame of a sequence and are removed before localization.
Classes outside the Mapillary vocabulary can be detected with SAM 3 on downsampled thumbnails when
detection_sourceallows it; the default only does so for classes Mapillary cannot supply.- Parameters:
classes (Sequence[str]) – Objects to find, in plain English (
'cars','utility poles') or as exact Mapillary labels ('object--vehicle--truck').access_token (str | Path | None) – Mapillary API token, the path of a file holding it, or
Noneto read theMAPILLARY_ACCESS_TOKENenvironment variable. Not needed whenclientis given.region (BoundingBox | PolygonRegion | None) – Area to survey. May instead be passed when the extractor is called.
start_date (str) – Inclusive lower bound on capture date (
YYYY-MM-DD).end_date (str) – Inclusive upper bound on capture date.
filter_rapid_only (bool) – Only use imagery uploaded by the RAPID Facility. Defaults to
True.detection_source (str | Mapping[str, str]) –
'auto'(Mapillary map features for static point classes such as utility poles and hydrants, Mapillary detections for the rest, SAM 3 for unresolved classes),'mapillary'(detections only; skip unresolved classes with a warning),'sam3'(SAM 3 for every class),'sam3_tiles'(SAM 3 on tiles of the full-resolution frames, for objects too small to find in a thumbnail, such as fire hydrants; see thesam3_tile_*options) or'map_features'(only Mapillary’s pre-triangulated map features; other classes are skipped). A mapping chooses per class and leaves the rest on'auto':{'buildings': 'sam3'}segments every building on its own with SAM 3 while vehicles still come from Mapillary.localization_method (str) – How sightings become objects.
'auto'(default) uses'points'for buildings and other structures and'fusion'for everything else.'fusion'reads every outline as a range scan and fuses all frames of a survey day in a ground occupancy grid; objects are the cells most frames agree are occupied, whatever their size and from however many streets they were seen (seestreet_fusion).'points'labels the survey’s own structure-from-motion point cloud with the outlines and reads structures off the labeled points as footprint polygons (seestreet_structures); it needs panoramas Mapillary has reconstructed and falls back to'fusion'otherwise.'instances'is for sightings that are one outline per object, as a segmentation model gives (detection_source='sam3'): outlines in different frames are linked into one object by the reconstructed points they share, which keeps neighbors apart where a fence or a shed joins them in Mapillary’s building surface (seestreet_instances).'auto'uses it for buildings detected with SAM 3. It downloads a thumbnail of every frame and runs the model on each, so it costs GPU time that'points'does not.'footprints'is for buildings whose footprints are known (thefootprintsoption): each footprint is projected into the frames around it and the outlines found there are its sightings, so nothing has to be discovered, located or told apart (seestreet_footprints).'auto'uses it for buildings wheneverfootprintsis given, with Mapillary’s outlines or a model’s.'tracks'is the earlier method: detections linked frame to frame by bearing, triangulated and merged by a set of rules tuned on vehicles (seestreet_tracking).'voting'accumulates rays on a ground grid and takes the peaks, and'cluster'clusters single-view positions by radius; both are baselines.geometry (str) – Geometry written to each asset.
'auto'(default) gives structures a footprint polygon and everything else a point;'footprint'gives every object found by'fusion'or'points'its footprint polygon;'point'gives every object a point (a structure’s is the footprint center). The footprint’s size is always in the attributes.min_observations (int) – Distinct frames an object must have been seen in;
3is a sound choice for a survey sampled every few meters. Defaults to 1.frame_spacing_m (float) – Keep one frame per this many meters along each sequence before detecting;
0keeps every frame. Defaults to 0.camera_height_m (float) – Camera height above the road, used for single-view ranges. Defaults to 2.4 (roof-mounted rig).
min_object_width_m (float | None) – Objects narrower than this, judged from the outline’s angular width at the estimated distance, are fragments or false detections and are dropped. Resolution-independent and tolerant of partial occlusion.
None(the default) lets'fusion'take it per class from the sightings themselves, the typical width of an outline between 0.2 and 1 m (1 m for vehicles, about 0.3 m for fire hydrants), and is 1.0 for the other methods.assumed_depth_m (float) – Depth given to a structure’s footprint when the survey saw less of it; the
depth_sourceattribute then reads'assumed'. Defaults to 10.0.reid (bool) – After localization, compare the appearance of objects from different sequences that lie within
reid_max_distance_mand merge look-alikes, removing double counts from repeated passes. Downloads one thumbnail per compared object and loadsreid_model. Appearance only ever adds merges: an object without a sighting at leastreid_min_width_pxwide is left as geometry placed it. Defaults toFalse.label_mapper (Any | None) – Optional
MapillaryLabelMapperto translate class names the built-in aliases do not cover.asset_type (str | None) –
asset_typeattribute written to every asset. Defaults to the class name each object was found under.id_prefix (str) – Prefix of the generated asset IDs. Defaults to
'street'.save_directory (str | Path) – Where SAM 3 thumbnails are cached when that source is used.
max_workers (int) – Threads for metadata and thumbnail downloads. Defaults to 10.
cancel_event (Event | None) – Cooperative cancellation flag checked between images and batches.
client (MapillaryClient | None) – Pre-configured client; one is created from
access_tokenotherwise.
The arguments above cover a first run. The options below are passed as keywords in the same way (
MapillaryFeatureExtractor(..., occupancy_threshold=0.7)); none of them is needed to get started, and a misspelled name raises aTypeErrorthat suggests the closest match.Occupancy fusion (
'fusion', the default method for objects):fusion_range_m(float): Farthest range at which a frame votes in'fusion'. Defaults to 30.0.cell_m(float | None): Ground cell of the'fusion'grid.Nonepicks a quarter ofmin_object_width_m, between 0.1 and 0.5 m.occupancy_threshold(float): Share of the range-weighted votes on a ground cell that must say “occupied” in'fusion'. Defaults to 0.6.strong_views(int | None): Frames that, outlining the same spot from three or more directions, keep an object the vote turns down because most frames in range show nothing (a hydrant behind a bush, or one the detector often misses). Such objects have avote_shareunderoccupancy_thresholdand are worth a look byDetectionVerifier.0keeps only what the vote accepts;None(the default) uses 5 for classes with outlines under a meter wide and 0 for the rest.min_range_m(float): Closest plausible object. Defaults to 2.0.bearing_sigma_deg(float): One-sigma bearing error of a sighting. Defaults to 0.75.aerial(AerialEvidence | Mapping[str, AerialEvidence] | None): Detections of a class in an overhead image of the same area, fused with the street frames in'fusion'(seeAerialEvidence). A mapping gives one per class (keys as inclasses); a single one is used for every class placed by fusion. Assets then carrysources('both','street'or'aerial'); those only the image shows have no observations. Defaults toNone.
Structures from the point cloud (
'points', the default for buildings):structure_range_m(float): Farthest range at which a frame votes on a point in'points', and from which a structure gets a sighting. Defaults to 40.0.min_gap_m(float): Free ground that separates two wall pieces in'points'. Pieces up to three times as far apart along the street are joined when the frames in front of them outline them as one building. Defaults to 1.0.structure_footprint(str):'stepped'(default) draws a footprint whose front follows the setbacks of the facade (garage forward, entrance back), with the unseen rear filled in;'rectangle'draws one facade-aligned rectangle;'observed'draws only the convex outline of what was seen.structure_views(int): Sightings kept per structure, spread over the directions it was seen from. Defaults to 12.point_cloud_dir(str | Path | None): Where downloaded point clouds are cached. Defaults to<save_directory>/point_clouds.footprints(PhysicalAssetCollection | str | Path | Sequence | None): Known building footprints: a collection, the path of a GeoJSON file, or polygons in longitude and latitude. When given, buildings are matched to them ('footprints') and come back with the footprint’s own geometry, identifier and attributes, plusframes_expected(the frames it should be visible in) andframes_seen. Defaults toNone: buildings are discovered.report_unmapped(bool): Withfootprints, also place the buildings the layer does not have (unmappedisTrueon them). With a segmentation model these come from the masks that lie on no footprint ('instances'); with Mapillary’s outlines, from the structures of'points'that lie off every footprint, which downloads the point clouds and costs about a minute per thousand frames. Either needs frames with a point cloud. Defaults toTrue;Falsematches the layer only.
Frames and detections (every method):
ego_filter(bool): Remove detections of the collection vehicle. Defaults toTrue.ego_min_recurrence(float): Fraction of a sequence’s frames a box must recur in to count as the collection vehicle. Defaults to 0.5.frame_batch_size(int): Frames whose metadata is fetched and converted at a time. Each image’s detection payload (every Mapillary label, as encoded geometry) is dropped as soon as the requested classes have been read from it, so memory use is bounded by one batch rather than by the size of the survey. Defaults to 200.simplify_tolerance(float): Douglas-Peucker tolerance, in normalized image units, applied to every detection outline before it is stored (0.002is about four pixels of a 2048-wide image), capped at 1 % of the outline’s longest side so small, distant objects keep their detail. Mapillary outlines trace every pixel step of a mask, so this cuts the memory of a city-wide run several-fold without changing which objects are found.0keeps the raw outlines. Defaults to 0.002.
SAM 3 detection (classes Mapillary does not segment, or
detection_source='sam3'):sam3_model(Any | None): Pre-loaded segmentation model: the local SAM 3 wrapper, or anything else with the samerun_inference. The local wrapper is loaded on demand otherwise.sam3_prompts(Mapping[str, str] | None): The text the model is asked for per class, where the class name is not it. SAM 3 wants a singular noun:{'buildings': 'house'}.join_wings_by(str): How'instances'decides that two masks are wings of one building.'touching'(default): their outlines touch in the frames in front of them.'prompt': a point-prompt model, asked for the whole object at a few points on one, returns a mask that covers the other; this joins neighbors far less often and costs a few model calls per pair of candidate wings.sam3_point_model(Any | None): Pre-loaded point-prompt model forjoin_wings_by='prompt': anything withsegment_at(image, points). SAM 3’s is loaded on demand otherwise.sam3_model_id(str): Hugging Face repository of the SAM 3 weights. Defaults to'facebook/sam3'.sam3_threshold(float): SAM 3 detection confidence threshold. Defaults to 0.5.sam3_mask_threshold(float): SAM 3 mask binarization threshold. Defaults to 0.5.sam3_image_size(str): Thumbnail size SAM 3 runs on:'1024'(default) or'2048'.sam3_batch_size(int): Thumbnails per SAM 3 inference call. Defaults to 4.sam3_tile_px(int): Side of the tiles'sam3_tiles'cuts from a full-resolution frame. Defaults to 1024.sam3_tile_overlap(float): Share of a tile the next one repeats, so that an object on a seam is whole in one of them. Defaults to 0.125.sam3_tile_elevation_deg(tuple[float, float]): Band of a panorama that is tiled, as its lowest and highest elevation. Defaults to(-26.5, 0.5): one row of tiles for a 13,504 pixel panorama, showing the ground from about 5 m out. Objects cut by the lower edge of the band are left out, and frames say nothing about the ground nearer than it shows. Perspective frames are tiled whole.sam3_tile_spacing_m(float): One frame per this many meters is searched on tiles. Defaults to 10: SAM 3 finds a hydrant in three of four full-resolution frames at 30 m, so few frames are needed.keep_full_resolution(bool): Keep the full-resolution frames (about 7 MB per panorama) insave_directoryafter their tiles were searched. Defaults toFalse.load_in_4bit(bool): Load SAM 3 with 4-bit quantization. Defaults toTrue.device(str): Compute device for SAM 3 ('auto','cuda','cpu').
Appearance re-identification (
reid=True):reid_model(str): Hugging Face vision backbone for the embeddings. Defaults to'openai/clip-vit-base-patch16'; DINOv2 checkpoints work too.reid_min_similarity(float | None): Cosine similarity at which two crops count as the same object.None(the default) takes the value recommended forreid_model: 0.89 for CLIP, 0.83 for DINOv2.reid_max_distance_m(float): Only objects this close are compared. Defaults to 6.0.reid_min_width_px(float): Narrowest detection whose crop is embedded, in pixels of a 2048-pixel-wide thumbnail (scaled toreid_image_size). On the Spokane survey, crops below this width scored as alike whether or not they showed the same vehicle.0embeds every object. Defaults to 100.reid_image_size(str): Thumbnail size the re-identification crops are cut from:'2048'(default, the size the thresholds were tuned on) or'1024'.reid_embedder(Any | None): A readyAppearanceEmbedder(or anything withembed(images)) to use instead of loadingreid_model.
Earlier methods (
localization_method'tracks','voting'or'cluster'only):max_range_m(float): Farthest triangulated position reported, and the farthest single-view range kept as a prior. Defaults to 60.0.max_single_view_range_m(float): A single-view object whose nearest sighting is farther than this is not reported; beyond it the ground- contact range is a guess and the track tends to hop between neighboring objects.0keeps them. Defaults to 30.0.witness_radius_m(float): Negative-evidence check: a weak object (a single view, or a triangulation never seen closer than 25 m) that same- day frames within this distance had in view, without any detection of the class along its bearing, is dropped (at least two such frames, outnumbering frames that did see it, tallied per survey day).0disables the check. Defaults to 12.0.object_height_m(float): Typical height of the class. When a track’s ground-contact ranges disagree with its triangulation, the track is called moving only if enough of an object this tall is visible for occlusion to be ruled out. Defaults to 1.5 (vehicles).min_area_fraction(float | None): Deprecated. Pixel-area floor below which a detection is ignored;None(the default) keeps only a tiny floor for decoding noise. Size is judged withmin_object_width_minstead.cluster_radius_m(float): Sightings closer than this are the same object in the legacy'cluster'method; with'tracks'it only sets the defaultmax_merge_m(1.5 times this value). Defaults to 4.0.max_merge_m(float | None): Farthest two estimates can be and still be merged into one object.Noneuses1.5 * cluster_radius_m.track_gap_frames(int): Frames a track may miss before it is closed. Defaults to 2.min_path_distance_m(float): Objects closer than this to the line the camera drove are dropped; the survey vehicle passed through that spot. Defaults to 1.5.object_size_m(float): Object footprint used by the voting method. Defaults to 4.5.merge_pieces_of_neighbors(bool): After localization, fold an object whose closest sightings show a better-located neighbor into that neighbor: the second track left by a split outline (a car cut in two by a pole, or into a front and a rear) or by the tracker sliding between vehicles lined up along the line of sight. Such pairs share frames, which the position merge takes as proof of two objects, so they are judged on what their sightings show (seemerge_pieces()). Defaults toTrue.close_range_m(float): Range within which an object must have been seen to be reported. Ground-contact ranges read from farther away are off by a third and the tracker hops between vehicles lined up down the road, so an object never seen this close whose closest rays point at a vehicle within 15 m already placed from the close pass is a far sighting of that vehicle, and is dropped unless it is well triangulated regardless (parallax of 45 degrees or more and uncertainty of half a meter or less). One whose rays point elsewhere, a car set back in a driveway or down a side street, stays. The piece merge judges sightings by the same range.0keeps every object. Defaults to 20.min_sighting_deg(float): An object must have been seen at least once with an outline this wide or tall, in degrees of the panorama (6 degrees is 34 pixels on a 2048-pixel thumbnail, 225 on the original). What was never more than a speck cannot be identified by anyone and is not reported; a drive-by survey sees anything worth counting properly in some frame.0keeps every object. Defaults to 6.report_single_views(bool): Keep objects placed from ground-contact ranges alone, without parallax (localization='single_view'). Their positions are guesses; defaults toFalse.abeam_window_deg(float): Objects are built only from the sightings made while passing them, within this many degrees of abeam on either side of the direction of travel. A drive-by survey passes everything worth counting, and the passing frames carry the widest parallax and the largest outlines; the frames looking ahead or behind down the road cannot place anything and are where tracks slide between vehicles that line up. Those sightings are attached afterward to the objects their rays point at, so records and crops stay complete, but never create an object. Off (0) by default: the track classification is tuned on tracks that include the approach and a pass alone trips it, losing real vehicles on the surveys tried. Defaults to 0.
Example
>>> from rapidtools.core import BoundingBox >>> extractor = MapillaryFeatureExtractor( ... classes=['vehicles'], ... access_token='MLY|...', ... start_date='2025-08-01', ... min_observations=2, ... ) >>> region = BoundingBox(-117.45, 47.69, -117.44, 47.70) >>> vehicles = extractor(region) >>> vehicles[0].attributes['localization'] 'triangulated'