Source code for rapidtools.processing.street_fusion

# Copyright (c) 2025 The University of Washington
#
# This file is part of rapidtools.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its contributors
# may be used to endorse or promote products derived from this software without
# specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#
# You should have received a copy of the BSD 3-Clause License along with
# rapidtools. If not, see <http://www.opensource.org/licenses/>.
#
# Contributors:
# Barbaros Cetiner
#
#
# Last updated:
# 11-28-2026

"""
From sightings to objects by occupancy fusion.

Every detection outline in a street-level frame is read as a small range
scan, the way a robot reads a lidar sweep. Each image column the outline
covers gives a bearing; where the outline's lower edge lies below the
horizon it also gives the range at which the object meets the ground. That
tells three things about the ground along the column: it is *free* up to
the object, *occupied* for a stretch behind the contact, and *unknown*
beyond. Columns of a frame without any outline are free as far as the
detector can be trusted to see.

All frames of a survey day are fused in one ground grid. A cell belongs to
an object when the frames that vote on it mostly agree that it is occupied;
objects are the connected blobs of such cells. Nothing is tracked from
frame to frame and no pair of sightings is ever compared, so there are no
association rules to tune per class:

- An object seen from several streets, or on the way in and on the way
  out, lands on the same cells and is one object.
- A moving vehicle never collects agreeing votes, and the cells the survey
  vehicle drove through are free by construction.
- A far sighting has a long, uncertain band and a low weight; it cannot
  create an object by itself and cannot move one placed from close up.
- The same code handles a hydrant and a bus: only the cell size changes,
  and it is taken from the size of the outlines themselves.

The vote rests on frames that show nothing: for a class the detector
outlines in nearly every frame, they tell a parked car from a passing one.
For anything else their silence is weaker than it looks. A hydrant behind a
bush is seen from one side only, a car in a carport is hidden from half the
street, and a detector may skip a hydrant in plain view for a whole
sequence. So for classes with narrow outlines (under a meter: hydrants,
poles), an object the vote turns down is still kept when ``strong_views``
or more frames outlined the same cells from :data:`MIN_SEEN_SECTORS` or
more directions (the horizon is cut into :data:`N_SECTORS`): their lines of
sight cross at a point and fix the place without anyone's silence. Every
object carries its ``vote_share``, so the two kinds can be told apart. Wide
classes are left to the vote: the lines of sight to cars parked in a row
cross in many places where there is nothing.

Where frames keep seeing several outlines on one blob (two cars parked door
to door), the blob is split along the outlines of the closest frame that
separates them. Each object is then placed by intersecting the center
bearings of its sightings, and its footprint is the part of the blob that
lies inside the outlines of most of them (a plan-view visual hull). When
the sightings surround enough of the object (bearings spread by 60 degrees
or more), the position is refined to the center of the ellipse that the
left and right edges of the outlines are tangent to: the middle of an
outline points at the middle of what a frame sees, which for a car seen
from beside is nearer its close end, while the edges are tangents of the
object wherever the frame stands.

The same edges give the object its footprint. The cells most frames agree
on say where an object is, not how large: they reach past a parked car at
each end and more across it. A box is fitted that every edge line touches
from its own side, which measures the object's length, width and heading
(``heading_deg``). Objects seen from too few directions for that, and
classes outlined as one surface, keep the outline of their cells.

An overhead image of the same area can join in as one more source
(``aerial``, see :mod:`~rapidtools.processing.aerial_evidence`). Where it
has something to say, its log-odds are added to the street frames' share
of votes; where it does not (outside its coverage, under tree crowns), the
street frames decide alone, exactly as without it. Separate outlines in
the image split a blob the street frames see as one (two cars door to door
seen end-on), the image's outline becomes the footprint, and objects only
the image shows (a car behind a house) are kept where no street frame saw
the spot empty.

All geometry runs in a local meter frame from
:func:`~rapidtools.processing.street_localization.local_projection`.

Example:
    >>> from rapidtools.processing.street_fusion import fuse_observations
    >>> objects, counts, unproject = fuse_observations(sightings)  # doctest: +SKIP
    >>> objects[0].n_images, round(objects[0].area_m2)  # doctest: +SKIP
    (41, 9)
"""

from __future__ import annotations

import logging
import math
from collections import defaultdict
from collections.abc import Callable, Sequence
from dataclasses import dataclass, field
from typing import Any

import numpy as np
from scipy import ndimage
from scipy.optimize import least_squares
from scipy.spatial import cKDTree
from shapely.geometry import MultiPoint, MultiPolygon, Point, Polygon
from shapely.ops import unary_union

from rapidtools.core import Observation

from .aerial_evidence import AerialEvidence, LocalAerialEvidence
from .street_localization import local_projection, pixel_bearing, rotation_matrix

logger = logging.getLogger(__name__)

#: Width of one bearing column of a scan, in degrees.
BIN_DEG = 0.5
#: Number of bearing columns around the horizon.
N_BINS = int(round(360.0 / BIN_DEG))
#: Outlines whose lower edge is closer to the horizon than this give no range.
MIN_DEPRESSION_DEG = 1.0
#: Range at which a vote counts half as much as one from next to the object.
WEIGHT_RANGE_M = 10.0
#: Share of a blob's peak occupied weight a cell needs to count as footprint.
_CORE_FRACTION = 0.6
#: Bearings must spread at least this much for an intersection to be used.
MIN_PARALLAX_DEG = 10.0
#: Votes, in close frames, added to each side of a cell's street tally before
#: it is turned into log-odds next to an overhead image: a cell seen once from
#: far away is not taken as certain.
_STREET_PRIOR = 1.0
#: Share of an overhead outline that must lie in a blob for it to count there.
_AERIAL_SHARE = 0.5
#: Viewing directions in which the sightings of a cell are told apart.
N_SECTORS = 16
#: Directions a cell must have been outlined from for the sightings to fix its
#: place by themselves (see ``strong_views``).
MIN_SEEN_SECTORS = 3
#: Bearings of such an object's sightings must spread at least this much.
_STRONG_PARALLAX_DEG = 30.0
#: Bearings must spread at least this much for an object to be placed by the
#: ellipse its outlines' edges are tangent to.
_ELLIPSE_PARALLAX_DEG = 60.0
#: How square the corners of an object's plan outline are taken to be when a
#: box is fitted to the edges of its sightings: 2 is an ellipse, 1 a
#: rectangle with sharp corners. With 1.6 the boxes of parked cars came out
#: neither longer nor wider than their outlines in a drone orthomosaic.
_CORNER_POWER = 1.6
#: Widest gap, in meters, closed between patches of a surface on the ground
#: before they are told apart: a car standing on a driveway hides a strip
#: of it about this wide.
_GROUND_GAP_M = 2.0
#: Share of the frames outlining a ground surface's best cells that must
#: outline a cell for it to belong to the footprint.
_GROUND_VIEWS = 0.3

Project = Callable[[float, float], tuple[float, float]]
Unproject = Callable[[float, float], tuple[float, float]]


# --------------------------------------------------------------- records
@dataclass
class Scan:
    """
    One detection outline as a range scan.

    Attributes:
        index: Position of the sighting in the list it came from.
        cols: Bearing columns the outline covers (``N_BINS`` per turn).
        bottom: Lowest elevation of the outline in each column, degrees.
        top: Highest elevation of the outline in each column, degrees.
        center: Bearing of the outline's center, degrees clockwise from north.
        width: Angular width of the outline, degrees.
        lo: Near end of the occupied band per column in meters; ``nan``
            where the column gives no range.
        hi: Far end of the occupied band per column.
        contact: Ground-contact range of the outline (its nearer quartile),
            or ``nan`` when no column reaches below the horizon.
    """

    index: int
    cols: np.ndarray
    bottom: np.ndarray
    top: np.ndarray
    center: float
    width: float
    lo: np.ndarray | None = None
    hi: np.ndarray | None = None
    contact: float = math.nan


