Admit observed crossing ground between zebra markings

This commit is contained in:
DCCONSTRUCTIONS
2026-10-09 23:01:29 +03:00
parent 60d660f447
commit e61aa6da5f
4 changed files with 261 additions and 96 deletions
@@ -82,10 +82,10 @@ class ContinuousComposition(ComposedInference):
np.ones_like(permitted, dtype=bool), self.environment, np.ones_like(permitted, dtype=bool), self.environment,
self.segmenter_id, self.models.labels) self.segmenter_id, self.models.labels)
permissions |= crossing_mask permissions |= crossing_mask
permitted |= crossing_mask & values["segmentation.surface"] permitted |= crossing_mask
values["navigation.surface"] = permitted values["navigation.surface"] = permitted
allowed = permissions[indices] allowed = permissions[indices]
known = values["segmentation.known"][indices] & (permitted[indices] | ~allowed) known = (values["segmentation.known"][indices] | crossing_mask[indices]) & (permitted[indices] | ~allowed)
known &= self.camera_source.semantic_pixels(u[visible], v[visible]) known &= self.camera_source.semantic_pixels(u[visible], v[visible])
sample = { sample = {
"samples": np.column_stack((points[visible][known], allowed[known].astype(int))).tolist(), "samples": np.column_stack((points[visible][known], allowed[known].astype(int))).tolist(),
+6 -4
View File
@@ -559,10 +559,12 @@ class ComposedInference:
crossing = inputs.get("source.crossing-mask") crossing = inputs.get("source.crossing-mask")
if crossing is not None and self.environment == "urban" and self.segmenter_id == "simulation-sam3-surfaces": if crossing is not None and self.environment == "urban" and self.segmenter_id == "simulation-sam3-surfaces":
crossing = np.asarray(crossing, dtype=bool) crossing = np.asarray(crossing, dtype=bool)
if crossing.shape != surface.shape or np.any(crossing & (inputs["segmentation.labels"] != 3)): if crossing.shape != surface.shape or np.any(crossing & ~np.isin(inputs["segmentation.labels"], (0, 1, 2, 3))):
raise ValueError("Crossing admission exceeds observed marking") raise ValueError("Crossing admission exceeds ground surface classes")
if crossing.any() and not inputs.get("source.crossing-admission", {}).get("admitted"):
raise ValueError("Crossing ground requires manoeuvre admission")
permissions |= crossing permissions |= crossing
surface |= crossing & inputs["segmentation.surface"] surface |= crossing
observed_goals = getattr(self, "observed_goals", None) observed_goals = getattr(self, "observed_goals", None)
semantic_observation = inputs.get("source.semantic-observation") semantic_observation = inputs.get("source.semantic-observation")
if observed_goals is not None and semantic_observation is not None: if observed_goals is not None and semantic_observation is not None:
@@ -678,7 +680,7 @@ class ComposedInference:
"navigation.goal": self.goal, "navigation.goal": self.goal,
"navigation.intent": intent, "navigation.intent": intent,
"navigation.surface": surface, "navigation.surface": surface,
"navigation.semantic-known": inputs["segmentation.known"], "navigation.semantic-known": inputs["segmentation.known"] | (crossing if crossing is not None else False),
# Low confidence is not a semantic obstacle. Keep that gate in # Low confidence is not a semantic obstacle. Keep that gate in
# visual_goal, but persist only explicit profile exclusions in CMU. # visual_goal, but persist only explicit profile exclusions in CMU.
"navigation.permissions": permissions, "navigation.permissions": permissions,
+133 -90
View File
@@ -1,116 +1,159 @@
"""Marked-crossing admission for the static RGB/range simulation contour. """Observed crossing-area permission for the static simulation contour.
This admits only the observed crosswalk component after a measured stop and A zebra is an area, not a set of paint islands. Admission retains a bounded
an observed sidewalk exit. It is not a traffic-light/right-of-way estimator; metric footprint after a measured entry stop and observed sidewalk exit. Only
physical deployment and moving-traffic qualification need that separate owner. current ground returns inside it can override unknown/carriageway semantics.
Range, body, semantic freshness and road-user collision vetoes remain active. This is not traffic right-of-way: range, body, freshness and object vetoes remain
independent. Moving traffic needs a separately qualified gap/occlusion policy.
""" """
import math import math
import numpy as np import numpy as np
from PIL import Image, ImageDraw from scipy import ndimage
from scipy.spatial import ConvexHull, QhullError
class MarkedCrossing: class MarkedCrossing:
speed_limit_mps = .3
stop_seconds = .6 stop_seconds = .6
# Geometric reconstruction tolerances, not traffic clearance margins.
grid_m = .2
ground_tolerance_m = .1
def __init__(self, geometry): def __init__(self, geometry):
self.geometry = geometry self.geometry = geometry
self.previous = self.stopped_since = self.active = None self.previous = self.stopped_since = self.active = None
def _groups(self, local, candidate):
"""Join neighbouring paint islands in metres, never the entire raster."""
indices = np.flatnonzero(candidate)
if not len(indices):
return []
cells = np.floor(local[indices] / self.grid_m).astype(int)
low = cells.min(axis=0)
cells -= low
occupied = np.zeros(tuple(cells.max(axis=0) + 7), dtype=bool)
cells += 3
occupied[tuple(cells.T)] = True
y, x = np.mgrid[-3:4, -3:4]
# Two 0.6m neighbourhoods bridge ordinary stripe gaps; distant
# crossings stay separate. A hull is built per connected group.
grown = ndimage.binary_dilation(occupied, structure=x*x+y*y <= 9)
components, _ = ndimage.label(grown)
owners = components[tuple(cells.T)]
return [indices[owners == key] for key in np.unique(owners)]
def _admit(self, points, local, sampled, ground, candidate, pose, axes, now):
state = {'state': 'approach' if candidate.any() else 'sidewalk'}
groups = sorted(self._groups(local, candidate),
key=lambda ids: float(np.linalg.norm(local[ids], axis=1).min()))
for ids in groups:
if len(ids) < 12:
continue
patch = local[ids]
low, high = patch.min(axis=0), patch.max(axis=0)
if high[1]-low[1] < self.geometry['width_m']+.1 or high[0]-low[0] < 1:
continue
# Keep a measured ground plane as well as XY bounds: an unknown
# bus, wall or person above the crossing is never permitted ground.
xyz = points[ids] - pose[:3]
design = np.column_stack((xyz[:, :2], np.ones(len(xyz))))
plane, _, rank, _ = np.linalg.lstsq(design, xyz[:, 2], rcond=None)
if (rank < 3 or np.linalg.norm(plane[:2]) > math.tan(math.radians(self.geometry['max_slope_degrees']))
or np.max(np.abs(design @ plane - xyz[:, 2])) > self.ground_tolerance_m):
continue
planar = np.abs(np.column_stack((points[:, :2]-pose[:2], np.ones(len(points)))) @ plane
- (points[:, 2]-pose[2])) <= self.ground_tolerance_m
exit_mask = ((sampled == 1) & ground & planar
& (local[:, 0] >= high[0]-.3) & (local[:, 0] <= high[0]+4)
& (local[:, 1] >= low[1]) & (local[:, 1] <= high[1]))
exit_points = local[exit_mask]
exit_seen = (len(exit_points) >= 3
and np.linalg.eigvalsh(np.cov(exit_points.T))[0] > 1e-4)
state.update(marked_points=len(ids), exit_points=int(exit_mask.sum()),
observed_exit=bool(exit_seen), marked_width_m=float(high[1]-low[1]))
if not exit_seen:
state['state'] = 'incomplete-crossing'
continue
if np.linalg.norm(patch, axis=1).min() > self.geometry['length_m']/2+1.25:
continue
if self.stopped_since is None or now-self.stopped_since < self.stop_seconds:
return {**state, 'state': 'waiting-for-stop'}
# Connect marking to observed pedestrian entry/exit within the same
# lateral span; no permission is extrapolated into unobserved road.
entry = ((sampled == 1) & ground & planar
& (local[:, 0] >= low[0]-1.5) & (local[:, 0] < low[0])
& (local[:, 1] >= low[1]) & (local[:, 1] <= high[1]))
footprint = np.vstack((patch, local[entry | exit_mask]))
try:
hull = ConvexHull(footprint)
except QhullError:
continue
self.active = dict(origin=pose[:3].copy(), axes=axes.copy(), plane=plane,
polygon=footprint[hull.vertices], equations=hull.equations,
exit_forward=float(np.max(exit_points[:, 0])))
return state
return state
def observe(self, labels, points, pixels, pose, captured_at, *, advance=True): def observe(self, labels, points, pixels, pose, captured_at, *, advance=True):
labels = np.asarray(labels) labels = np.asarray(labels)
points = np.asarray(points, dtype=float).reshape(-1, 3) points = np.asarray(points, dtype=float).reshape(-1, 3)
pose = np.asarray(pose, dtype=float) pose = np.asarray(pose, dtype=float)
if (labels.shape != (512,512) or not np.isfinite(points).all() if (labels.shape != (512, 512) or not np.isfinite(points).all()
or pose.shape != (7,) or not np.isfinite(pose).all() or pose.shape != (7,) or not np.isfinite(pose).all()
or not math.isfinite(captured_at) or len(points) != len(pixels[0])): or not math.isfinite(captured_at) or len(points) != len(pixels[0])):
raise ValueError('Invalid crossing observation') raise ValueError('Invalid crossing observation')
denied = np.zeros(labels.shape, dtype=bool) denied = np.zeros(labels.shape, dtype=bool)
x,y,z,w=pose[3:]; yaw=math.atan2(2*(w*z+x*y),1-2*(y*y+z*z)) x, y, z, w = pose[3:]
axes=np.array([[math.cos(yaw),-math.sin(yaw)],[math.sin(yaw),math.cos(yaw)]]) yaw = math.atan2(2*(w*z+x*y), 1-2*(y*y+z*z))
local=(points[:,:2]-pose[:2])@axes axes = np.array([[math.cos(yaw), -math.sin(yaw)], [math.sin(yaw), math.cos(yaw)]])
sampled=labels[pixels] local = (points[:, :2]-pose[:2]) @ axes
up=np.array([2*(x*z+w*y),2*(y*z-w*x),1-2*(x*x+y*y)]) sampled = labels[pixels]
height=(points-pose[:3])@up+self.geometry['body_contact_height_m'] up = np.array([2*(x*z+w*y), 2*(y*z-w*x), 1-2*(x*x+y*y)])
distance=np.linalg.norm(local,axis=1) height = (points-pose[:3]) @ up + self.geometry['body_contact_height_m']
# This selects semantic ground candidates; it does not certify their distance = np.linalg.norm(local, axis=1)
# physical support. The existing 3D surface/body guards own that check. ground = np.abs(height) <= .1+distance*math.tan(math.radians(self.geometry['max_slope_degrees']))
ground=(np.abs(height)<=.1+distance*math.tan(math.radians(self.geometry['max_slope_degrees']))) candidate = (sampled == 3) & ground & (local[:, 0] > 0) & (distance < 12)
candidate=(sampled==3)&ground&(local[:,0]>0)&(distance<12) now = captured_at
now=captured_at if advance and (self.previous is None or now > self.previous[0]):
if advance and (self.previous is None or now>self.previous[0]):
if self.previous is not None: if self.previous is not None:
before, previous_pose=self.previous; dt=now-before before, previous_pose = self.previous
stable=(0<dt<=2 and np.linalg.norm(pose[:2]-previous_pose[:2])/dt<=.02 dt = now-before
and abs(float(pose[3:]@previous_pose[3:]))>=math.cos(.01/2)) stable = (0 < dt <= 2 and np.linalg.norm(pose[:2]-previous_pose[:2])/dt <= .02
self.stopped_since=(before if self.stopped_since is None else self.stopped_since) if stable else None and abs(float(pose[3:] @ previous_pose[3:])) >= math.cos(.01/2))
self.previous=(now,pose.copy()) self.stopped_since = ((before if self.stopped_since is None else self.stopped_since)
if stable else None)
self.previous = (now, pose.copy())
elif self.previous is not None and now < self.previous[0]: elif self.previous is not None and now < self.previous[0]:
return denied, {'state':'stale-observation','admitted':False} return denied, {'state': 'stale-observation', 'admitted': False}
if self.active is not None: if self.active is not None:
a=self.active; relative=(pose[:2]-a['origin'])@a['axes'] a = self.active
if relative[0]>a['upper'][0]+self.geometry['length_m']/2: relative = (pose[:2]-a['origin'][:2]) @ a['axes']
self.active=None;self.stopped_since=None # Completion and abandonment revoke this manoeuvre. It cannot
state={'state':'approach' if candidate.any() else 'sidewalk','admitted':False, # expand indefinitely by following unrelated new yellow pixels.
'active':self.active is not None, if (relative[0] > a['exit_forward']+self.geometry['length_m']/2
'speed_limit_mps':self.speed_limit_mps if self.active is not None else None, or np.linalg.norm(relative) > 16):
'scope':'static-simulation; marked area only; no traffic-priority certification'} self.active = None
if not candidate.any(): self.stopped_since = None
return denied,{**state,'active':self.active is not None, state = {'scope': 'static-simulation; observed crossing ground only; no traffic-priority certification',
'speed_limit_mps':self.speed_limit_mps if self.active is not None else None} 'admitted': False, 'active': False, 'speed_limit_mps': None,
indices=np.flatnonzero(candidate) 'speed_policy': 'mission-profile-with-independent-collision-limits'}
if self.active is not None:
a=self.active; coords=(points[indices,:2]-a['origin'])@a['axes']
matching=np.all((coords>=a['lower']-.4)&(coords<=a['upper']+.4),axis=1)
indices=indices[matching]
if not len(indices):return denied,{**state,'state':'different-crossing','active':True,
'speed_limit_mps':self.speed_limit_mps}
image=Image.fromarray((labels==3).astype(np.uint8)).copy()
seen=np.zeros(labels.shape,dtype=bool); component=None; attempts=0; chosen=None
for seed in indices[np.argsort(distance[indices])]:
if seen[pixels[0][seed],pixels[1][seed]]:continue
attempts+=1
if attempts>16:break
ImageDraw.floodfill(image,(int(pixels[1][seed]),int(pixels[0][seed])),2)
region=(np.asarray(image)==2)&~seen; seen|=region
measured=candidate & region[pixels]
patch=local[measured]
if len(patch)<(3 if self.active is not None else 12):continue
low,high=np.min(patch,axis=0),np.max(patch,axis=0)
# A spatial area wider than the vehicle, not an isolated stripe.
# Entry proves the complete marked area and its exit. Near that
# exit the same component becomes a short visible strip: retain
# its observed permission without demanding another full crossing.
# Seeds still have to match the active area's measured bounds.
if (self.active is not None or
(high[1]-low[1]>=self.geometry['width_m']+.1 and high[0]-low[0]>=1.)):
evidence=int(np.count_nonzero(region[pixels][indices]))
if chosen is None or evidence>chosen[0]:
chosen=(evidence,region,measured,low,high,seed)
if self.active is None:break
if chosen is None:return denied,{**state,'state':'insufficient-marked-area'}
# A tiny near-camera fragment must not replace the main marked area
# merely because one of its rays is closer. Track the component with
# the most current range evidence inside this already admitted area.
_,component,measured,low,high,seed=chosen
exit_mask=(sampled==1)&ground&(local[:,0]>=high[0]-.3)&(local[:,0]<=high[0]+4)
exit_mask &= (local[:,1]>=low[1]-.5)&(local[:,1]<=high[1]+.5)
exit_points=local[exit_mask]
exit_seen=(len(exit_points)>=3 and np.linalg.eigvalsh(np.cov(exit_points.T))[0]>1e-4)
state.update(marked_points=int(measured.sum()),exit_points=int(exit_mask.sum()),
observed_exit=bool(exit_seen),marked_width_m=float(high[1]-low[1]))
if self.active is None: if self.active is None:
if not exit_seen:return denied,{**state,'state':'incomplete-crossing'} state.update(self._admit(points, local, sampled, ground, candidate, pose, axes, now))
if distance[seed]>self.geometry['length_m']/2+1.25: if self.active is None:
return denied,state return denied, state
if self.stopped_since is None or now-self.stopped_since<self.stop_seconds: a = self.active
return denied,{**state,'state':'waiting-for-stop'} relative = points-a['origin']
self.active={'origin':pose[:2].copy(),'axes':axes.copy(),'lower':low,'upper':high} coords = relative[:, :2] @ a['axes']
a=self.active; observed=(points[measured,:2]-a['origin'])@a['axes'] inside = np.all(coords @ a['equations'][:, :2].T + a['equations'][:, 2] <= 1e-7, axis=1)
a['lower']=np.minimum(a['lower'],observed.min(axis=0)) planar = np.abs(np.column_stack((relative[:, :2], np.ones(len(points)))) @ a['plane']
a['upper']=np.maximum(a['upper'],observed.max(axis=0)) - relative[:, 2]) <= self.ground_tolerance_m
return component,{**state,'state':'crossing','admitted':True,'active':True, admitted = inside & planar & np.isin(sampled, (0, 1, 2, 3))
'speed_limit_mps':self.speed_limit_mps, # Sparse raster permissions correspond to actual visible ground returns.
'entry_stop_confirmed':True} # Never fill a 2D hull over an occluding object; duplicate projected
# pixels with a non-ground return are conservatively denied.
mask = denied.copy()
mask[pixels[0][admitted], pixels[1][admitted]] = True
mask[pixels[0][~admitted], pixels[1][~admitted]] = False
return mask, {**state, 'state': 'crossing', 'admitted': True, 'active': True,
'entry_stop_confirmed': True, 'permitted_ground_points': int(admitted.sum()),
'footprint_world_xy': (a['polygon'] @ a['axes'].T + a['origin'][:2]).tolist()}
+120
View File
@@ -0,0 +1,120 @@
"""Crossing permission covers asphalt gaps, never unrelated road or obstacles."""
import importlib
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
from types import SimpleNamespace
import numpy as np
import pytest
@pytest.fixture
def module(monkeypatch):
monkeypatch.syspath_prepend(str(Path(__file__).parents[1] / 'simulation/ai-polygon'))
return importlib.import_module('urban_crossing')
def scene():
x, y = np.meshgrid(np.arange(.4, 8, .2), np.arange(-3, 3, .2), indexing='ij')
points = np.column_stack((x.ravel(), y.ravel(), np.zeros(x.size)))
pixels = np.unravel_index(np.arange(len(points)), (512, 512))
labels = np.zeros((512, 512), np.uint8)
near = (np.abs(points[:, 1]) <= 1.05)
paint = near & (points[:, 0] >= 1) & (points[:, 0] <= 6.1) & (np.mod(points[:, 0]+.01, 1) < .45)
sidewalk = near & ((points[:, 0] < 1) | (points[:, 0] >= 6.5))
labels[pixels[0][paint], pixels[1][paint]] = 3
labels[pixels[0][sidewalk], pixels[1][sidewalk]] = 1
return labels, points, pixels, np.array([0, 0, .37, 0, 0, 0, 1.])
def gate(module):
return module.MarkedCrossing(dict(length_m=1.16, width_m=.905,
body_contact_height_m=.37, max_slope_degrees=25))
def enter(g, data):
g.observe(*data, 10.)
g.observe(*data, 10.4)
return g.observe(*data, 10.8)
def test_stripes_admit_connected_ground_gaps_only_after_entry_stop(module):
data = scene(); labels, points, pixels, _ = data; g = gate(module)
mask, status = g.observe(*data, 10.)
assert not mask.any() and status['state'] == 'waiting-for-stop'
g.observe(*data, 10.4)
mask, status = g.observe(*data, 10.8)
assert status['admitted'] and status['speed_limit_mps'] is None
inside = (points[:, 0] > 1.1) & (points[:, 0] < 6.1) & (np.abs(points[:, 1]) < .9)
assert mask[pixels][inside].all()
assert mask[pixels][inside & (labels[pixels] == 0)].any()
assert not mask[pixels][np.abs(points[:, 1]) > 1.1].any()
def test_exit_evidence_and_ground_area_are_required(module):
data = scene(); labels, _, pixels, _ = data
labels[labels == 1] = 0
mask, status = enter(gate(module), data)
assert not mask.any() and not status['admitted']
labels[:] = 0
labels[pixels[0][:8], pixels[1][:8]] = 3
assert not enter(gate(module), data)[0].any()
def test_active_crossing_survives_paint_flicker_but_not_obstacles_or_new_road(module):
data = scene(); labels, points, pixels, pose = data; g = gate(module)
original, status = enter(g, data)
assert status['admitted']
labels[labels == 3] = 0
mask, _ = g.observe(*data, 11.)
np.testing.assert_array_equal(mask, original)
ix = np.flatnonzero(mask[pixels])[:3]
# Unknown raised object, explicit wall, and explicit conflict each veto.
points[ix[0], 2] = 1.
labels[pixels[0][ix[1]], pixels[1][ix[1]]] = 4
labels[pixels[0][ix[2]], pixels[1][ix[2]]] = 5
mask, _ = g.observe(*data, 11.2)
assert not mask[pixels][ix].any()
assert not mask[pixels][np.abs(points[:, 1]) > 1.1].any()
assert not g.observe(*data, 9.)[0].any() # out-of-order input
pose[0] = 10.
mask, status = g.observe(*data, 12.)
assert not mask.any() and not status['active']
def test_grouping_does_not_join_distant_markings(module):
g = gate(module)
local = np.array([[1, 0], [1, .2], [2, 0], [2, .2], [8, 0], [8, .2]])
groups = g._groups(local, np.ones(len(local), bool))
assert sorted(map(len, groups)) == [2, 4]
def test_unknown_crossing_ground_reaches_semantic_memory(monkeypatch, module):
composition = importlib.import_module('continuous_composition')
labels, points, pixels, pose = scene(); g = gate(module)
enter(g, (labels, points, pixels, pose))
# Isolate the integration boundary: calibrated point projection/model input
# stay fixed while original unknown confidence remains false.
obj = object.__new__(composition.ContinuousComposition)
obj.environment, obj.segmenter_id = 'urban', 'simulation-sam3-surfaces'
obj.crossing = g
obj.optics = SimpleNamespace(lens_axes=np.array([np.eye(3)]),
rectify_forward=lambda *a: (np.zeros((600,800,3),np.uint8), None))
obj.camera_source = SimpleNamespace(indices=lambda *a:pixels,
semantic_pixels=lambda *a:np.ones(len(points),bool))
monkeypatch.setattr(composition, 'project', lambda *a:(None, np.zeros(len(points)),
np.zeros(len(points)), np.ones(len(points),bool)))
obj.models = SimpleNamespace(labels={}, surface=lambda rgb:{'segmentation.labels':labels,
'segmentation.surface':np.isin(labels, (1,2,3)), 'segmentation.known':labels != 0})
observation = dict(calibration={'lens_axes':[np.eye(3)], 'intrinsics':[1,1,1,1]},
captured_at=11., points=points, pose=pose,
camera_sources={'insta360_left':None,'insta360_right':None}, lens_depths=[])
with ThreadPoolExecutor(max_workers=1) as pool:
obj.pool = pool
result = obj.perceive_view(observation, 1, 0, detect=False)
samples = np.asarray(result['samples']['samples'])
expected_unknown = result['values']['source.crossing-mask'][pixels] & (labels[pixels] == 0)
assert expected_unknown.any()
permitted_points = set(map(tuple, samples[samples[:,3] == 1, :3]))
assert all(tuple(p) in permitted_points for p in points[expected_unknown])
assert not any(tuple(p) in permitted_points for p in points[np.abs(points[:,1]) > 1.1])