feat(research): preserve urban geometry pipelines and qualification suites

Preserve offline geometry, marking, replay and evaluation pipelines with source manifests and synthetic tests. Research qualification does not activate these methods as production navigation.
This commit is contained in:
DCCONSTRUCTIONS
2026-10-29 09:10:00 +03:00
parent 5d56237124
commit 69dc566665
611 changed files with 52016 additions and 28 deletions
@@ -0,0 +1,101 @@
Image-driven road divider and dash-row reconstruction
====================================================
Research scope
--------------
Downstream linear-paint refinement of families-pass-20261012. Gaussian ground
renders and calibrated transforms are the geometric/image input; point clouds
and colliders are not used. Road, pedestrian, facade, crossing and symbol
features stay unchanged. Existing semantic road coverage and vehicle evidence
are reused. This does not retrain or rerun the semantic models.
Why the prior output missed paint
--------------------------------
The prior extractor required semantic marking support for visible image paint.
Its later dash completion only filled slots between already admitted objects;
it could not discover an entirely missing neighboring row. Short component
orientation and median period estimates could also skew placement.
Method
------
OpenCV top-hat morphology extracts locally bright, thin white/yellow paint.
Connected components propose dashes; probabilistic Hough and transverse ridge
centroids propose longer strips. Detection runs on every surveyed tile using
the same metric policy. Road-domain, vehicle and whole-crossing/symbol masks
constrain proposals; semantic road-marking confidence is not a mandatory gate.
Overlapping tile observations are deduplicated in world coordinates. OpenCV
Huber fitting estimates axes. A standard consensus search on short-component
centers forms rows even when individual blurred rectangles have noisy angles.
SciPy least_squares estimates phase and period jointly, with shared median
length and width. Neighbouring supported straight rows can share direction,
but need not share phase or lane spacing. Center/angle/residual evidence must
support the shared direction; arbitrary curves are not forced parallel.
Every proposed dashed row then requires fresh longitudinal image-profile
confirmation (brightness peaks, width, period and intervening gaps). This
rejects periodic-looking dirt and recovers visible exterior dashes within a
bounded 10 m search. Profile centers reanchor the axis; supported neighboring
rows share direction and period after this image check. Prior map objects may
propose a row, but cannot bypass image confirmation.
Collinear continuous and dashed sections are partitioned before periodic
fitting. Only bounded internal missing dash slots are inferred. Newly found
exterior paint requires actual image profile peaks; no blind continuation outside
the observed range. Full crossing envelopes are excluded from thin-line search.
New accepted line geometry replaces covered prior line geometry; uncovered
pieces are retained with provenance. This reduces duplicate overlays but does
not guarantee seamless joins or resolve every closely spaced paint pattern.
Ready components and sources
----------------------------
OpenCV morphology, HoughLinesP, fitLine; SciPy least_squares and cKDTree;
GEOS/Shapely overlap, clipping and validity. The application glue associates
observations and preserves topology/provenance; there are no street-specific
coordinates, processing ROIs or threshold branches.
https://docs.opencv.org/4.x/d9/db0/tutorial_hough_lines.html
https://docs.opencv.org/4.x/d3/dbe/tutorial_opening_closing_hats.html
Validation and limits
---------------------
Controlled checks cover unseeded parallel dividers/two dash rows, empty and
masked images, exact row spacing, internal missing slots, mixed solid/dash
transitions and rigid-transform invariance. Real-scene audit checks unchanged
nonlinear layers, valid XYZ, unique IDs, collinear rows and output references.
Counts measure produced objects, not independent precision or recall.
This pass models locally straight paint. Curved long markings, severe scan
noise, occlusion, missing road coverage and irregular lengths can still leave
partial rows. The reviewed frozen run also has small gaps introduced where
new rectangles replace only part of a prior continuous line. Closely adjacent
solid/dashed paint can merge into a thick proposal; undetected arrow stems or
crossing stripes can be classified as linear paint. A low-quality Smolensk
candidate remains visually uncertain. These are known limitations, not a
production-quality acceptance. It does not solve every symbol or every marking type. Images
show whole prior review areas as well as every admitted row; diagnostic review
framing never affects processing. Refer to visual-review.json for the actual
accepted scope and limitations of this exact frozen run.
Execution and reproduction
--------------------------
All detection, numerical fitting, tests and rendering run on Worker006.
Mac operations are orchestration, hash verification, artifact copying and review.
Qualification: .runtime/simulation-qualifications/lines-pass-20261012/operator.
Worker: C:/NDC_MISSIONCORE_CACHE/urban-mapping/qualifications/lines-pass-20261012.
Canonical source: simulation/urban-plan-research/lines_pass/bundle.json.
Stage flat sources using bundle files and SHA-256; the source ZIP is already flat.
review-font.ttf is an external rendering-only dependency retained and hashed in
qualification source, omitted from the source archive.
Stages: reconstruct_lines, test_lines, audit_lines, render_lines, render_plan.
Operator replay uses run_lines.py, collect_lines.py, verify_lines.py, the scene
registry, config-v8.json, accepted baseline hashes, the existing checkout/queue,
SSH mission-gpu and private survey caches. It is not a standalone public CLI.
Set URBAN_SOURCE_BUNDLE to the qualified immutable source directory.
Pinned image:
sha256:925b093545e15c270d95d4076139ad8ed48e790eccd9434a58495d58c97671d0
4 CPU, 20 GiB memory, 1 GiB tmpfs, network none, read-only root, 1800 s timeout.
Queue reservation precedes execution; exact owned-container cleanup is checked
before release. Source and accepted baseline hashes accompany every receipt.
No production-map deployment, system installs, commit or Ops publication.
@@ -0,0 +1,19 @@
from pathlib import Path
import json,hashlib,numpy as np,shapely
from shapely.geometry import shape
old=json.loads(Path('/fullplan/full-map.json').read_text());path=Path('/out/full-map.json');new=json.loads(path.read_text());groups=json.loads(Path('/out/line-rows.json').read_text());removed=set(json.loads(Path('/out/line-replacements.json').read_text())['removed_ids']);features={f['id']:f for f in new['features']};checks={}
checks['untouched_identical']=all(features.get(f['id'])==f for f in old['features']if f['id']not in removed)
checks['unique_ids']=len(features)==len(new['features'])
checks['valid_finite_xyz']=all(shape(f['geometry']).is_valid and np.isfinite(shapely.get_coordinates(shape(f['geometry']),include_z=True)).all()for f in new['features'])
checks['only_linear_paint_replaced']=all(f['properties'].get('subtype')=='linear_marking'for f in old['features']if f['id']in removed)
checks['output_ids_materialized']=all(n in features for r in groups for n in r['output_ids'])
checks['parallel_edges']=True
for r in groups:
u=np.array(r['axis']);n=np.array([-u[1],u[0]]);centers=[]
for fid in r['output_ids']:
p=shapely.force_2d(shape(features[fid]['geometry']));centers.append(np.array(p.centroid.coords[0]))
if len(centers)>1 and np.ptp(np.array(centers)@n)>.0001:checks['parallel_edges']=False
checks['dash_rows_have_image_profile']=all(r.get('verified_profile')and r['observed_profile_peaks']>=4 for r in groups if r['kind']=='dashed')
checks['same_policy']=new['linear_paint_refinement']=='image-driven-row-v1'
result=dict(passed=all(checks.values()),checks=checks,full_map_sha256=hashlib.sha256(path.read_bytes()).hexdigest(),metric_accuracy_measured=False,complete_recall_measured=False)
Path('/out/lines-audit.json').write_text(json.dumps(result,indent=2));print(json.dumps(result));assert result['passed']
@@ -0,0 +1,34 @@
{
"schema": "missioncore.offline-plan-bundle/v1",
"root": "simulation/urban-plan-research",
"files": {
"audit_lines.py": "lines_pass/audit_lines.py",
"fit_scene.py": "full_plan/fit_scene.py",
"image_profiles.py": "lines_pass/image_profiles.py",
"layer_common.py": "full_plan/layer_common.py",
"line_reconstruction.py": "lines_pass/line_reconstruction.py",
"reconstruct_lines.py": "lines_pass/reconstruct_lines.py",
"render_lines.py": "lines_pass/render_lines.py",
"render_plan.py": "continuation_pass/render_plan.py",
"test_lines.py": "lines_pass/test_lines.py"
},
"reference_qualification": "lines-pass-20261012",
"source_snapshot": "7fda565ebb80b322deb4",
"source_sha256": {
"audit_lines.py": "623037b2670525f903183f228cd088fa00bb43dd78855cd276e5e8bdd66a7cec",
"fit_scene.py": "d130e092d0acad9994da04ca34810beaa8a31c9602d1858cb4d686c240e42ab8",
"image_profiles.py": "1c497f06053ffff63a476baf6dd65ba75ee17d7c38d04c8ff8c22ae03a27eca8",
"layer_common.py": "5e6a2ef463a786b81d387250b2f2be21511f3dae887c8b9ea424051b1722fa59",
"line_reconstruction.py": "4f76ba0e7e0149ab46086c20a959663a8350dd6c61ec4f204f32bc03c2578479",
"reconstruct_lines.py": "3b83df6fbd2a7b996e03cd7967348dfb1b2f567b6329f4f326efb5d2a96d55e7",
"render_lines.py": "982700451babfb64952071938acb58a71c155bdb4f32927be1635f4b23010cab",
"render_plan.py": "5caa0393cb72808bfb37d9f01ac75cfcacc39d0ea89700aea2a615955d9f8064",
"test_lines.py": "a5b2aab9cb0627bd463d1bd37b1353e0ca14fbffa7dfbac2a928e528dc8ca29a"
},
"external_review_font": {
"name": "review-font.ttf",
"sha256": "525979822591a3447cfc49d943d6f7683508e25543407871c0ed8fed05fd2bd9",
"purpose": "rendering only; qualified copy retained under qualification source; omitted from ZIP"
},
"deployment": false
}
@@ -0,0 +1,69 @@
"""Verify a whole proposed paint row against measured image intensity."""
import numpy as np,cv2
from scipy.signal import find_peaks,peak_widths
from scipy.ndimage import gaussian_filter1d
from shapely.geometry import Polygon
def confirm(rec,sampler):
u=np.array(rec['axis']);o=np.array(rec['origin']);n=np.array([-u[1],u[0]]);points=np.concatenate([np.asarray(p.exterior.coords)for p in rec['polygons']]);a,b=np.min((points-o)@u),np.max((points-o)@u)
if not rec['kind']=='dashed':return rec
step=.025;ts=np.arange(a-10,b+10+step,step);ns=np.arange(-.50,.501,.025);xy=o+ts[:,None,None]*u+ns[None,:,None]*n
rgb,allowed=sampler(xy.reshape(-1,2));gray=cv2.cvtColor(rgb.reshape(len(ts),len(ns),3).astype('uint8'),cv2.COLOR_RGB2GRAY).astype(float);allowed=allowed.reshape(len(ts),len(ns));central=abs(ns)<.18;flank=abs(ns)>.32
back=np.median(gray[:,flank],axis=1);signal=np.quantile(gray[:,central],.85,axis=1)-back;good=allowed[:,central].mean(1)>.8
signal=np.where(good,signal,0);signal=gaussian_filter1d(signal,1)
peaks,props=find_peaks(signal,height=20,prominence=18,distance=int(.4/step));ww=peak_widths(signal,peaks,rel_height=.5)
records=[]
for j,k in enumerate(peaks):
L=ww[0][j]*step
if not .26<L<1.4 or not good[k]:continue
t=ts[0]+(ww[2][j]+ww[3][j])/2*step;normal=gray[max(0,k-3):k+4].mean(0)-back[max(0,k-3):k+4].mean();near=abs(ns)<.28;weights=np.where(near,np.maximum(normal-.5*normal[near].max(),0),0)
if weights.sum()<1:continue
off=float(weights@ns/weights.sum());bright=normal>max(15,.5*normal[near].max());indices=np.flatnonzero(bright&near);W=(indices.max()-indices.min()+1)*.025 if len(indices)else 0
if not .065<W<.36:continue
records.append(dict(t=float(t),L=float(L),W=float(W),offset=off,contrast=float(props['peak_heights'][j]),center=o+t*u+off*n))
if len(records)<4:return None
# Compatible observed peaks extend a row. Distant crossing branches cannot
# bridge more than two missing periods or create unobserved exterior slots.
P=rec['period_m'];center0=np.mean([p.centroid.coords[0]for p in rec['polygons']],axis=0);origcenters=np.array([(np.array(p.centroid.coords[0])-o)@u for p in rec['polygons']]);phase=origcenters[0]
records=[r for r in records if abs((r['t']-phase)/P-round((r['t']-phase)/P))<.23]
if len(records)<4:return None
groups=[]
for r in records:
if not groups or r['t']-groups[-1][-1]['t']>2.4*P:groups.append([r])
else:groups[-1].append(r)
valid=[g for g in groups if g[-1]['t']>a and g[0]['t']<b and len(g)>=4]
if not valid:return None
records=max(valid,key=len)
if len(records)<6 and np.median([r['contrast']for r in records])<40:return None
pts=np.array([r['center']for r in records]);fit=cv2.fitLine(pts.astype('float32'),cv2.DIST_HUBER,0,.0001,.0001).ravel();u=fit[:2];o=fit[2:]
if u[0]<0:u=-u
n=np.array([-u[1],u[0]])
if np.quantile(abs((pts-o)@n),.95)>.10:return None
from line_reconstruction import reconstruct
obs=[dict(center=r['center'],axis=u,L=r['L'],W=r['W'],source_tile=rec['source_tiles'][0])for r in records]
fitted=reconstruct(dict(records=obs,axis=u,origin=o,points=pts,parallel=rec['shared_parallel_direction']))
if fitted is None or fitted['kind']!='dashed':return None
fitted.update(verified_profile=True,observed_profile_peaks=len(records),median_paint_contrast=float(np.median([r['contrast']for r in records])),profile_centers=pts.tolist())
return fitted
def parallelize(records):
"""Joint direction/period only for image-confirmed neighboring straight rows."""
for i,a in enumerate(records):
if not a.get('verified_profile'):continue
pa=np.array(a['profile_centers']);u=np.array(a['axis']);n=np.array([-u[1],u[0]])
for b in records[i+1:]:
if not b.get('verified_profile')or abs(u@b['axis'])<np.cos(np.deg2rad(2)):continue
pb=np.array(b['profile_centers']);delta=pb.mean(0)-pa.mean(0)
if not .6<abs(delta@n)<15 or abs(a['period_m']/b['period_m']-1)>.08:continue
ta=pa@u;tb=pb@u
if min(ta.max(),tb.max())-max(ta.min(),tb.min())<.6*min(np.ptp(ta),np.ptp(tb)):continue
pts=np.concatenate([pa-pa.mean(0),pb-pb.mean(0)]);_,_,vt=np.linalg.svd(pts,full_matrices=False);common=vt[0];common*=1 if common[0]>=0 else -1;normal=np.array([-common[1],common[0]])
if max(np.max(abs((p-p.mean(0))@normal))for p in [pa,pb])>.10:continue
P=(a['period_m']+b['period_m'])/2
for r in [a,b]:
o=np.array(r['origin']);polys=r['polygons'];centers=np.array([p.centroid.coords[0]for p in polys]);t=centers@common;order=np.argsort(t);slots=np.rint((t-t.min())/P);phase=np.median(t-slots*P);offset=float(np.mean(np.array(r['profile_centers'])@normal));length=float(np.median([np.ptp(np.asarray(p.exterior.coords)@common)for p in polys]));width=r['width_m'];new=[]
for slot in slots[order]:
c=(phase+slot*P)*common+offset*normal;new.append(Polygon(c+np.array([[-length/2,-width/2],[length/2,-width/2],[length/2,width/2],[-length/2,width/2],[-length/2,-width/2]])@np.stack([common,normal])))
r.update(polygons=new,axis=common.tolist(),period_m=float(P),shared_parallel_direction=True)
bounds=np.array([p.bounds for p in new]);r['bounds_xy']=[float(bounds[:,0].min()),float(bounds[:,1].min()),float(bounds[:,2].max()),float(bounds[:,3].max())]
return records
@@ -0,0 +1,160 @@
"""Image-driven thin paint observations and whole-row robust metric fitting."""
import numpy as np,cv2,shapely
from shapely.geometry import Polygon,LineString
from scipy.optimize import least_squares
def observation(p,source,kind='component'):
p=np.asarray(p,np.float32);rect=cv2.minAreaRect(p);box=cv2.boxPoints(rect);edges=np.roll(box,-1,axis=0)-box;k=np.argmax(np.linalg.norm(edges,axis=1));L=float(np.linalg.norm(edges[k]));W=float(min(rect[1]));u=edges[k]/max(L,1e-9)
if u[0]<0:u=-u
return dict(center=np.array(rect[0]),axis=u,L=L,W=W,source_tile=source,kind=kind,polygon=Polygon(box))
def extract(rgb,allowed,xy,source,mpp):
gray=cv2.cvtColor(rgb,cv2.COLOR_RGB2GRAY);hsv=cv2.cvtColor(rgb,cv2.COLOR_RGB2HSV)
kernel=cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(int(.6/mpp)//2*2+1,)*2)
ridge=cv2.morphologyEx(gray,cv2.MORPH_TOPHAT,kernel)
white=(hsv[:,:,1]<100)&(gray>100);yellow=(hsv[:,:,0]>12)&(hsv[:,:,0]<36)&(hsv[:,:,1]>50)&(gray>100)
binary=((ridge>12)&(white|yellow)&allowed).astype('uint8')
binary=cv2.morphologyEx(binary,cv2.MORPH_CLOSE,np.ones((3,3),np.uint8))
cc,_=cv2.findContours(binary,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE);records=[]
for c in cc:
if cv2.contourArea(c)*mpp*mpp<.02:continue
o=observation(xy(c[:,0]),source);L,W=o['L'],o['W'];area=cv2.contourArea(c)*mpp*mpp
if .26<L<65 and .045<W<.45 and L/W>2.0 and area/(L*W)>.48:records.append(o)
# Connected stop lines/crossing remnants must not erase long thin strips.
lines=cv2.HoughLinesP(binary,1,np.pi/720,threshold=max(25,int(1.5/mpp)),minLineLength=2.8/mpp,maxLineGap=.10/mpp)
if lines is not None:
for x1,y1,x2,y2 in lines[:,0]:
a=np.array([x1,y1],float);b=np.array([x2,y2],float);u=b-a;L=np.linalg.norm(u);u/=L;n=np.array([-u[1],u[0]])
ts=np.arange(0,L, max(1,.1/mpp));ns=np.arange(-.22/mpp,.22/mpp+1);uv=a+ts[:,None,None]*u+ns[None,:,None]*n
val=cv2.remap(binary,uv[:,:,0].astype('float32'),uv[:,:,1].astype('float32'),cv2.INTER_NEAREST);cnt=val.sum(1)
good=(cnt>=.04/mpp)&(cnt<=.30/mpp)
if np.mean(good)<.80:continue
gaps=np.flatnonzero(np.diff(np.r_[False,~good,False].astype('int8')))
if len(gaps) and max(gaps[1::2]-gaps[::2])*.1>.25:continue
offsets=np.divide(val@ns,cnt,out=np.zeros(len(cnt)),where=cnt>0);points=a+ts[good,None]*u+offsets[good,None]*n
fit=cv2.fitLine(points.astype('float32'),cv2.DIST_HUBER,0,.001,.001).ravel();u=fit[:2];origin=fit[2:];n=np.array([-u[1],u[0]])
if np.quantile(abs((points-origin)@n),.90)*mpp>.045:continue
width=float(np.median(cnt[good])*mpp);t=(points-origin)@u;box=origin+np.array([[t.min(),-width/(2*mpp)],[t.max(),-width/(2*mpp)],[t.max(),width/(2*mpp)],[t.min(),width/(2*mpp)]])@np.stack([u,n]);o=observation(xy(box),source,'hough-ridge')
if o['L']>2.7:records.append(o)
return records,dict(raw_components=len(cc),linear_observations=len(records))
def dedup(records):
result=[]
for o in sorted(records,key=lambda o:-(o['L']*o['W'])):
if any(o['polygon'].intersection(r['polygon']).area/min(o['polygon'].area,r['polygon'].area)>.48 for r in result):continue
result.append(o)
return result
def rows(records):
parent=list(range(len(records)))
def root(i):
while parent[i]!=i:parent[i]=parent[parent[i]];i=parent[i]
return i
for i,a in enumerate(records):
for j,b in enumerate(records[:i]):
d=b['center']-a['center'];u=a['axis'];n=np.array([-u[1],u[0]]);v=b['axis'];m=np.array([-v[1],v[0]])
if abs(u@v)<np.cos(np.deg2rad(15 if max(a['L'],b['L'])<1.5 else 8)):continue
# Short dash orientation is noisy. Both center-to-axis tests constrain rows.
if min(abs(d@n),abs(d@m))>.14 or max(abs(d@n),abs(d@m))>.65:continue
gap=abs(d@u)-(a['L']+b['L'])/2
if gap>9 or abs(d@u)>60:continue
parent[root(i)]=root(j)
groups={}
for i in range(len(records)):groups.setdefault(root(i),[]).append(records[i])
result=[]
for group in groups.values():
pts=np.concatenate([r['center']+np.linspace(-r['L']/2,r['L']/2,max(2,int(r['L']/.4)))[:,None]*r['axis']for r in group]);f=cv2.fitLine(pts.astype('float32'),cv2.DIST_HUBER,0,.0001,.0001).ravel();u=f[:2];o=f[2:];n=np.array([-u[1],u[0]])
if u[0]<0:u=-u;n=-n
residual=abs((pts-o)@n)
if np.quantile(residual,.95)>.14 or residual.max()>.30:
# Reject incompatible chain: retain longer independent supported observations.
for r in group:
if r['L']>3:result.append(dict(records=[r],axis=r['axis'],origin=r['center'],points=np.array([r['center']-r['L']/2*r['axis'],r['center']+r['L']/2*r['axis']]),parallel=False))
continue
result.append(dict(records=group,axis=u,origin=o,points=pts,parallel=False))
# RANSAC-style consensus on component centers supplies entire short-dash
# rows even when each small blurred rectangle has an unreliable orientation.
# The fitting primitive is OpenCV Huber; period/length consistency remains
# mandatory, so random bright components cannot form an admitted row.
from scipy.spatial import cKDTree
short=[r for r in records if .26<r['L']<1.5]
if len(short)>=3:
centers=np.array([r['center']for r in short]);axes=np.array([r['axis']for r in short]);hypotheses=[];seen=set()
for i,j in sorted(cKDTree(centers).query_pairs(3.5)):
u=centers[j]-centers[i];distance=np.linalg.norm(u)
if distance<.5:continue
u/=distance
if min(abs(axes[i]@u),abs(axes[j]@u))<np.cos(np.deg2rad(25)):continue
n=np.array([-u[1],u[0]]);delta=centers-centers[i];ids=np.flatnonzero((abs(delta@n)<.12)&(abs(delta@u)<25)&(abs(axes@u)>np.cos(np.deg2rad(25))))
ids=ids[np.argsort((centers[ids]-centers[i])@u)]
chunks=np.split(ids,np.flatnonzero(np.diff((centers[ids]-centers[i])@u)>3.5)+1)
for ids in chunks:
identity=tuple(sorted(ids.tolist()))
if len(ids)<3 or identity in seen:continue
seen.add(identity);pts=centers[ids];f=cv2.fitLine(pts.astype('float32'),cv2.DIST_HUBER,0,.0001,.0001).ravel();uu=f[:2];oo=f[2:]
if uu[0]<0:uu=-uu
rr=dict(records=[short[k]for k in ids],axis=uu,origin=oo,points=pts,parallel=False)
fit=reconstruct(rr)
if fit is None or fit['kind']!='dashed':continue
hypotheses.append((len(ids),identity,rr))
taken=set();consensus=[]
for _,ids,rr in sorted(hypotheses,key=lambda item:-item[0]):
if len(taken.intersection(ids))>1:continue
taken.update(ids);consensus.append(rr)
if consensus:
claimed={id(short[k])for k in taken}
result=[rr for rr in result if not all(id(r)in claimed for r in rr['records'])]+consensus
# Shared direction for supported neighboring straight rows. Never require equal
# phase or equal spacing across distinct rows; curved evidence can veto it.
for i,a in enumerate(result):
if len(a['records'])<3:continue
neighbors=[a]
for b in result[i+1:]:
if len(b['records'])<3 or abs(a['axis']@b['axis'])<np.cos(np.deg2rad(3)):continue
n=np.array([-a['axis'][1],a['axis'][0]]);delta=b['origin']-a['origin']
if not .6<abs(delta@n)<15:continue
ta=(a['points']-a['origin'])@a['axis'];tb=(b['points']-a['origin'])@a['axis'];overlap=min(ta.max(),tb.max())-max(ta.min(),tb.min())
if overlap<.6*min(np.ptp(ta),np.ptp(tb)):continue
neighbors.append(b)
if len(neighbors)<2:continue
pts=np.concatenate([r['points']-np.mean(r['points'],axis=0)for r in neighbors]);_,_,vt=np.linalg.svd(pts,full_matrices=False);u=vt[0];u*=1 if u[0]>=0 else -1;n=np.array([-u[1],u[0]])
if any(np.max(abs((r['points']-np.mean(r['points'],axis=0))@n))>.14 for r in neighbors):continue
for r in neighbors:r.update(axis=u,origin=np.mean(r['points'],axis=0),parallel=True)
# Partition a shared axis at changes between continuous and dashed paint.
# Collinear solid approaches and short junction dashes must not invalidate
# one another's length/period estimate.
partitioned=[]
for row in result:
u=row['axis'];o=row['origin'];ordered=sorted(row['records'],key=lambda r:(r['center']-o)@u);lens=np.array([r['L']for r in ordered]);values=np.sort(lens)
ratio=values[1:]/np.maximum(values[:-1],1e-6)
cut=np.sqrt(values[np.argmax(ratio)]*values[np.argmax(ratio)+1])if len(ratio)and ratio.max()>2.2 else None
chunks=[]
for r in ordered:
cls=r['L']>cut if cut else False
if not chunks or chunks[-1][0]!=cls:chunks.append((cls,[r]))
else:chunks[-1][1].append(r)
for _,chunk in chunks:
q={**row,'records':chunk};partitioned.append(q)
return partitioned
def reconstruct(row):
u=row['axis'];o=row['origin'];n=np.array([-u[1],u[0]]);rs=row['records'];ranges=sorted([[(r['center']-o)@u-r['L']/2,(r['center']-o)@u+r['L']/2]for r in rs]);merged=[]
for a,b in ranges:
if merged and a<=merged[-1][1]+.11:merged[-1][1]=max(b,merged[-1][1])
else:merged.append([a,b])
lens=np.diff(merged,axis=1).ravel();centers=np.mean(merged,axis=1);width=float(np.clip(np.median([r['W']for r in rs]),.07,.24));filled=0;period=None
if len(merged)==1 and lens[0]>2.7:intervals=merged;kind='solid'
elif len(merged)>=3 and np.median(abs(lens-np.median(lens)))/np.median(lens)<.22:
steps=np.diff(centers);P=float(np.median(steps[steps<np.quantile(steps,.60)+.01]));L=float(np.median(lens));slots=np.rint((centers-centers[0])/P).astype(int)
if P<L*1.25 or P>15 or np.max(np.diff(slots))>3 or len(np.unique(slots))!=len(slots):return None
fit=least_squares(lambda x:(x[0]+slots*x[1])-centers,[centers[0],P],loss='soft_l1',f_scale=.06,bounds=([-np.inf,.85*P],[np.inf,1.15*P]))
phase,P=fit.x;err=abs(phase+slots*P-centers)
if err.max()>min(.20,.17*P):return None
# Only observed range; image discovery supplies previously missing exterior
# dashes, not blind extrapolation from this periodic model.
allslots=np.arange(slots.min(),slots.max()+1);intervals=[[phase+t*P-L/2,phase+t*P+L/2]for t in allslots];filled=len(allslots)-len(slots);kind='dashed';period=float(P)
elif len(merged)>=2 and max(b[0]-a[1]for a,b in zip(merged,merged[1:]))<.55 and sum(lens)>4:
intervals=[[merged[0][0],merged[-1][1]]];kind='solid-interpolated'
else:return None
polys=[Polygon(o+np.array([[a,-width/2],[b,-width/2],[b,width/2],[a,width/2],[a,-width/2]])@np.stack([u,n]))for a,b in intervals]
return dict(polygons=polys,kind=kind,axis=u.tolist(),origin=o.tolist(),width_m=width,period_m=period,filled_internal_slots=int(filled),input_observations=len(rs),output_objects=len(polys),shared_parallel_direction=row['parallel'],source_tiles=sorted(set(r['source_tile']for r in rs)))
@@ -0,0 +1,110 @@
from pathlib import Path
import os,json,time,hashlib
import numpy as np,cv2,shapely
from PIL import Image
from shapely.geometry import shape,Polygon,LineString,mapping
from shapely.ops import transform
from scipy.ndimage import distance_transform_edt
from layer_common import O,S,feature,sample
from fit_scene import world,project
from line_reconstruction import extract,dedup,rows,reconstruct,observation
from image_profiles import confirm,parallelize
from functools import lru_cache
cv2.setNumThreads(3);start=time.monotonic();baseline=Path('/fullplan/full-map.json');old=json.loads(baseline.read_text());tiles=[t for t in json.loads((S/'tile-index.json').read_text())['tiles']if t['status']=='surveyed'];allobs=[];tile_reports=[]
with np.load('/evidence_plan/fields.npz')as z:labels=z['labels'];height=z['z'];low,high=z['bounds']
road=(labels==1);inside=distance_transform_edt(road)*.1
protected=[shapely.force_2d(shape(f['geometry']))for f in old['features']if f['properties']['class']=='road_marking'and f['properties'].get('subtype')!='linear_marking'];families={}
for f in old['features']:
if f['properties'].get('subtype')=='crosswalk':
key=f['properties'].get('crosswalk_family',f['id']);families.setdefault(key,[]).append(shapely.force_2d(shape(f['geometry'])))
protected.extend(shapely.union_all(items).convex_hull.buffer(.20)for items in families.values())
protected_union=shapely.union_all(protected)
def lift(g):return transform(lambda x,y,z=None:(x,y,sample(height,np.c_[x,y],low,high)),g)
for tile in tiles:
name=tile['id'];g=dict(np.load(S/name/'top.geometry.npz'));size=2048;mpp=60/size;rgb=np.asarray(Image.open(Path('/ortho/evidence')/(name+'.ground.png')).convert('RGB').resize((size,size),Image.Resampling.LANCZOS))
with np.load(Path('/ortho/evidence')/(name+'.normal.npz'))as z:vehicle=cv2.resize(z['vehicle'].astype('float32'),(size,size))
def xy(uv):return world((np.asarray(uv)+.5)*1200/size-.5,g)
yy,xx=np.mgrid[:size,:size];points=xy(np.c_[xx.ravel(),yy.ravel()]);allowed=(sample(inside,points,low,high)>.25).reshape(size,size)&(vehicle<.20)
mask=np.zeros((size,size),np.uint8)
# Rasterize only intersecting protected objects; top view transform is calibrated.
domain=shapely.box(*tile['bounds_xy'][0],*tile['bounds_xy'][1])
for p in protected:
if not p.intersects(domain):continue
for q in getattr(p.buffer(.13),'geoms',[p.buffer(.13)]):
if q.geom_type=='Polygon':cv2.fillPoly(mask,[np.rint((project(q.exterior.coords,g)+.5)*size/1200-.5).astype('int32')],1)
allowed&=mask==0
observations,rec=extract(rgb,allowed,xy,name,mpp);allobs.extend(observations);tile_reports.append(dict(tile=name,**rec));print('TILE',name,len(observations),flush=True)
# Prior line objects are only proposals. All dash rows need fresh profile
# evidence before acceptance, including proposals from the previous output.
for f in old['features']:
if f['properties'].get('subtype')!='linear_marking':continue
p=shapely.force_2d(shape(f['geometry']))
if p.geom_type!='Polygon':continue
o=observation(np.asarray(p.exterior.coords),'prior-map')
if .26<o['L']<1.5:allobs.append(o)
records=dedup(allobs);fitted=[];rejected=[]
@lru_cache(maxsize=3)
def inputs(name):
g=dict(np.load(S/name/'top.geometry.npz'));rgb=np.asarray(Image.open(Path('/ortho/evidence')/(name+'.ground.png')).convert('RGB'))
with np.load(Path('/ortho/evidence')/(name+'.normal.npz'))as z:vehicle=z['vehicle'].astype('float32')
return g,rgb,vehicle
(O/'observations.json').write_text(json.dumps([dict(center=r['center'].tolist(),axis=r['axis'].tolist(),L=r['L'],W=r['W'],tile=r['source_tile'],kind=r['kind'])for r in records]))
for row in rows(records):
rec=reconstruct(row)
if rec is None:
rejected.append(dict(count=len(row['records']),center=row['origin'].tolist(),lengths=[r['L']for r in row['records']]));continue
if rec['kind']=='dashed':
midpoint=np.mean([p.centroid.coords[0]for p in rec['polygons']],axis=0);tile=min(tiles,key=lambda t:np.linalg.norm(np.mean(t['bounds_xy'],axis=0)-midpoint));name=tile['id'];geom,rgb,vehicle=inputs(name)
def sampler(xy):
uv=project(xy,geom).astype('float32');native=(uv+.5)*(rgb.shape[0]/1200)-.5
colors=np.concatenate([cv2.remap(rgb,p[:,0,None],p[:,1,None],cv2.INTER_LINEAR).reshape(-1,3)for p in np.array_split(native,max(1,int(np.ceil(len(native)/20000))))]);veh=np.concatenate([cv2.remap(vehicle,p[:,0,None],p[:,1,None],cv2.INTER_LINEAR).ravel()for p in np.array_split(uv,max(1,int(np.ceil(len(uv)/20000))))])
allowed=(sample(labels,xy,low,high)==1)&(veh<.2)&~shapely.contains_xy(protected_union,xy[:,0],xy[:,1])
return colors,allowed
rec['source_tiles']=[name];rec=confirm(rec,sampler)
if rec is None:continue
polys=rec.pop('polygons');okay=[]
for p in polys:
coords=np.asarray(p.exterior.coords);grid=np.array([p.centroid.coords[0],*coords[:,:2]])
if np.mean(sample(labels,grid,low,high)==1)<.8 or p.intersection(protected_union).area>.01:continue
okay.append(p)
if len(okay)<(3 if rec['kind']=='dashed'else 1):continue
rec['output_objects']=len(okay);rec['bounds_xy']=shapely.union_all(okay).bounds;rec['polygons']=okay;fitted.append(rec)
(O/'rejected-rows.json').write_text(json.dumps(rejected,indent=2))
fitted=parallelize(fitted)
# Global geometric NMS after fitting prevents tile overlap and adjacent hypotheses.
accepted=[];used=[]
for rec in sorted(fitted,key=lambda r:-sum(p.area for p in r['polygons'])):
polys=rec['polygons'];kept=[p for p in polys if not any(p.intersection(q).area/min(p.area,q.area)>.35 for q in used)]
if len(kept)<(3 if rec['kind']=='dashed'else 1):continue
rec['polygons']=kept;rec['output_objects']=len(kept);accepted.append(rec);used.extend(kept)
new=[];remove=set();reports=[]
priorlines=[f for f in old['features']if f['properties'].get('subtype')=='linear_marking']
for gi,rec in enumerate(accepted):
polygons=rec.pop('polygons');covered=shapely.union_all(polygons).buffer(.16)
if rec['kind']=='dashed':covered=LineString([polygons[0].centroid.coords[0],polygons[-1].centroid.coords[0]]).buffer(.32,cap_style=2)
sources=[]
for f in priorlines:
p=shapely.force_2d(shape(f['geometry']))
if p.intersection(covered).area/max(p.area,1e-8)>.60:sources.append(f['id']);remove.add(f['id'])
output=[]
for p in polygons:
f=feature(lift(p),'road_marking',subtype='linear_marking',method='image-driven-row-v1',line_kind=rec['kind'],line_family=gi,source_ids=sources,source_tiles=rec['source_tiles'],shared_direction=rec['shared_parallel_direction'],inferred_internal_completion=bool(rec['filled_internal_slots']),template_width_m=rec['width_m'],period_m=rec['period_m']);new.append(f);output.append(f['id'])
reports.append(dict(group=gi,**rec,source_ids=sources,output_ids=output,baseline_objects=len(sources)))
# Clip partially replaced prior line objects instead of drawing old and new
# rectangles over one another. Uncovered prior geometry stays with provenance.
from layer_common import parts
clip=shapely.union_all(used).buffer(.16);residuals=[]
for f in priorlines:
if f['id']in remove:continue
p=shapely.force_2d(shape(f['geometry']));hit=p.intersection(clip).area
if hit/max(p.area,1e-8)<.08:continue
remove.add(f['id'])
for remainder in parts(p.difference(clip)):
if remainder.area<.025:continue
residuals.append(feature(lift(remainder),'road_marking',subtype='linear_marking',method='preserved-unreplaced-linear-part',source_ids=[f['id']]))
(O/'line-replacements.json').write_text(json.dumps(dict(removed_ids=sorted(remove),residual_ids=[f['id']for f in residuals]),indent=2))
result={**old,'features':[f for f in old['features']if f['id']not in remove]+new+residuals,'linear_paint_refinement':'image-driven-row-v1'}
(O/'full-map.json').write_text(json.dumps(result,allow_nan=False));(O/'line-rows.json').write_text(json.dumps(reports,indent=2));(O/'tile-observations.json').write_text(json.dumps(tile_reports,indent=2))
report=dict(scene=os.environ['SCENE'],seconds=time.monotonic()-start,baseline_sha256=hashlib.sha256(baseline.read_bytes()).hexdigest(),raw_observations=len(allobs),deduplicated_observations=len(records),accepted_rows=len(reports),solid_rows=sum(r['kind'].startswith('solid')for r in reports),dashed_rows=sum(r['kind']=='dashed'for r in reports),added_objects=len(new),replaced_objects=len(remove),internal_dash_slots=sum(r['filled_internal_slots']for r in reports),manual_geometry=False,manual_rois=[],policy_version='image-driven-row-v1')
(O/'lines-report.json').write_text(json.dumps(report,indent=2));print('REPORT',json.dumps(report),flush=True)
@@ -0,0 +1,41 @@
from pathlib import Path
import os,json,shutil
from datetime import datetime,timezone
import numpy as np,shapely
from PIL import Image,ImageDraw,ImageFont
from shapely.geometry import shape
from layer_common import O,S
from fit_scene import project
old=json.loads(Path('/fullplan/full-map.json').read_text());new=json.loads((O/'full-map.json').read_text());groups=json.loads((O/'line-rows.json').read_text());tiles=[t for t in json.loads((S/'tile-index.json').read_text())['tiles']if t['status']=='surveyed'];font=ImageFont.truetype('/candidate/review-font.ttf',23)
for p in O.glob('rows-*.jpg'):
h=O/'attempts'/('render-'+datetime.now(timezone.utc).strftime('%Y%m%dT%H%M%S'));h.mkdir(parents=True,exist_ok=True);shutil.move(p,h/p.name)
def draw(im,g,features):
im=im.copy();d=ImageDraw.Draw(im);factor=im.width/1200
for f in features:
if f['properties'].get('subtype')not in ['linear_marking','crosswalk']:continue
for ring in f['geometry']['coordinates']:d.line([tuple(p)for p in project(ring,g)*factor],fill='#f1c300',width=max(3,int(factor*1.2)))
return im
frames=[];manifest=[];loaded={}
for gi,rec in enumerate(groups):
x0,y0,x1,y1=rec['bounds_xy'];center=np.array([(x0+x1)/2,(y0+y1)/2]);tile=min(tiles,key=lambda t:np.linalg.norm(np.mean(t['bounds_xy'],axis=0)-center));name=tile['id']
if name not in loaded:
g=dict(np.load(S/name/'top.geometry.npz'));raw=Image.open(Path('/ortho/evidence')/(name+'.ground.png')).convert('RGB');loaded={name:(g,raw,draw(raw,g,old['features']),draw(raw,g,new['features']))}
g,raw,before,after=loaded[name];factor=raw.width/1200;uv=project([[x0,y0],[x1,y0],[x1,y1],[x0,y1]],g)*factor;center=(uv.min(0)+uv.max(0))/2;extent=max(max(uv.max(0)-uv.min(0))+raw.width*4/60,raw.width*12/60);bbox=tuple(np.r_[center-extent/2,center+extent/2].astype(int));frame=Image.new('RGB',(1800,655),'white');d=ImageDraw.Draw(frame)
for j,(im,label)in enumerate([(raw,'Гауссы'),(before,'До'),(after,'После')]):
frame.paste(im.crop(bbox).resize((600,600),Image.Resampling.LANCZOS),(600*j,55));d.text((600*j+10,12),str(gi)+' · '+label,font=font,fill='#263640')
fn='rows-%03d.jpg'%gi;frame.save(O/fn,quality=94);frames.append(frame);manifest.append(dict(group=gi,file=fn,source_tile=name,kind=rec['kind'],input=rec['baseline_objects'],output=rec['output_objects']))
for start in range(0,len(frames),4):
part=frames[start:start+4];sheet=Image.new('RGB',(1800,655*len(part)),'white')
for k,im in enumerate(part):sheet.paste(im,(0,k*655))
sheet.save(O/('rows-proof-%03d.jpg'%(start//4+1)),quality=94)
(O/'rows-visual-manifest.json').write_text(json.dumps(manifest,indent=2));print('ROWS',len(manifest),flush=True)
# Revisit every short-dash family shown in the prior delivery, using its stored
# bounds only for review framing; these bounds never enter the detector.
references=json.loads(Path('/fullplan/line-families.json').read_text());ref_manifest=[]
for gi,rec in enumerate(references):
x0,y0,x1,y1=rec['bounds_xy'];center=np.array([(x0+x1)/2,(y0+y1)/2]);tile=min(tiles,key=lambda t:np.linalg.norm(np.mean(t['bounds_xy'],axis=0)-center));name=tile['id'];g=dict(np.load(S/name/'top.geometry.npz'));raw=Image.open(Path('/ortho/evidence')/(name+'.ground.png')).convert('RGB');factor=raw.width/1200
uv=project([[x0,y0],[x1,y0],[x1,y1],[x0,y1]],g)*factor;center=(uv.min(0)+uv.max(0))/2;extent=max(max(uv.max(0)-uv.min(0))+raw.width*8/60,raw.width*18/60);bbox=tuple(np.r_[center-extent/2,center+extent/2].astype(int));frame=Image.new('RGB',(2400,855),'white');d=ImageDraw.Draw(frame)
for j,(im,label)in enumerate([(raw,'Гауссы'),(draw(raw,g,old['features']),'До'),(draw(raw,g,new['features']),'После')]):
frame.paste(im.crop(bbox).resize((800,800),Image.Resampling.LANCZOS),(800*j,55));d.text((800*j+10,12),label,font=font,fill='#263640')
fn='reference-%02d.jpg'%gi;frame.save(O/fn,quality=96);ref_manifest.append(dict(group=gi,file=fn,source_tile=name,bounds_source='prior line-families.json; review framing only'))
(O/'reference-visual-manifest.json').write_text(json.dumps(ref_manifest,indent=2))
@@ -0,0 +1,42 @@
import json,numpy as np,cv2
from shapely.geometry import Polygon
from line_reconstruction import extract,dedup,rows,reconstruct,observation
checks={};rng=np.random.default_rng(319);mpp=.025;rgb=np.full((700,1000,3),65,np.uint8)
for y in [170,430]:
for x in range(100,851,50):cv2.rectangle(rgb,(x,y),(x+22,y+6),(200,200,200),-1)
for y in [280,295]:cv2.rectangle(rgb,(70,y),(925,y+5),(210,210,210),-1)
allow=np.ones(rgb.shape[:2],bool);xy=lambda x:np.asarray(x)*mpp
obs,_=extract(rgb,allow,xy,'synthetic',mpp);recs=[x for r in rows(dedup(obs))if(x:=reconstruct(r))is not None]
dash=[r for r in recs if r['kind']=='dashed'];solid=[r for r in recs if r['kind'].startswith('solid')]
checks['unseeded_two_dash_rows']=len(dash)==2 and all(r['output_objects']==16 for r in dash)
checks['unseeded_parallel_dividers']=len(solid)==2
checks['straight_parallel_dash_geometry']=all(abs(r['axis'][1])<1e-5 for r in dash)
checks['same_measured_period']=all(abs(r['period_m']-1.25)<.03 for r in dash)
none,_=extract(rgb,np.zeros_like(allow),xy,'masked',mpp);checks['masked_surface_not_paint']=len(none)==0
none,_=extract(np.full_like(rgb,65),allow,xy,'blank',mpp);checks['blank_no_paint']=len(none)==0
# Independent per-dash length/orientation noise must not accumulate phase drift.
g=[]
for i in [0,1,2,4,5,6,7,8,9,10]:
center=np.array([i*1.25+rng.normal(0,.02),rng.normal(0,.015)]);ang=rng.normal(0,.006);u=np.array([np.cos(ang),np.sin(ang)]);n=np.array([-u[1],u[0]]);L=.58+rng.normal(0,.025);box=center+np.array([[-L/2,-.07],[L/2,-.07],[L/2,.07],[-L/2,.07]])@np.stack([u,n]);g.append(observation(box,'synthetic'))
a=[reconstruct(r)for r in rows(g)];a=[x for x in a if x is not None];checks['missing_internal_slot']=len(a)==1 and a[0]['filled_internal_slots']==1 and a[0]['output_objects']==11
if a:
centers=np.array([p.centroid.coords[0]for p in a[0]['polygons']]);diff=np.diff(centers,axis=0);checks['equal_spacing_no_accumulated_jitter']=np.max(np.linalg.norm(diff-diff.mean(0),axis=1))<1e-6
mixed=g+[observation(np.array([[-12,-.07],[-2,-.07],[-2,.07],[-12,.07]]),'solid')]
mm=[reconstruct(r)for r in rows(mixed)];mm=[r for r in mm if r is not None]
checks['solid_to_dash_transition_preserves_both']=any(r['kind']=='dashed'and r['output_objects']==11 for r in mm)and any(r['kind']=='solid'for r in mm)
rot=np.array([[np.cos(.73),-np.sin(.73)],[np.sin(.73),np.cos(.73)]]);gg=[observation(np.asarray(r['polygon'].exterior.coords)@rot.T+np.array([133.,-82.]),'rotated')for r in g];rr=[reconstruct(r)for r in rows(gg)];rr=[x for x in rr if x is not None];checks['rigid_transform_invariance']=len(rr)==len(a) and rr[0]['output_objects']==a[0]['output_objects']and abs(rr[0]['period_m']-a[0]['period_m'])<.002
from image_profiles import confirm
proposal={**dash[0]};proposal['polygons']=proposal['polygons'][:9] # remaining seven lie within the bounded 10 m search
def sampler(points):
uv=(points/mpp).astype('float32');colors=np.concatenate([cv2.remap(rgb,q[:,0,None],q[:,1,None],cv2.INTER_LINEAR).reshape(-1,3)for q in np.array_split(uv,max(1,int(np.ceil(len(uv)/20000))))]);allowed=(uv[:,0]>=0)&(uv[:,0]<rgb.shape[1])&(uv[:,1]>=0)&(uv[:,1]<rgb.shape[0]);return colors,allowed
verified=confirm(proposal,sampler)
checks['profile_recovers_visible_exterior_dashes']=verified is not None and verified['output_objects']==16
blank=lambda p:(np.full((len(p),3),90,np.uint8),np.ones(len(p),bool))
checks['periodic_proposal_on_blank_is_rejected']=confirm(proposal,blank)is None
shifted={**proposal,'origin':(np.array(proposal['origin'])+np.array([0,.12])).tolist()}
verified=confirm(shifted,sampler)
checks['profile_reanchors_offset_row']=verified is not None and abs(verified['origin'][1]-dash[0]['origin'][1])<.04
from image_profiles import parallelize
pair=[confirm(r,sampler)for r in dash];pair=[r for r in pair if r is not None];pair=parallelize(pair)
checks['confirmed_neighbor_rows_share_direction_and_period']=len(pair)==2 and np.allclose(pair[0]['axis'],pair[1]['axis'])and abs(pair[0]['period_m']-pair[1]['period_m'])<1e-8
result=dict(passed=all(checks.values()),checks={k:bool(v)for k,v in checks.items()});open('/out/line-tests.json','w').write(json.dumps(result,indent=2));print(json.dumps(result));assert result['passed']