[docs] @dataclass class FusedObject: """ One object found by occupancy fusion. Attributes: x: East coordinate of the object in the local meter frame. y: North coordinate. cov: 2 x 2 position covariance in square meters, or ``None`` when the position is the blob center rather than an intersection. members: The sightings that show the object. footprint: Outline of the object on the ground, as ``(x, y)`` vertices in the local meter frame. area_m2: Area of the footprint. length_m: Long side of the footprint's bounding rectangle. width_m: Short side of the footprint's bounding rectangle. heading_deg: Direction of the long side in degrees clockwise from north (0 to 180), when the footprint is the box fitted to the edges of the sightings; ``None`` when it is the outline of the object's cells or of the overhead image. parallax_deg: Largest spread among the sightings' bearings. days: Survey days the object was seen on (none for an object only the overhead image shows). localization: ``'triangulated'`` (bearings intersected), ``'fused'`` (center of the occupied cells) or ``'aerial'`` (center of the overhead outline). rms_m: Root-mean-square distance between the position and the sightings' bearing lines, when triangulated. sources: With an overhead image, what showed the object: ``'both'``, ``'street'`` or ``'aerial'``; ``None`` without one. aerial_offset_m: Distance between the triangulated position and the center of the overhead outline, when both exist. vote_share: Largest share of "occupied" among the range-weighted votes of the street frames on the object's cells: near 1 when every frame in range outlined it, under the fusion's ``occupancy_threshold`` for an object kept because many frames agree on it although most in range show nothing (hidden from part of the street, or often missed by the detector). ``None`` for an object only the overhead image shows. """ x: float y: float cov: np.ndarray | None members: list[Observation] footprint: list[tuple[float, float]] area_m2: float length_m: float width_m: float parallax_deg: float days: list[str] = field(default_factory=list) localization: str = 'triangulated' rms_m: float | None = None sources: str | None = None aerial_offset_m: float | None = None vote_share: float | None = None heading_deg: float | None = None @property def n_images(self) -> int: """Number of distinct frames that show the object.""" return len({o.image_id for o in self.members}) @property def sigma_m(self) -> float: """One-sigma position uncertainty along the worst direction.""" if self.cov is None: return round(max(0.5, 0.25 * self.length_m), 2) return float(math.sqrt(max(float(np.linalg.eigvalsh(self.cov).max()), 0.0)))
@dataclass class _Frame: """A camera position with the scans made from it.""" image_id: str x: float y: float scans: list[Scan] = field(default_factory=list) fov: tuple[float, float] | None = None # (center, width) of a perspective frame class _Grid: """Evidence accumulated over a rectangle of ground cells.""" def __init__(self, x0: float, y0: float, cell: float, nx: int, ny: int) -> None: self.x0, self.y0, self.cell, self.nx, self.ny = x0, y0, cell, nx, ny self.occ = np.zeros((ny, nx), np.float32) self.free = np.zeros((ny, nx), np.float32) self.views = np.zeros((ny, nx), np.uint16) # Viewing directions the cell was outlined from, one bit per sector. self.seen = np.zeros((ny, nx), np.uint16) # Overhead evidence, when there is any: log-odds per cell, the outline # each cell lies in (0 for none) and the number of cells per outline. self.aerial_lo: np.ndarray | None = None self.aerial_id: np.ndarray | None = None self.aerial_cells: np.ndarray | None = None def set_aerial(self, log_odds: np.ndarray, outline: np.ndarray) -> None: """Attach overhead evidence laid on this grid's cells.""" self.aerial_lo = log_odds self.aerial_id = outline self.aerial_cells = np.bincount(outline.ravel()) def xy(self, flat: np.ndarray) -> tuple[np.ndarray, np.ndarray]: """Center coordinates of cells given by their flat indices.""" jj, ii = np.divmod(flat, self.nx) return self.x0 + (ii + 0.5) * self.cell, self.y0 + (jj + 0.5) * self.cell # --------------------------------------------------------------- scans def outline_angles(obs: Observation) -> tuple[np.ndarray, np.ndarray]: """ World bearing and elevation of every vertex of a sighting's outline. Uses the frame's full pose (``computed_rotation``) and camera model when the sighting carries them, and a level camera at ``compass_angle`` otherwise. Returns: tuple[numpy.ndarray, numpy.ndarray]: Bearings in degrees clockwise from north (not wrapped consistently; see :func:`scan_from_observation`) and elevations in degrees, negative below the horizon. Example: >>> from rapidtools.core import Observation >>> obs = Observation('i', 'car', [(0.5, 0.5), (0.75, 0.5), (0.75, 0.75)], ... 0.0, 0.0, 90.0, is_pano=True) >>> bearing, elevation = outline_angles(obs) >>> [round(float(b)) for b in bearing], [round(float(e)) for e in elevation] ([90, 180, 180], [0, 0, -45]) """ pts = np.asarray(obs.polygon, dtype=float) extra = obs.extra or {} kind = ( extra.get('camera_type') or ('spherical' if obs.is_pano else 'perspective') ).lower() if kind in ('spherical', 'equirectangular'): w, h = float(obs.image_width or 2.0), float(obs.image_height or 1.0) lon = 2.0 * np.pi * (pts[:, 0] - 0.5) lat = -2.0 * np.pi * (pts[:, 1] - 0.5) * h / w rays = np.c_[np.cos(lat) * np.sin(lon), -np.sin(lat), np.cos(lat) * np.cos(lon)] else: params = extra.get('camera_parameters') rays = np.array( [ pixel_bearing(x, y, kind, obs.image_width, obs.image_height, params) for x, y in pts ] ) rotation = extra.get('computed_rotation') if rotation is not None: world = rays @ rotation_matrix(rotation) # row-wise R.T @ ray else: c = math.radians(float(obs.compass_angle or 0.0)) world = np.c_[ math.sin(c) * rays[:, 2] + math.cos(c) * rays[:, 0], math.cos(c) * rays[:, 2] - math.sin(c) * rays[:, 0], -rays[:, 1], ] bearing = np.degrees(np.arctan2(world[:, 0], world[:, 1])) elevation = np.degrees(np.arctan2(world[:, 2], np.hypot(world[:, 0], world[:, 1]))) return bearing, elevation
[docs] def scan_from_observation(index: int, obs: Observation) -> Scan | None: """ Read a sighting's outline as a scan: its lower and upper edge per column. Args: index: Position of the sighting in its list, kept on the scan. obs: The sighting. Returns: Scan | None: The scan without range bands (see :func:`set_range_bands`), or ``None`` for an outline that wraps the whole horizon. Example: >>> from rapidtools.core import Observation >>> obs = Observation('i', 'car', [(0.50, 0.55), (0.52, 0.55), (0.52, 0.60), ... (0.50, 0.60)], 0.0, 0.0, 0.0, is_pano=True) >>> scan = scan_from_observation(0, obs) >>> round(scan.width, 1), round(float(scan.bottom.min()), 1) (7.2, -18.0) """ bearing, elevation = outline_angles(obs) ring = np.degrees(np.unwrap(np.radians(np.r_[bearing, bearing[0]]))) elev = np.r_[elevation, elevation[0]] if abs(ring[-1] - ring[0]) > 180.0: return None # the outline circles the camera (ground, sky, the car itself) steps = np.maximum(1, np.ceil(np.abs(np.diff(ring)) / (BIN_DEG / 2.0)).astype(int)) total = int(steps.sum()) if total > 40 * N_BINS: return None start = np.cumsum(steps) - steps pos = np.repeat(np.arange(len(steps)), steps) + ( np.arange(total) - np.repeat(start, steps) ) / np.repeat(steps, steps) a = np.interp(pos, np.arange(len(ring)), ring) e = np.interp(pos, np.arange(len(elev)), elev) b = np.floor(a / BIN_DEG).astype(int) b0 = int(b.min()) n = int(b.max()) - b0 + 1 if n > N_BINS: return None bottom = np.full(n, np.inf) top = np.full(n, -np.inf) np.minimum.at(bottom, b - b0, e) np.maximum.at(top, b - b0, e) seen = np.isfinite(bottom) cols = (np.arange(n) + b0)[seen] % N_BINS width = float(a.max() - a.min()) center = float(((a.max() + a.min()) / 2.0) % 360.0) return Scan(index, cols, bottom[seen], top[seen], center, width)
[docs] def set_range_bands( scan: Scan, camera_height_m: float = 2.4, min_range_m: float = 2.0, max_range_m: float = 30.0, elevation_sigma_deg: float = 0.75, range_sigma_fraction: float = 0.2, depth_factor: float = 0.5, flat: bool = False, ) -> Scan: """ Turn a scan's lower edge into an occupied range band per column. A column whose lower edge lies below the horizon meets flat ground at ``camera_height / tan(depression)``. The band starts two standard deviations in front of that contact and ends the same distance behind it plus the object's assumed depth. The range error has a part that grows with the square of the range (``elevation_sigma_deg`` of pixel and pose error) and a part proportional to it (``range_sigma_fraction``: sloping ground, a hidden lower edge), so a close sighting pins the object down and a far one says little more than its bearing. Runs of columns whose contact range changes smoothly are one visible face. The object is assumed to reach behind a face by ``depth_factor`` times the face's length, and never beyond the range at which a ray over the outline's top meets the ground (an object lower than the camera cannot hide ground behind its own shadow). Columns without a ground contact abstain: they claim nothing and clear nothing. Args: scan: Scan from :func:`scan_from_observation`; modified in place. camera_height_m: Camera height above the ground. min_range_m: Closest range a band may start at. max_range_m: Contacts beyond 1.5 times this are ignored. elevation_sigma_deg: One-sigma error of an outline edge's elevation. range_sigma_fraction: One-sigma range error as a share of the range. depth_factor: Assumed depth of an object behind a visible face, as a share of the face's length. flat: The outline is of something that lies on the ground (a driveway, a marking). Its outline is then its plan seen aslant: a column covers the ground from where its lower edge meets it to where its upper edge does, and nothing about a depth has to be assumed. Both ends are taken as read, without a margin: a margin would widen the surface on every side, and the frames that read an edge short and those that read it long settle it between them. Returns: Scan: The same scan with ``lo``, ``hi`` and ``contact`` set. Example: >>> import numpy as np >>> scan = Scan(0, np.arange(4), np.full(4, -16.7), np.full(4, -5.0), 1.0, 2.0) >>> scan = set_range_bands(scan) >>> round(scan.contact, 1), bool(scan.lo[0] < 8.0 < scan.hi[0]) (8.0, True) """ n = len(scan.cols) with np.errstate(divide='ignore', invalid='ignore'): near = np.where( scan.bottom < -MIN_DEPRESSION_DEG, camera_height_m / np.tan(np.radians(-scan.bottom)), np.nan, ) over = np.where( scan.top < -MIN_DEPRESSION_DEG, camera_height_m / np.tan(np.radians(-scan.top)), np.inf, ) near[near > 1.5 * max_range_m] = np.nan seen = np.isfinite(near) scan.lo = np.full(n, np.nan) scan.hi = np.full(n, np.nan) scan.contact = float(np.percentile(near[seen], 25)) if seen.any() else math.nan if not seen.any(): return scan d = math.radians(elevation_sigma_deg) if flat: far = np.minimum(over, 1.5 * max_range_m) with np.errstate(invalid='ignore'): lo = np.maximum(min_range_m, near) hi = np.maximum(far, lo + 0.5) scan.lo = np.where(seen, lo, np.nan) scan.hi = np.where(seen, hi, np.nan) return scan sigma = np.hypot(near * near * d / camera_height_m, range_sigma_fraction * near) with np.errstate(invalid='ignore'): jump = np.abs(np.diff(near)) smooth = jump <= np.maximum(1.5, 0.15 * np.minimum(near[1:], near[:-1])) face = np.concatenate([[0], np.cumsum(~smooth)]) angle = np.radians((np.arange(n) + 0.5) * BIN_DEG) step = np.hypot(np.diff(near * np.sin(angle)), np.diff(near * np.cos(angle))) step = np.where(smooth, np.nan_to_num(step), 0.0) n_faces = int(face[-1]) + 1 length = np.bincount(face[1:], weights=step, minlength=n_faces) breadth = np.bincount( face, weights=np.where(seen, near * math.radians(BIN_DEG), 0.0), minlength=n_faces, ) depth = np.maximum(1.0, depth_factor * np.maximum(length, breadth)[face]) with np.errstate(invalid='ignore'): sigma_over = np.hypot( over * over * d / camera_height_m, range_sigma_fraction * over ) lo = np.maximum(min_range_m, near - 2.0 * sigma - 0.3) hi = np.minimum(near + 2.0 * sigma + depth, over + 2.0 * sigma_over) hi = np.maximum(hi, lo + 0.5) scan.lo = np.where(seen, lo, np.nan) scan.hi = np.where(seen, hi, np.nan) return scan
# --------------------------------------------------------------- fusion def _columns( frame: _Frame, max_range_m: float, layers: int = 3 ) -> tuple[np.ndarray, np.ndarray, np.ndarray]: """A frame's occupied bands and the range each bearing column is free to.""" lo = np.full((layers, N_BINS), np.inf, np.float32) hi = np.zeros((layers, N_BINS), np.float32) count = np.zeros(N_BINS, int) blind = np.zeros(N_BINS, bool) ordered = sorted( frame.scans, key=lambda s: s.contact if math.isfinite(s.contact) else math.inf ) for scan in ordered: assert scan.lo is not None and scan.hi is not None # range_bands seen = np.isfinite(scan.lo) blind[scan.cols[~seen]] = True layer = count[scan.cols] ok = seen & (layer < layers) lo[layer[ok], scan.cols[ok]] = scan.lo[ok] hi[layer[ok], scan.cols[ok]] = scan.hi[ok] count[scan.cols[ok]] += 1 has = count > 0 # Free up to the nearest object in the column, or as far as the frame # sees when the column shows none. Columns outside a perspective frame, # or covered only by an outline without a ground contact, say nothing. free_to = np.where(has, lo.min(axis=0), max_range_m).astype(np.float32) free_to[blind & ~has] = 0.0 if frame.fov is not None: center, width = frame.fov b = (np.arange(N_BINS) + 0.5) * BIN_DEG outside = np.abs((b - center + 180.0) % 360.0 - 180.0) > width / 2.0 free_to[outside & ~has] = 0.0 return lo, hi, free_to def _window( grid: _Grid, frame: _Frame, max_range_m: float ) -> tuple[int, int, int, int] | None: """Rows and columns of the grid within a frame's range, or ``None``.""" c = grid.cell i0 = max(0, int((frame.x - max_range_m - grid.x0) / c)) i1 = min(grid.nx, int((frame.x + max_range_m - grid.x0) / c) + 1) j0 = max(0, int((frame.y - max_range_m - grid.y0) / c)) j1 = min(grid.ny, int((frame.y + max_range_m - grid.y0) / c) + 1) if i0 >= i1 or j0 >= j1: return None return j0, j1, i0, i1 def _polar( grid: _Grid, frame: _Frame, jj: np.ndarray, ii: np.ndarray ) -> tuple[np.ndarray, np.ndarray]: """Range and bearing column of cells (rows ``jj``, columns ``ii``) from a frame.""" gx = grid.x0 + (ii + 0.5) * grid.cell - frame.x gy = grid.y0 + (jj + 0.5) * grid.cell - frame.y r = np.hypot(gx, gy).astype(np.float32) b = np.floor(np.degrees(np.arctan2(gx, gy)) / BIN_DEG).astype(int) % N_BINS return r, b def _in_bands( r: np.ndarray, b: np.ndarray, lo: np.ndarray, hi: np.ndarray, min_range_m: float, max_range_m: float, ) -> np.ndarray: """Cells that lie in one of the frame's occupied bands.""" occupied = np.zeros(r.shape, bool) for k in range(len(lo)): occupied |= (r >= lo[k][b]) & (r <= hi[k][b]) return occupied & (r >= min_range_m) & (r <= max_range_m) def _vote_seen( grid: _Grid, frame: _Frame, min_range_m: float, max_range_m: float ) -> None: """Add a frame's occupied votes and note the direction each cell was seen from.""" window = _window(grid, frame, max_range_m) if window is None or not frame.scans: return j0, j1, i0, i1 = window lo, hi, _ = _columns(frame, max_range_m) r, b = _polar(grid, frame, np.arange(j0, j1)[:, None], np.arange(i0, i1)[None, :]) jj, ii = np.nonzero(_in_bands(r, b, lo, hi, min_range_m, max_range_m)) if not len(jj): return r, b = r[jj, ii], b[jj, ii] jj, ii = jj + j0, ii + i0 grid.occ[jj, ii] += 1.0 / (1.0 + (r / WEIGHT_RANGE_M) ** 2) grid.views[jj, ii] += 1 grid.seen[jj, ii] |= np.left_shift(1, b * N_SECTORS // N_BINS).astype(np.uint16) def _vote_empty( grid: _Grid, frame: _Frame, cells: np.ndarray, min_range_m: float, max_range_m: float, clear_from_m: float = 0.0, ) -> None: """ Add a frame's free votes on the cells some source says are occupied. Free votes only ever matter on those cells (``cells``), so the rest of the grid is left alone. Cells nearer than ``clear_from_m`` get none: the frame was not searched that close to the camera. """ window = _window(grid, frame, max_range_m) if window is None: return j0, j1, i0, i1 = window jj, ii = np.nonzero(cells[j0:j1, i0:i1]) if not len(jj): return jj, ii = jj + j0, ii + i0 r, b = _polar(grid, frame, jj, ii) lo, hi, free_to = _columns(frame, max_range_m) free = ( (r < free_to[b]) & (r >= max(min_range_m, clear_from_m)) & (r <= max_range_m) & ~_in_bands(r, b, lo, hi, min_range_m, max_range_m) ) weight = 1.0 / (1.0 + (r / WEIGHT_RANGE_M) ** 2) # The survey vehicle itself stood here: nothing static can. grid.free[jj, ii] += weight * free + 5.0 * (r < min_range_m) def _strongly_seen(grid: _Grid, strong_views: int, min_weight: float) -> np.ndarray: """ Cells of objects the vote turned down but many frames agree on. A frame that shows nothing where others outlined an object is a vote against it, and for a class the detector outlines in nearly every frame (vehicles) that is what tells a parked car from a passing one. It is weaker evidence than it looks for anything else: a hydrant behind a bush is seen from one side only, a car in a carport is hidden from half the street, and a detector may skip a hydrant in plain view for a whole sequence. Where ``strong_views`` or more frames outlined the same cells from :data:`MIN_SEEN_SECTORS` or more directions, their lines of sight cross there and fix the place without anyone's silence, so the object is kept. Of each group of such cells, those are taken that at least :data:`_CORE_FRACTION` as many frames outlined as its best cell. Where they touch cells the vote accepted they are one object with them (the vote may accept a few cells of a hydrant, too few to pass for one). """ strong = (grid.views >= strong_views) & (grid.occ >= min_weight) jj, ii = np.nonzero(strong) if not len(jj): return strong bits = grid.seen[jj, ii] sectors = np.zeros(len(bits), np.uint8) for k in range(N_SECTORS): sectors += ((bits >> k) & 1).astype(np.uint8) strong[jj, ii] = sectors >= MIN_SEEN_SECTORS labels, n = ndimage.label(strong, structure=np.ones((3, 3))) if not n: return strong peak = np.zeros(n + 1) peak[1:] = ndimage.maximum(grid.views, labels, index=np.arange(1, n + 1)) return strong & (grid.views >= _CORE_FRACTION * peak[labels]) def _band_cells(grid: _Grid, frame: _Frame, scan: Scan) -> np.ndarray: """Flat indices of the grid cells inside a scan's occupied bands.""" assert scan.lo is not None and scan.hi is not None # range_bands seen = np.isfinite(scan.lo) if not seen.any(): return np.zeros(0, int) lo, hi, cols = scan.lo[seen], scan.hi[seen], scan.cols[seen] n = max(2, int(math.ceil(float(np.max(hi - lo)) / (0.7 * grid.cell))) + 1) r = lo[:, None] + (hi - lo)[:, None] * np.linspace(0.0, 1.0, n)[None, :] found = [] for offset in (0.25, 0.75): # two rays per column so no cell is stepped over a = np.radians((cols[:, None] + offset) * BIN_DEG) i = np.floor((frame.x + r * np.sin(a) - grid.x0) / grid.cell).astype(int) j = np.floor((frame.y + r * np.cos(a) - grid.y0) / grid.cell).astype(int) ok = (i >= 0) & (i < grid.nx) & (j >= 0) & (j < grid.ny) found.append(j[ok] * grid.nx + i[ok]) return np.unique(np.concatenate(found)) def _aerial_seeds(grid: _Grid, cells: np.ndarray) -> list[np.ndarray]: """ The overhead outlines that lie on a blob, as positions in ``cells``. An outline counts when at least half of its cells are in the blob. """ if grid.aerial_id is None or grid.aerial_cells is None: return [] ids = grid.aerial_id.ravel()[cells] seeds = [] for outline in np.unique(ids[ids > 0]): inside = np.flatnonzero(ids == outline) if len(inside) >= _AERIAL_SHARE * grid.aerial_cells[outline]: seeds.append(inside) return seeds def _split_instances( grid: _Grid, frames: dict[str, _Frame], cells: np.ndarray, members: list[tuple[str, Scan, np.ndarray]], ) -> tuple[list[tuple[np.ndarray, list[tuple[str, Scan, np.ndarray]]]], bool]: """ Split a blob where frames keep seeing several outlines on it. The number of objects is the weighted median, over the frames that see the blob, of how many outlines each puts on it (close frames count most). The closest frame showing exactly that many seeds the parts; every other such frame adds its outlines to the parts they overlap most, one outline per part, and each cell goes to the part with most votes. When an overhead image puts at least as many separate outlines on the blob (and at least two), those outlines seed the parts instead: seen from above, two cars door to door do not hide each other. A part the overhead image shows is kept even if no street sighting falls on it. Returns the parts with their sightings, and whether the overhead outlines made the split (the street bearings then aim at the joint outline, not at any one part). """ xs, ys = grid.xy(cells) cx, cy = float(xs.mean()), float(ys.mean()) per_frame: dict[str, list[tuple[str, Scan, np.ndarray]]] = defaultdict(list) for member in members: per_frame[member[0]].append(member) ranges = { iid: math.hypot(frames[iid].x - cx, frames[iid].y - cy) for iid in per_frame } weights = {iid: 1.0 / (1.0 + (ranges[iid] / WEIGHT_RANGE_M) ** 2) for iid in ranges} k = 0 if per_frame: counts = np.array([len(v) for v in per_frame.values()]) w = np.array([weights[iid] for iid in per_frame]) order = np.argsort(counts) cum = np.cumsum(w[order]) k = int(counts[order][np.searchsorted(cum, 0.5 * cum[-1])]) seeds = _aerial_seeds(grid, cells) position = {int(c): n for n, c in enumerate(cells)} if len(seeds) >= 2 and len(seeds) >= k: k = len(seeds) part = np.full(len(cells), -1) for label, seed in enumerate(seeds): part[seed] = label unlabeled = part < 0 elif k >= 2: votes = np.zeros((k, len(cells)), np.float32) exact = sorted( (iid for iid, v in per_frame.items() if len(v) == k), key=lambda iid: ranges[iid], ) for n_frame, iid in enumerate(exact): sets = [ np.fromiter((position[int(c)] for c in m[2]), int, len(m[2])) for m in per_frame[iid] ] if n_frame == 0: labels = list(range(k)) else: affinity = np.array( [ [votes[p][s].sum() / max(1, len(s)) for p in range(k)] for s in sets ] ) labels = [-1] * k for _ in range(k): a, b = np.unravel_index(int(np.argmax(affinity)), affinity.shape) labels[a] = int(b) affinity[a, :] = -1.0 affinity[:, b] = -1.0 owners = np.zeros(len(cells), int) for s in sets: owners[s] += 1 for s, label in zip(sets, labels, strict=True): votes[label][s[owners[s] == 1]] += weights[iid] part = votes.argmax(axis=0) unlabeled = votes.max(axis=0) <= 0 seeds = [] else: return [(cells, members)], False if unlabeled.all(): return [(cells, members)], False if unlabeled.any(): pts = np.c_[xs, ys] _, nearest = cKDTree(pts[~unlabeled]).query(pts[unlabeled]) part[unlabeled] = part[~unlabeled][nearest] assigned: dict[int, list[tuple[str, Scan, np.ndarray]]] = defaultdict(list) for iid, scan, claimed in members: s = np.fromiter((position[int(c)] for c in claimed), int, len(claimed)) inside = np.bincount(part[s], minlength=k) label = int(inside.argmax()) assigned[label].append((iid, scan, claimed[part[s] == label])) out = [] for label in range(k): sel = cells[part == label] if len(sel) and (assigned[label] or seeds): out.append((sel, assigned[label])) if not out: return [(cells, members)], False return out, bool(seeds) and len(out) > 1 def _intersect( cams: np.ndarray, bearings_deg: np.ndarray, start: np.ndarray, sigma_deg: float ) -> tuple[np.ndarray, np.ndarray | None, float, float | None]: """ Robust least-squares intersection of bearings; falls back to ``start``. Returns the position, its covariance (``None`` without enough parallax), the parallax in degrees and the root-mean-square distance in meters between the position and the bearing lines. """ az = np.radians(bearings_deg) spread = az[:, None] - az[None, :] parallax = ( float(np.degrees(np.abs(np.arctan2(np.sin(spread), np.cos(spread))).max())) if len(az) > 1 else 0.0 ) if parallax < MIN_PARALLAX_DEG: return start, None, parallax, None normal = np.c_[np.cos(az), -np.sin(az)] offset = (normal * cams).sum(axis=1) p = np.asarray(start, float) w = np.ones(len(az)) a = np.zeros((2, 2)) for _ in range(8): sigma = np.maximum(1.0, np.hypot(*(p - cams).T)) * math.radians(sigma_deg) ww = w / sigma**2 a = (normal * ww[:, None]).T @ normal try: q = np.linalg.solve(a, (normal * ww[:, None]).T @ offset) except np.linalg.LinAlgError: return start, None, parallax, None residual = np.abs(((q - cams) * normal).sum(axis=1)) / sigma w = np.where(residual < 2.5, 1.0, 2.5 / np.maximum(residual, 1e-9)) p = q try: cov = np.linalg.inv(a) except np.linalg.LinAlgError: return start, None, parallax, None rms = float(np.sqrt(np.mean(((p - cams) * normal).sum(axis=1) ** 2))) return p, cov, parallax, rms def _tangent_ellipse( cams: np.ndarray, left_deg: np.ndarray, right_deg: np.ndarray, start: np.ndarray, sigma_deg: float, ) -> np.ndarray | None: """ Center of the ellipse the outlines' left and right edges are tangent to. The middle of an outline points at the middle of what the frame sees of an object, not at the object's center: from beside a parked car the near end fills more of the view than the far end, and the center bearings of the frames before and behind it cross behind the car. The two edges of an outline are tangents of the object instead, wherever the frame stands, and an ellipse touching all of them sits on the object. With the center ``m`` and the shape ``S`` of the ellipse, a line with unit normal ``n`` at distance ``d`` from the origin is a tangent when ``(d - n.m)^2 = n'Sn``, which is linear in ``m`` and ``mm' - S``. Returns ``None`` when the edges do not close an ellipse (too few views, all from one side, an object narrower than the bearing noise). """ fitted = _ellipse_fit(cams, left_deg, right_deg, start, sigma_deg) return None if fitted is None else fitted[0] def _ellipse_fit( cams: np.ndarray, left_deg: np.ndarray, right_deg: np.ndarray, start: np.ndarray, sigma_deg: float, ) -> tuple[np.ndarray, np.ndarray] | None: """Center and shape matrix of :func:`_tangent_ellipse`, or ``None``.""" if len(cams) < 4: return None rel = np.r_[cams, cams] - start az = np.radians(np.r_[left_deg, right_deg]) n = np.c_[np.cos(az), -np.sin(az)] d = (n * rel).sum(axis=1) system = np.c_[ n[:, 0] ** 2, 2.0 * n[:, 0] * n[:, 1], n[:, 1] ** 2, -2.0 * d * n[:, 0], -2.0 * d * n[:, 1], ] rhs = -(d**2) line_sigma = np.maximum(1.0, np.hypot(*rel.T)) * math.radians(sigma_deg) w = np.ones(len(d)) half = 1.0 m = np.zeros(2) shape = np.eye(2) for _ in range(8): # A residual is about twice the ellipse's half-width times the # distance between the line and the tangent it should be. scale = 2.0 * half * line_sigma ww = w / scale try: solution = np.linalg.lstsq(system * ww[:, None], rhs * ww, rcond=None)[0] except np.linalg.LinAlgError: return None m = solution[3:] shape = np.outer(m, m) - np.array( [[solution[0], solution[1]], [solution[1], solution[2]]] ) half = max(0.3, math.sqrt(max(1e-6, float(np.trace(shape)) / 2.0))) residual = np.abs(system @ solution - rhs) / (2.0 * half * line_sigma) w = np.where(residual < 2.5, 1.0, 2.5 / np.maximum(residual, 1e-9)) low, high = np.linalg.eigvalsh(shape) if not (low > 0.05**2 and high < 8.0**2): return None return np.asarray(start, float) + m, shape def _tangent_box( cams: np.ndarray, left_deg: np.ndarray, right_deg: np.ndarray, start: np.ndarray, sigma_deg: float, ) -> tuple[np.ndarray, float, float, float] | None: """ The box an object's sightings fit in: center, heading and half sides. The cells of a blob say where an object is, not how large: range bands are generous, and the cells most frames agree on reach half a meter past a parked car at each end and more than that across it. The edges of the outlines measure the object itself. Each is a line the object touches from one side, so with the center ``m``, the long axis ``e1`` and the half sides ``a`` and ``b``, a line with unit normal ``n`` toward the object, passing through the camera ``c``, satisfies ``n.(m - c) = (|a n.e1|^q + |b n.e2|^q)^(1/q)``: the right-hand side is how far the shape reaches against ``n`` (``q`` is :data:`_CORNER_POWER`). The five unknowns are fitted to all edges at once, starting from the ellipse of :func:`_tangent_ellipse`, with outlines cut short by something in front weighted down. Returns: tuple | None: The center, the heading of the long side in degrees clockwise from north (0 to 180), half the length and half the width; ``None`` when the edges do not close a shape. """ fitted = _ellipse_fit(cams, left_deg, right_deg, start, sigma_deg) if fitted is None: return None center, shape = fitted values, vectors = np.linalg.eigh(shape) left, right = np.radians(left_deg), np.radians(right_deg) # Unit normals of the edge lines, pointing at the object. n = np.r_[np.c_[np.cos(left), -np.sin(left)], np.c_[-np.cos(right), np.sin(right)]] c = np.r_[cams, cams] sigma = np.maximum(1.0, np.hypot(*(c - center).T)) * math.radians(sigma_deg) q = _CORNER_POWER def residual(v: np.ndarray) -> np.ndarray: e1 = np.array([math.cos(v[2]), math.sin(v[2])]) e2 = np.array([-e1[1], e1[0]]) reach = (np.abs(v[3] * (n @ e1)) ** q + np.abs(v[4] * (n @ e2)) ** q) ** (1 / q) return (((v[:2] - c) * n).sum(axis=1) - reach) / sigma angle = math.atan2(vectors[1, 1], vectors[0, 1]) sides = [math.sqrt(values[1]), math.sqrt(values[0])] best = None for turn in ( 0.0, math.pi / 4.0, ): # the ellipse of a near-square shape may lie askew try: fit = least_squares( residual, [*center, angle + turn, *sides], loss='soft_l1', f_scale=1.5 ) except ValueError: continue if best is None or fit.cost < best.cost: best = fit if best is None: return None a, b, theta = abs(best.x[3]), abs(best.x[4]), float(best.x[2]) if b > a: a, b, theta = b, a, theta + math.pi / 2.0 if not (0.05 < b and a < 8.0): return None heading = (90.0 - math.degrees(theta)) % 180.0 return best.x[:2].copy(), float(heading), float(a), float(b) def _box_outline( center: np.ndarray, heading_deg: float, half_length: float, half_width: float ) -> list[tuple[float, float]]: """Corners of a box given by its center, heading and half sides.""" t = math.radians(heading_deg) e1 = np.array([math.sin(t), math.cos(t)]) e2 = np.array([e1[1], -e1[0]]) return [ (float(q[0]), float(q[1])) for q in ( center + sx * half_length * e1 + sy * half_width * e2 for sx, sy in ((1, 1), (1, -1), (-1, -1), (-1, 1)) ) ] def _hull_cells( grid: _Grid, frames: dict[str, _Frame], cells: np.ndarray, members: list[tuple[str, Scan, np.ndarray]], agreement: float, ) -> np.ndarray: """Cells of a blob that lie inside the outlines of most of its sightings.""" xs, ys = grid.xy(cells) inside = np.zeros(len(cells), np.float32) total = 0.0 for iid, scan, _ in members: frame = frames[iid] dx, dy = xs - frame.x, ys - frame.y b = np.floor(np.degrees(np.arctan2(dx, dy)) / BIN_DEG).astype(int) % N_BINS covered = np.zeros(N_BINS, bool) covered[scan.cols] = True covered[(scan.cols + 1) % N_BINS] = True covered[(scan.cols - 1) % N_BINS] = True weight = 1.0 / (1.0 + (float(np.hypot(dx, dy).mean()) / WEIGHT_RANGE_M) ** 2) inside += weight * covered[b] total += weight keep = inside >= agreement * total if keep.sum() < max(4, 0.2 * len(cells)): return cells # Range bands are generous in depth, so the blob reaches behind and in # front of the object where fewer frames vote. The object itself is where # nearly every frame's band overlaps: the cells with most of the peak # occupied weight. weight = grid.occ.ravel()[cells] core = keep & (weight >= _CORE_FRACTION * np.percentile(weight[keep], 95)) if core.sum() >= max(4, 0.1 * len(cells)): keep = core return cells[keep] def _footprint( grid: _Grid, cells: np.ndarray, convex: bool = True ) -> tuple[list[tuple[float, float]], float, float, float]: """ Outline of a set of cells with its area and side lengths. Convex by default. Otherwise the outline follows the cells themselves (gaps a cell wide closed, holes filled, the largest piece kept, steps of the grid smoothed away), which keeps the bend of a driveway or the notch a planter cuts into it. """ if not convex: shaped = _cell_outline(grid, cells) if shaped is not None: return shaped xs, ys = grid.xy(cells) half = grid.cell / 2.0 corners = np.concatenate( [np.c_[xs + sx * half, ys + sy * half] for sx in (-1, 1) for sy in (-1, 1)] ) hull = MultiPoint(corners).convex_hull if not isinstance(hull, Polygon): hull = hull.buffer(half) rect = np.asarray(hull.minimum_rotated_rectangle.exterior.coords)[:4] a = float(np.hypot(*(rect[1] - rect[0]))) b = float(np.hypot(*(rect[2] - rect[1]))) outline = [(float(x), float(y)) for x, y in hull.exterior.coords[:-1]] return outline, float(hull.area), max(a, b), min(a, b) def _cell_outline( grid: _Grid, cells: np.ndarray ) -> tuple[list[tuple[float, float]], float, float, float] | None: """The outline that follows a set of cells, or ``None`` if they give none.""" jj, ii = np.divmod(cells, grid.nx) j0, i0 = int(jj.min()) - 2, int(ii.min()) - 2 mask = np.zeros((int(jj.max()) - j0 + 3, int(ii.max()) - i0 + 3), bool) mask[jj - j0, ii - i0] = True mask = ndimage.binary_fill_holes(ndimage.binary_closing(mask, np.ones((3, 3)))) labels, n = ndimage.label(mask) if not n: return None if n > 1: mask = labels == 1 + int(np.argmax(ndimage.sum(mask, labels, range(1, n + 1)))) rows, cols = np.nonzero(mask) c = grid.cell squares = [ Polygon( [ (grid.x0 + (i + i0) * c, grid.y0 + (j + j0) * c), (grid.x0 + (i + i0 + 1) * c, grid.y0 + (j + j0) * c), (grid.x0 + (i + i0 + 1) * c, grid.y0 + (j + j0 + 1) * c), (grid.x0 + (i + i0) * c, grid.y0 + (j + j0 + 1) * c), ] ) for j, i in zip(rows, cols, strict=True) ] shape = unary_union(squares).simplify(0.75 * c) if isinstance(shape, MultiPolygon): shape = max(shape.geoms, key=lambda g: g.area) if not isinstance(shape, Polygon) or shape.is_empty: return None rect = np.asarray(shape.minimum_rotated_rectangle.exterior.coords)[:4] a = float(np.hypot(*(rect[1] - rect[0]))) b = float(np.hypot(*(rect[2] - rect[1]))) outline = [(float(x), float(y)) for x, y in shape.exterior.coords[:-1]] return outline, float(shape.area), max(a, b), min(a, b) def _extract( grid: _Grid, frames: dict[str, _Frame], observations: Sequence[Observation], core: tuple[float, float, float, float] | None, *, max_range_m: float, occupancy_threshold: float, min_views: int, min_weight: float, min_object_width_m: float, split_instances: bool, hull_agreement: float, bearing_sigma_deg: float, min_parallax_deg: float, counts: dict[str, int], day: str | None, strong_views: int = 0, on_ground: bool = False, ) -> list[FusedObject]: """Blobs of occupied cells, split into instances and described.""" total = grid.occ + grid.free with np.errstate(invalid='ignore', divide='ignore'): score = np.where(total > 0, grid.occ / total, 0.0) street = (grid.views >= min_views) & (grid.occ >= min_weight) mask = (score >= occupancy_threshold) & street aerial = grid.aerial_lo is not None and grid.aerial_id is not None if aerial: assert grid.aerial_lo is not None and grid.aerial_id is not None hit = grid.aerial_id > 0 said = grid.aerial_lo != 0.0 # Where the overhead image says something, it and the street frames # add up as independent log-odds. A cell the image shows needs no # street views; elsewhere the street frames decide as before. share = (grid.occ + _STREET_PRIOR) / (total + 2.0 * _STREET_PRIOR) combined = np.log(share / (1.0 - share)) + grid.aerial_lo cut = min(max(occupancy_threshold, 1e-6), 1.0 - 1e-6) decided = (combined >= math.log(cut / (1.0 - cut))) & (street | hit) mask = np.where(said, decided, mask) strong = ( _strongly_seen(grid, strong_views, min_weight) if strong_views else np.zeros(mask.shape, bool) ) if aerial and strong.any(): # Where the overhead image could see and shows nothing, it has had # its say in the vote above: the street frames do not overrule it. strong &= ~(said & ~hit) gaps = np.zeros(mask.shape, bool) if on_ground: # What stands on a surface cuts it into patches; the strip under it # is part of the surface. r = int(round(0.5 * _GROUND_GAP_M / grid.cell)) if r > 0: yy, xx = np.ogrid[-r : r + 1, -r : r + 1] disk = xx * xx + yy * yy <= r * r gaps = ndimage.binary_closing(mask, structure=disk) & ~mask labels, n = ndimage.label(mask | strong | gaps, structure=np.ones((3, 3))) if not n: return [] counts['blobs'] += n # Objects that owe their place to the agreement of their sightings alone: strong_labels = set(np.unique(labels[strong]).tolist()) - set( np.unique(labels[mask]).tolist() ) flat = labels.ravel() slices = ndimage.find_objects(labels) def cells_of_label(label: int) -> np.ndarray: """Flat indices of a blob's cells, in ascending order.""" sl = slices[label - 1] assert sl is not None jj, ii = np.nonzero(labels[sl] == label) return (jj + sl[0].start) * grid.nx + (ii + sl[1].start) ids = list(frames) tree = cKDTree(np.array([[frames[i].x, frames[i].y] for i in ids])) cells_of: dict[tuple[str, int], np.ndarray] = {} claims: dict[tuple[str, int], tuple[int, int]] = {} # scan -> (label, cells) for label, sl in enumerate(slices, start=1): if sl is None: continue j0, j1, i0, i1 = sl[0].start, sl[0].stop, sl[1].start, sl[1].stop bx = grid.x0 + (i0 + i1) / 2.0 * grid.cell by = grid.y0 + (j0 + j1) / 2.0 * grid.cell radius = 0.5 * math.hypot(i1 - i0, j1 - j0) * grid.cell if core is not None and not ( core[0] - radius <= bx < core[2] + radius and core[1] - radius <= by < core[3] + radius ): continue for n_frame in tree.query_ball_point([bx, by], max_range_m + radius): frame = frames[ids[n_frame]] dist = math.hypot(bx - frame.x, by - frame.y) bearing = math.degrees(math.atan2(bx - frame.x, by - frame.y)) half = ( math.degrees(math.asin(min(1.0, radius / dist))) if dist > radius else 180.0 ) for n_scan, scan in enumerate(frame.scans): if not math.isfinite(scan.contact): continue off = abs((scan.center - bearing + 180.0) % 360.0 - 180.0) if off > scan.width / 2.0 + half + 1.0: continue key = (frame.image_id, n_scan) cells = cells_of.get(key) if cells is None: cells = cells_of[key] = _band_cells(grid, frame, scan) inside = int(np.count_nonzero(flat[cells] == label)) if inside >= 3 and inside > claims.get(key, (0, 0))[1]: claims[key] = (label, inside) members_of: dict[int, list[tuple[str, Scan, np.ndarray]]] = defaultdict(list) for (iid, n_scan), (label, _) in claims.items(): cells = cells_of[(iid, n_scan)] members_of[label].append( (iid, frames[iid].scans[n_scan], cells[flat[cells] == label]) ) aerial_id = grid.aerial_id.ravel() if grid.aerial_id is not None else None if aerial_id is not None: # Blobs only the overhead image shows: no street sighting claims them. for label in np.unique(flat[(aerial_id > 0) & (flat > 0)]): members_of.setdefault(int(label), []) # Fewest overhead cells for an outline to stand for the object. min_aerial_cells = max(1.0, 0.25 * (min_object_width_m / grid.cell) ** 2) objects: list[FusedObject] = [] for label, members in members_of.items(): cells = cells_of_label(label) parts, by_aerial = ( _split_instances(grid, frames, cells, members) if split_instances else ([(cells, members)], False) ) counts['split'] += len(parts) - 1 for part_cells, part_members in parts: above = ( part_cells[aerial_id[part_cells] > 0] if aerial_id is not None else part_cells[:0] ) if len(above) >= min_aerial_cells: outline, area, length, width = _footprint(grid, above) if length < min_object_width_m: above = above[:0] # a speck: the street frames decide else: above = above[:0] seen_above = len(above) > 0 if not seen_above and len({iid for iid, _, _ in part_members}) < min_views: counts['few_views'] += 1 continue if seen_above: # Seen from above, the outline is the footprint. hull = above xs, ys = grid.xy(hull) center = np.array([xs.mean(), ys.mean()]) else: if on_ground: # Past the far end of a surface a few frames still vote # "occupied" (each end is known to within an error, and # nothing looks behind it to say otherwise): its cells # are those most of its frames outline, and the strips # closed between them. seen = grid.views.ravel()[part_cells] closed = gaps.ravel()[part_cells] enough = ( _GROUND_VIEWS * np.percentile(seen[~closed], 95) if not closed.all() else 0.0 ) hull = part_cells[closed | (seen >= enough)] else: hull = _hull_cells( grid, frames, part_cells, part_members, hull_agreement ) outline, area, length, width = _footprint(grid, hull, not on_ground) if length < min_object_width_m: counts['fragment'] += 1 continue xs, ys = grid.xy(hull) w = grid.occ.ravel()[hull] center = np.array( [np.average(xs, weights=w), np.average(ys, weights=w)] ) if core is not None and not ( core[0] <= center[0] < core[2] and core[1] <= center[1] < core[3] ): continue p, cov, parallax, rms = center, None, 0.0, None box = None cams = np.array([[frames[i].x, frames[i].y] for i, _, _ in part_members]) if part_members: bearings = np.array([s.center for _, s, _ in part_members]) p, cov, parallax, rms = _intersect( cams, bearings, center, bearing_sigma_deg ) if cov is not None and parallax >= _ELLIPSE_PARALLAX_DEG: spread = np.array([s.width for _, s, _ in part_members]) / 2.0 fitted = _tangent_ellipse( cams, bearings - spread, bearings + spread, p, bearing_sigma_deg, ) if fitted is not None and math.hypot(*(fitted - p)) <= max( length, 2.0 ): p = fitted counts['by_edges'] += 1 if split_instances and not seen_above: box = _tangent_box( cams, bearings - spread, bearings + spread, p, bearing_sigma_deg, ) if label in strong_labels and parallax < _STRONG_PARALLAX_DEG: counts['no_parallax'] += 1 continue if parallax < min_parallax_deg: if not seen_above: # Seen along one line only (a vehicle driving ahead of # the survey car where a sequence ends): nothing fixes # its range. counts['no_parallax'] += 1 continue p, cov, rms = center, None, None # the image fixes it if cov is not None and math.hypot(*(p - center)) > max(length, 2.0): p, cov, rms = center, None, None # bearings disagree with the blob heading = None if ( box is not None and cov is not None and math.hypot(*(box[0] - p)) <= max(0.5 * width, 0.5) and 2.0 * box[2] <= 1.5 * length + 1.0 ): # The edges of the sightings measure the object; the cells # most frames agree on reach past it (see _tangent_box). p, heading = box[0], box[1] outline = _box_outline(*box) area = 4.0 * box[2] * box[3] length, width = 2.0 * box[2], 2.0 * box[3] counts['boxed'] += 1 offset = ( round(float(math.hypot(*(p - center))), 2) if seen_above and cov is not None else None ) if offset is not None and ( by_aerial or not Polygon(outline).contains(Point(*p)) ): # The street frames saw this object and a neighbor as one, so # their bearings aim between the two: place it from above. p, cov, rms = center, None, None best_share = float(score.ravel()[hull].max()) if part_members else None if label in strong_labels: counts['strongly_seen'] += 1 sources = None if aerial: sources = ( ('both' if part_members else 'aerial') if seen_above else 'street' ) sightings = [] for (_, scan, _), cam in zip(part_members, cams, strict=True): obs = observations[scan.index] obs.bearing = round(scan.center, 2) obs.elevation = round(float(scan.bottom.min()), 2) obs.range_m = round(float(math.hypot(*(p - cam))), 2) sightings.append(obs) objects.append( FusedObject( x=float(p[0]), y=float(p[1]), cov=cov, members=sightings, footprint=outline, area_m2=area, length_m=length, width_m=width, parallax_deg=parallax, days=[day] if day and part_members else [], localization=( 'triangulated' if cov is not None else ('aerial' if seen_above else 'fused') ), rms_m=rms, sources=sources, aerial_offset_m=offset, vote_share=best_share, heading_deg=heading, ) ) return objects def _merge_days(objects: list[FusedObject]) -> list[FusedObject]: """Join objects of different survey days that stand on the same spot.""" if len(objects) < 2: return objects polys = [Polygon(o.footprint) for o in objects] reach = max(o.length_m for o in objects) tree = cKDTree(np.array([[o.x, o.y] for o in objects])) parent = list(range(len(objects))) def find(a: int) -> int: while parent[a] != a: parent[a] = parent[parent[a]] a = parent[a] return a for a, b in sorted(tree.query_pairs(reach)): if set(objects[a].days) & set(objects[b].days): continue # seen apart on the same day: two objects if polys[a].contains(Point(objects[b].x, objects[b].y)) or polys[b].contains( Point(objects[a].x, objects[a].y) ): ra, rb = find(a), find(b) if ra != rb and not ( _group_days(objects, parent, ra) & _group_days(objects, parent, rb) ): parent[rb] = ra groups: dict[int, list[int]] = defaultdict(list) for i in range(len(objects)): groups[find(i)].append(i) merged = [] for members in groups.values(): best = min(members, key=lambda i: (objects[i].cov is None, objects[i].sigma_m)) keep = objects[best] for i in members: if i != best: keep.members.extend(objects[i].members) keep.days = sorted(set(keep.days) | set(objects[i].days)) kinds = {objects[i].sources for i in members} if 'both' in kinds or {'street', 'aerial'} <= kinds: keep.sources = 'both' shares = [v for i in members if (v := objects[i].vote_share) is not None] keep.vote_share = max(shares) if shares else None merged.append(keep) return merged def _group_days(objects: list[FusedObject], parent: list[int], root: int) -> set[str]: """Survey days of every object currently joined under ``root``.""" days: set[str] = set() for i, obj in enumerate(objects): j = i while parent[j] != j: j = parent[j] if j == root: days |= set(obj.days) return days def _typical_width( days: dict[str | None, dict[str, _Frame]], max_range_m: float ) -> float: """ Smallest footprint worth keeping, from the sightings' own sizes. The median width of the outlines at the range of their ground contact, kept between 0.2 and 1 m: 1 m for vehicles, about 0.3 m for hydrants. """ widths = [ 2.0 * scan.contact * math.tan(math.radians(min(scan.width, 170.0)) / 2.0) for day_frames in days.values() for frame in day_frames.values() for scan in frame.scans if math.isfinite(scan.contact) and scan.contact <= max_range_m ] if not widths: return 1.0 return float(min(1.0, max(0.2, round(float(np.median(widths)), 1))))
[docs] def fuse_observations( observations: Sequence[Observation], frames: Sequence[Any] | None = None, *, camera_height_m: float = 2.4, min_range_m: float = 2.0, max_range_m: float = 30.0, cell_m: float | None = None, occupancy_threshold: float = 0.6, min_views: int = 2, min_object_width_m: float | None = None, split_instances: bool = True, strong_views: int | None = None, elevation_sigma_deg: float = 0.75, range_sigma_fraction: float = 0.2, depth_factor: float = 0.5, hull_agreement: float = 0.75, bearing_sigma_deg: float = 0.75, min_parallax_deg: float = MIN_PARALLAX_DEG, tile_m: float = 300.0, project: Project | None = None, unproject: Unproject | None = None, aerial: AerialEvidence | None = None, clear_from_m: float | None = None, flat: bool = False, ) -> tuple[list[FusedObject], dict[str, int], Unproject]: """ Turn the sightings of one class into objects by occupancy fusion. See the module docstring for the method. Each survey day is fused by itself, so a car that left between two passes is not voted away by the later one; objects of different days that stand on the same spot are joined afterward. Args: observations: Sightings of one class. ``bearing``, ``elevation`` and ``range_m`` are filled in on those that end up in an object. frames: Every frame of the survey (objects with ``image_id``, ``lon``, ``lat``, ``compass_angle``, ``is_pano``, ``captured_at`` and ``horizontal_fov_deg``, such as :class:`~rapidtools.processing.street_tracking.CameraFrame`), including those without a sighting: they are the ones that say a stretch of curb is empty. The sightings' own frames are used when omitted. camera_height_m: Camera height above the ground. min_range_m: Closest range anything is placed at. max_range_m: Farthest range a frame votes at. cell_m: Size of a ground cell. ``None`` takes a quarter of ``min_object_width_m``, between 0.1 and 0.5 m: a quarter of a meter for vehicles, a tenth for hydrants and poles. occupancy_threshold: Share of the (range-weighted) votes on a cell that must say "occupied". min_views: Frames that must agree on a cell, and that an object must have been seen in. min_object_width_m: Objects whose footprint is shorter than this are dropped. ``None`` takes it from the sightings themselves: the typical width of an outline at the range of its ground contact, between 0.2 and 1 m (1 m for vehicles, 0.3 m for hydrants), so small classes need no setting of their own. split_instances: Split a blob that frames keep seeing as several outlines. Turn off for classes Mapillary segments as one surface (buildings, fences, vegetation). strong_views: Frames that, outlining the same cells from three or more directions, place an object there even when the vote turns it down because most frames in range show nothing (an object hidden from part of the street, or one the detector often misses). Such objects have a ``vote_share`` under ``occupancy_threshold``. ``0`` keeps only what the vote accepts. ``None`` uses 5 for classes whose outlines are typically under a meter wide (hydrants, poles) and 0 for the rest: the lines of sight to a narrow object cross at a point, while those to cars parked in a row cross in many places where there is nothing. elevation_sigma_deg: One-sigma error of an outline edge's elevation. range_sigma_fraction: One-sigma range error as a share of the range. depth_factor: Assumed depth of an object behind a visible face, as a share of the face's length. hull_agreement: Share of an object's sightings whose outline must cover a cell for it to count as footprint. bearing_sigma_deg: One-sigma bearing error, for the position uncertainty. min_parallax_deg: Objects whose sightings all look along one line (bearings spread less than this) are dropped; ``0`` keeps them at the center of their cells. tile_m: Side of the ground tiles the survey is processed in; bounds memory, not accuracy. project: Projection to local meters; one centered on the sightings is made when omitted. unproject: Inverse of ``project``. aerial: Detections of the same class in an overhead image (see :class:`~rapidtools.processing.aerial_evidence.AerialEvidence`). They are used around the street survey only: objects the image alone shows are kept within ``max_range_m`` of its frames, where no frame saw the spot empty. Objects then carry ``sources``. clear_from_m: Closest range at which a frame that shows nothing there counts as having seen the ground empty. For frames that were only searched from some distance out (tiles of a panorama's horizon band, see :mod:`~rapidtools.processing.street_tiles`); ``None`` means from ``min_range_m``. flat: The class lies on the ground (driveways, markings). Its outlines are then read as plans seen aslant (see :func:`set_range_bands`), and a footprint follows its cells instead of being their convex outline. Returns: tuple[list[FusedObject], dict[str, int], Unproject]: The objects, counters describing the run, and the inverse projection that turns their coordinates back into longitude and latitude. Example: >>> objects, counts, unproject = fuse_observations(sightings) # doctest: +SKIP >>> unproject(objects[0].x, objects[0].y) # doctest: +SKIP (-117.4885, 47.7165) """ counts: dict[str, int] = defaultdict(int) counts['sightings'] = len(observations) if project is None or unproject is None: if observations: lon0 = float(np.mean([o.camera_lon for o in observations])) lat0 = float(np.mean([o.camera_lat for o in observations])) else: lon0 = lat0 = 0.0 project, unproject = local_projection(lon0, lat0) if not observations: counts['objects'] = 0 return [], dict(counts), unproject days: dict[str | None, dict[str, _Frame]] = defaultdict(dict) for index, obs in enumerate(observations): scan = scan_from_observation(index, obs) if scan is None: counts['unusable'] += 1 continue set_range_bands( scan, camera_height_m, min_range_m, max_range_m, elevation_sigma_deg, range_sigma_fraction, depth_factor, flat, ) day = obs.captured_at[:10] if obs.captured_at else None frame = days[day].get(obs.image_id) if frame is None: x, y = project(obs.camera_lon, obs.camera_lat) fov = None if not obs.is_pano: params = (obs.extra or {}).get('camera_parameters') focal = float(params[0]) if params and params[0] else 0.85 fov = ( float(obs.compass_angle or 0.0), 2.0 * math.degrees(math.atan(0.5 / focal)), ) frame = days[day][obs.image_id] = _Frame(obs.image_id, x, y, fov=fov) frame.scans.append(scan) counts['scans'] += 1 typical = _typical_width(days, max_range_m) if min_object_width_m is None: min_object_width_m = typical if strong_views is None: strong_views = 5 if typical < 1.0 else 0 if cell_m is None: cell_m = min(0.5, max(0.1, min_object_width_m / 4.0)) counts['cell_mm'] = int(round(1000.0 * cell_m)) counts['min_width_mm'] = int(round(1000.0 * min_object_width_m)) for cam in frames or (): captured = getattr(cam, 'captured_at', None) day = captured[:10] if captured else None if day not in days or cam.image_id in days[day]: continue x, y = project(cam.lon, cam.lat) fov = None if not getattr(cam, 'is_pano', True): fov = (float(cam.compass_angle or 0.0), float(cam.horizontal_fov_deg)) days[day][cam.image_id] = _Frame(cam.image_id, x, y, fov=fov) local: LocalAerialEvidence | None = None if aerial is not None: local = aerial.to_local(project) counts['aerial_detections'] = len(local.detections) objects: list[FusedObject] = [] pad = max_range_m + 10.0 for day, day_frames in sorted(days.items(), key=lambda kv: kv[0] or ''): counts['frames'] += len(day_frames) xy = np.array([[f.x, f.y] for f in day_frames.values()]) ids = list(day_frames) tree = cKDTree(xy) x_min, y_min = xy.min(axis=0) x_max, y_max = xy.max(axis=0) nx = max(1, int(math.ceil((x_max - x_min + 1e-6) / tile_m))) ny = max(1, int(math.ceil((y_max - y_min + 1e-6) / tile_m))) for ty in range(ny): for tx in range(nx): core = ( x_min + tx * tile_m, y_min + ty * tile_m, x_min + (tx + 1) * tile_m, y_min + (ty + 1) * tile_m, ) # Objects stand up to max_range from a camera, so the edge # tiles own everything beyond the cameras on their side. core = ( -math.inf if tx == 0 else core[0], -math.inf if ty == 0 else core[1], math.inf if tx == nx - 1 else core[2], math.inf if ty == ny - 1 else core[3], ) gx0 = x_min + tx * tile_m - pad gy0 = y_min + ty * tile_m - pad span = tile_m + 2.0 * pad center = [gx0 + span / 2.0, gy0 + span / 2.0] near = tree.query_ball_point( center, span / math.sqrt(2.0) + max_range_m ) tile_frames = { ids[i]: day_frames[ids[i]] for i in near if gx0 - max_range_m <= xy[i, 0] <= gx0 + span + max_range_m and gy0 - max_range_m <= xy[i, 1] <= gy0 + span + max_range_m } if not any(f.scans for f in tile_frames.values()) and not ( local is not None and local.detections_in((gx0, gy0, gx0 + span, gy0 + span)) ): continue cells = int(math.ceil(span / cell_m)) grid = _Grid(gx0, gy0, cell_m, cells, cells) for frame in tile_frames.values(): _vote_seen(grid, frame, min_range_m, max_range_m) # Free votes matter only where something says "occupied". candidates = grid.views > 0 if local is not None: grid.set_aerial(*local.layers(gx0, gy0, cell_m, cells, cells)) assert grid.aerial_id is not None candidates |= grid.aerial_id > 0 for frame in tile_frames.values(): _vote_empty( grid, frame, candidates, min_range_m, max_range_m, clear_from_m or 0.0, ) objects.extend( _extract( grid, tile_frames, observations, core, max_range_m=max_range_m, occupancy_threshold=occupancy_threshold, min_views=min_views, min_weight=0.6, min_object_width_m=min_object_width_m, split_instances=split_instances, hull_agreement=hull_agreement, bearing_sigma_deg=bearing_sigma_deg, min_parallax_deg=min_parallax_deg, counts=counts, day=day, strong_views=strong_views, on_ground=flat, ) ) before = len(objects) objects = _merge_days(objects) for obj in objects: lon, lat = unproject(obj.x, obj.y) for obs in obj.members: obs.lon, obs.lat = lon, lat counts['merged_days'] = before - len(objects) counts['objects'] = len(objects) if aerial is not None: for obj in objects: counts[f'from_{obj.sources}'] += 1 return objects, dict(counts), unproject
def object_attributes(obj: FusedObject) -> dict[str, Any]: """ Attribute dictionary describing a fused object's quality and size. Example: >>> obj = FusedObject(0.0, 0.0, None, [], [(0, 0), (4, 0), (4, 2), (0, 2)], ... 8.0, 4.0, 2.0, 35.0) >>> object_attributes(obj)['footprint_area_m2'] 8.0 """ out: dict[str, Any] = { 'localization': obj.localization, 'n_images': obj.n_images, 'position_sigma_m': round(obj.sigma_m, 2), 'parallax_deg': round(obj.parallax_deg, 1), 'footprint_area_m2': round(obj.area_m2, 1), 'length_m': round(obj.length_m, 1), 'width_m': round(obj.width_m, 1), 'survey_days': list(obj.days), } if obj.rms_m is not None: out['position_rms_m'] = round(obj.rms_m, 2) if obj.sources is not None: out['sources'] = obj.sources if obj.aerial_offset_m is not None: out['aerial_offset_m'] = obj.aerial_offset_m if obj.vote_share is not None: out['vote_share'] = round(obj.vote_share, 2) if obj.heading_deg is not None: out['heading_deg'] = round(obj.heading_deg, 1) return out