Preserve offline geometry, marking, replay and evaluation pipelines with source manifests and synthetic tests. Research qualification does not activate these methods as production navigation.
93 lines
6.6 KiB
Python
93 lines
6.6 KiB
Python
from pathlib import Path
|
|
from collections import Counter
|
|
import numpy as np,cv2,shapely,json,hashlib,os,time
|
|
from shapely.geometry import shape,Polygon,LineString,mapping
|
|
from shapely.ops import transform
|
|
from layer_common import O,sample,feature
|
|
from plan_primitives import regularize_paint
|
|
from paint_templates import fit_symbol
|
|
from crosswalk_family import rectangle_info
|
|
from crossing_fit import joint_rectangles
|
|
start=time.monotonic();cv2.setNumThreads(3)
|
|
old=json.loads(Path('/fullplan/full-map.json').read_text());base=old
|
|
with np.load('/evidence_plan/fields.npz')as z:labels=z['labels'];height=z['z'];low,high=z['bounds']
|
|
def lift(g):return transform(lambda x,y,z=None:(x,y,sample(height,np.c_[x,y],low,high)),g)
|
|
records=json.loads(Path('/primary/observations.json').read_text())
|
|
paint_candidates=[(shape(v['geometry']),v['properties'])for v in records['paint']]
|
|
cross_candidates=[(shape(v['geometry']),v['properties'])for v in records['crossbars']]
|
|
paint=[];rejected=[]
|
|
def dedup(records):
|
|
result=[]
|
|
for p,props in sorted(records,key=lambda x:-x[0].area):
|
|
if any(p.intersection(q).area/min(p.area,q.area)>.5 for q,_ in result):continue
|
|
result.append((p,props))
|
|
return result
|
|
cross_candidates=dedup(cross_candidates)
|
|
# A broad appearance proposal must not suppress a semantic component before
|
|
# admission. Keep the two primary observation contracts separate until fitting.
|
|
semantic=[r for r in paint_candidates if r[1].get('proposal_contract')=='semantic-paint-v1']
|
|
appearance=[r for r in paint_candidates if r[1].get('proposal_contract')!='semantic-paint-v1']
|
|
paint_candidates=dedup(semantic)+dedup(appearance);paint=[]
|
|
# Group neighboring parallel stripes without fixture coordinates, then run existing joint fit.
|
|
obs=[]
|
|
for i,(p,props)in enumerate(cross_candidates):
|
|
points=np.asarray(p.exterior.coords);box,center,u,v=rectangle_info(points);obs.append(dict(id=str(i),points=points,box=box,center=center,u=u,v=v))
|
|
parent=list(range(len(obs)))
|
|
def root(i):
|
|
while parent[i]!=i:parent[i]=parent[parent[i]];i=parent[i]
|
|
return i
|
|
for i,a in enumerate(obs):
|
|
for j,b in enumerate(obs[:i]):
|
|
delta=a['center']-b['center']
|
|
if abs(a['u']@b['u'])>np.cos(np.deg2rad(12))and abs(delta@a['u'])<1 and abs(delta@a['v'])<2:parent[root(i)]=root(j)
|
|
groups={}
|
|
for i in range(len(obs)):groups.setdefault(root(i),[]).append(i)
|
|
for ids in groups.values():
|
|
if len(ids)<3:rejected.extend(dict(kind='crosswalk',reason='insufficient-family-support')for i in ids);continue
|
|
fitted,rec=joint_rectangles([obs[i]for i in ids])
|
|
if not rec['optimizer_success']or rec['boundary_residual_p95_m']>.15:rejected.append(dict(kind='crosswalk',reason='joint-fit-disagreement',stripes=len(ids)));continue
|
|
for f,i in zip(fitted,ids):paint.append(feature(lift(Polygon(f['points'])),'road_marking',**cross_candidates[i][1],family_size=len(ids),fit_p95_m=f['fit_p95_m']))
|
|
# Only admitted objects own paint; a rejected hypothesis cannot hide evidence.
|
|
admitted_crossbars=[shapely.force_2d(shape(f['geometry']))for f in paint]
|
|
for p,props in paint_candidates:
|
|
if any(p.intersection(q).area>.2*p.area for q in admitted_crossbars):continue
|
|
if any(p.intersection(shapely.force_2d(shape(f['geometry']))).area/max(min(p.area,shape(f['geometry']).area),1e-9)>.5 for f in paint if f['properties'].get('subtype')=='linear_marking'):continue
|
|
if props.get('proposal_contract')!='semantic-paint-v1' and (props.get('semantic_support',0)<.10 or props.get('semantic_peak',0)<.3):
|
|
rejected.append(dict(kind='paint',reason='appearance-without-object-support',geometry=mapping(p),**props));continue
|
|
fitted,method=regularize_paint(p)
|
|
if method=='parametric-paint-strip':
|
|
paint.append(feature(lift(fitted),'road_marking',subtype='linear_marking',method=method,**props));continue
|
|
rect=cv2.minAreaRect(np.asarray(p.exterior.coords,np.float32));a,b=sorted(rect[1]);iou=p.area/max(a*b,1e-8)
|
|
if a>.045 and a<.5 and b>.5 and b/a>3 and iou>.72 and not p.interiors:
|
|
paint.append(feature(lift(Polygon(cv2.boxPoints(rect))),'road_marking',subtype='linear_marking',method='rectangle-template',**props));continue
|
|
# Recognize a whole appearance component; model support may cover only part
|
|
# of a worn glyph. It must still locate the object, preventing symbols on noise.
|
|
if props.get('semantic_support',0)<.14 or props.get('semantic_peak',0)<.35:
|
|
rejected.append(dict(kind='symbol',reason='no-object-semantic-support',geometry=mapping(p),**props));continue
|
|
center=p.centroid;boundaries=[shapely.force_2d(shape(x['geometry']))for x in base['features']if x['properties']['class']=='road_boundary']
|
|
if not boundaries:
|
|
rejected.append(dict(kind='symbol',reason='no-street-direction',geometry=mapping(p),**props));continue
|
|
nearest=min(boundaries,key=lambda x:x.distance(center))
|
|
station=nearest.project(center);head=np.asarray(nearest.interpolate(min(nearest.length,station+5)).coords[0])-np.asarray(nearest.interpolate(max(0,station-5)).coords[0])
|
|
f=fit_symbol(p,heading=head if np.linalg.norm(head)>1 else None,allowed_kinds={'letter_A'})
|
|
if f is not None:
|
|
fitted,iou,kind,recall,params=f
|
|
axis=np.array([np.cos(params[2]),np.sin(params[2])]);center=fitted.centroid;aligned=False
|
|
for boundary in base['features']:
|
|
if boundary['properties']['class']!='road_boundary':continue
|
|
line=shapely.force_2d(shape(boundary['geometry']))
|
|
if line.distance(center)>12:continue
|
|
station=line.project(center);a=np.asarray(line.interpolate(max(0,station-3)).coords[0]);b=np.asarray(line.interpolate(min(line.length,station+3)).coords[0]);t=b-a;t/=max(np.linalg.norm(t),1e-8)
|
|
if abs(t@axis)>.88:aligned=True;break
|
|
if aligned:paint.append(feature(lift(fitted),'road_marking',subtype=kind,method='symbol-template',template_fit_score=iou,fit_recall=recall,template_parameters=params,**props))
|
|
else:rejected.append(dict(kind='symbol',reason='incompatible-street-direction',geometry=mapping(p),**props))
|
|
else:rejected.append(dict(kind='symbol',reason='no-template-admitted',geometry=mapping(p),**props))
|
|
|
|
from paint_dedup import deduplicate_glyphs
|
|
paint,audit=deduplicate_glyphs(paint)
|
|
result={**base,'features':base['features']+paint,'primary_observations_sha256':hashlib.sha256(Path('/primary/observations.json').read_bytes()).hexdigest()}
|
|
assert all(shape(f['geometry']).is_valid and np.isfinite(shapely.get_coordinates(shape(f['geometry']),include_z=True)).all() for f in result['features'])
|
|
(O/'full-map.json').write_text(json.dumps(result,allow_nan=False))
|
|
(O/'unresolved-markings.json').write_text(json.dumps(rejected,allow_nan=False))
|
|
(O/'paint-assembly-report.json').write_text(json.dumps(dict(paint_subtypes=dict(Counter(f['properties'].get('subtype')for f in paint)),seconds=time.monotonic()-start,source_objects_reused=0,manual_rois=[]),indent=2))
|