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,
self.segmenter_id, self.models.labels)
permissions |= crossing_mask
permitted |= crossing_mask & values["segmentation.surface"]
permitted |= crossing_mask
values["navigation.surface"] = permitted
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])
sample = {
"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")
if crossing is not None and self.environment == "urban" and self.segmenter_id == "simulation-sam3-surfaces":
crossing = np.asarray(crossing, dtype=bool)
if crossing.shape != surface.shape or np.any(crossing & (inputs["segmentation.labels"] != 3)):
raise ValueError("Crossing admission exceeds observed marking")
if crossing.shape != surface.shape or np.any(crossing & ~np.isin(inputs["segmentation.labels"], (0, 1, 2, 3))):
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
surface |= crossing & inputs["segmentation.surface"]
surface |= crossing
observed_goals = getattr(self, "observed_goals", None)
semantic_observation = inputs.get("source.semantic-observation")
if observed_goals is not None and semantic_observation is not None:
@@ -678,7 +680,7 @@ class ComposedInference:
"navigation.goal": self.goal,
"navigation.intent": intent,
"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
# visual_goal, but persist only explicit profile exclusions in CMU.
"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
an observed sidewalk exit. It is not a traffic-light/right-of-way estimator;
physical deployment and moving-traffic qualification need that separate owner.
Range, body, semantic freshness and road-user collision vetoes remain active.
A zebra is an area, not a set of paint islands. Admission retains a bounded
metric footprint after a measured entry stop and observed sidewalk exit. Only
current ground returns inside it can override unknown/carriageway semantics.
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 numpy as np
from PIL import Image, ImageDraw
from scipy import ndimage
from scipy.spatial import ConvexHull, QhullError
class MarkedCrossing:
speed_limit_mps = .3
stop_seconds = .6
# Geometric reconstruction tolerances, not traffic clearance margins.
grid_m = .2
ground_tolerance_m = .1
def __init__(self, geometry):
self.geometry = geometry
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):
labels = np.asarray(labels)
points = np.asarray(points, dtype=float).reshape(-1, 3)
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 not math.isfinite(captured_at) or len(points) != len(pixels[0])):
raise ValueError('Invalid crossing observation')
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))
axes=np.array([[math.cos(yaw),-math.sin(yaw)],[math.sin(yaw),math.cos(yaw)]])
local=(points[:,:2]-pose[:2])@axes
sampled=labels[pixels]
up=np.array([2*(x*z+w*y),2*(y*z-w*x),1-2*(x*x+y*y)])
height=(points-pose[:3])@up+self.geometry['body_contact_height_m']
distance=np.linalg.norm(local,axis=1)
# This selects semantic ground candidates; it does not certify their
# 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'])))
candidate=(sampled==3)&ground&(local[:,0]>0)&(distance<12)
now=captured_at
if advance and (self.previous is None or now>self.previous[0]):
x, y, z, w = pose[3:]
yaw = math.atan2(2*(w*z+x*y), 1-2*(y*y+z*z))
axes = np.array([[math.cos(yaw), -math.sin(yaw)], [math.sin(yaw), math.cos(yaw)]])
local = (points[:, :2]-pose[:2]) @ axes
sampled = labels[pixels]
up = np.array([2*(x*z+w*y), 2*(y*z-w*x), 1-2*(x*x+y*y)])
height = (points-pose[:3]) @ up + self.geometry['body_contact_height_m']
distance = np.linalg.norm(local, axis=1)
ground = np.abs(height) <= .1+distance*math.tan(math.radians(self.geometry['max_slope_degrees']))
candidate = (sampled == 3) & ground & (local[:, 0] > 0) & (distance < 12)
now = captured_at
if advance and (self.previous is None or now > self.previous[0]):
if self.previous is not None:
before, previous_pose=self.previous; dt=now-before
stable=(0<dt<=2 and np.linalg.norm(pose[:2]-previous_pose[:2])/dt<=.02
and abs(float(pose[3:]@previous_pose[3:]))>=math.cos(.01/2))
self.stopped_since=(before if self.stopped_since is None else self.stopped_since) if stable else None
self.previous=(now,pose.copy())
before, previous_pose = self.previous
dt = now-before
stable = (0 < dt <= 2 and np.linalg.norm(pose[:2]-previous_pose[:2])/dt <= .02
and abs(float(pose[3:] @ previous_pose[3:])) >= math.cos(.01/2))
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]:
return denied, {'state':'stale-observation','admitted':False}
return denied, {'state': 'stale-observation', 'admitted': False}
if self.active is not None:
a=self.active; relative=(pose[:2]-a['origin'])@a['axes']
if relative[0]>a['upper'][0]+self.geometry['length_m']/2:
self.active=None;self.stopped_since=None
state={'state':'approach' if candidate.any() else 'sidewalk','admitted':False,
'active':self.active is not None,
'speed_limit_mps':self.speed_limit_mps if self.active is not None else None,
'scope':'static-simulation; marked area only; no traffic-priority certification'}
if not candidate.any():
return denied,{**state,'active':self.active is not None,
'speed_limit_mps':self.speed_limit_mps if self.active is not None else None}
indices=np.flatnonzero(candidate)
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]))
a = self.active
relative = (pose[:2]-a['origin'][:2]) @ a['axes']
# Completion and abandonment revoke this manoeuvre. It cannot
# expand indefinitely by following unrelated new yellow pixels.
if (relative[0] > a['exit_forward']+self.geometry['length_m']/2
or np.linalg.norm(relative) > 16):
self.active = None
self.stopped_since = None
state = {'scope': 'static-simulation; observed crossing ground only; no traffic-priority certification',
'admitted': False, 'active': False, 'speed_limit_mps': None,
'speed_policy': 'mission-profile-with-independent-collision-limits'}
if self.active is None:
if not exit_seen:return denied,{**state,'state':'incomplete-crossing'}
if distance[seed]>self.geometry['length_m']/2+1.25:
return denied,state
if self.stopped_since is None or now-self.stopped_since<self.stop_seconds:
return denied,{**state,'state':'waiting-for-stop'}
self.active={'origin':pose[:2].copy(),'axes':axes.copy(),'lower':low,'upper':high}
a=self.active; observed=(points[measured,:2]-a['origin'])@a['axes']
a['lower']=np.minimum(a['lower'],observed.min(axis=0))
a['upper']=np.maximum(a['upper'],observed.max(axis=0))
return component,{**state,'state':'crossing','admitted':True,'active':True,
'speed_limit_mps':self.speed_limit_mps,
'entry_stop_confirmed':True}
state.update(self._admit(points, local, sampled, ground, candidate, pose, axes, now))
if self.active is None:
return denied, state
a = self.active
relative = points-a['origin']
coords = relative[:, :2] @ a['axes']
inside = np.all(coords @ a['equations'][:, :2].T + a['equations'][:, 2] <= 1e-7, axis=1)
planar = np.abs(np.column_stack((relative[:, :2], np.ones(len(points)))) @ a['plane']
- relative[:, 2]) <= self.ground_tolerance_m
admitted = inside & planar & np.isin(sampled, (0, 1, 2, 3))
# Sparse raster permissions correspond to actual visible ground returns.
# 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()}