"""Marked-crossing admission for the static RGB/range 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. """ import math import numpy as np from PIL import Image, ImageDraw class MarkedCrossing: speed_limit_mps = .3 stop_seconds = .6 def __init__(self, geometry): self.geometry = geometry self.previous = self.stopped_since = self.active = None 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() 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]): if self.previous is not None: before, previous_pose=self.previous; dt=now-before stable=(0=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} 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])) 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