Files
DCCONSTRUCTIONS 69dc566665 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.
2026-10-29 09:10:00 +03:00

107 lines
6.4 KiB
Python

"""Object-level frontage and paint fitting in metres, independent of location."""
import numpy as np,cv2,shapely
from scipy.ndimage import median_filter
from shapely.geometry import LineString,Point,Polygon
from shapely.ops import unary_union
def sample_line(p,step=.1):
line=LineString(p);t=np.linspace(0,line.length,max(2,int(np.ceil(line.length/step))+1))
return np.array([line.interpolate(x).coords[0][:2] for x in t])
def frontage_envelope(lines,ground_side,maximum_recess=1.0):
"""Keep the exposed first-floor envelope; retain unoccluded recesses.
Input line planes are independently supported by vertical source surfaces.
No building back or footprint closure is generated here.
"""
records=[]
for i,line in enumerate(lines):
q=np.asarray(line.coords)[:,:2];u=q[-1]-q[0];u/=np.linalg.norm(u);n=np.array([-u[1],u[0]])
points=sample_line(q);side=ground_side(points,n);records.append((q,u,n*side,points))
out=[];suppressed=0
for i,(q,u,n,points) in enumerate(records):
hidden=np.zeros(len(points),bool)
for j,(other,v,_,_) in enumerate(records):
if i==j or abs(u@v)<np.cos(np.deg2rad(5)):continue
t=(points-other[0])@v;length=np.linalg.norm(other[-1]-other[0]);nearest=other[0]+np.clip(t,0,length)[:,None]*v
offset=(nearest-points)@n;along=abs((nearest-points)@u)
hidden|=(t>=0)&(t<=length)&(offset>.12)&(offset<maximum_recess)&(along<.15)
suppressed+=float(hidden.mean()*lines[i].length)
# Opening/closing only 30 cm suppresses isolated sampling switches.
visible=~hidden
cuts=np.r_[0,np.flatnonzero(np.diff(visible.astype(int)))+1,len(points)]
for a,b in zip(cuts[:-1],cuts[1:]):
if visible[a] and b-a>1 and np.linalg.norm(points[b-1]-points[a])>=1.2:
out.append((LineString([points[a],points[b-1]]),[i]))
# Merge nearly collinear observed runs. A recess wider than 18 cm remains a
# distinct facade; an unobserved gap above 1.5 m is never bridged.
changed=True
while changed:
changed=False
for i,(a,idsa) in enumerate(out):
pa=np.array(a.coords);u=pa[1]-pa[0];u/=np.linalg.norm(u);n=np.array([-u[1],u[0]])
for j in range(i+1,len(out)):
b,idsb=out[j];pb=np.array(b.coords);v=pb[1]-pb[0];v/=np.linalg.norm(v)
if abs(u@v)<np.cos(np.deg2rad(3)):continue
if abs((pb-pa[0])@n).max()>.18:continue
ranges=sorted([(0,a.length),tuple(sorted((pb-pa[0])@u))]);gap=ranges[1][0]-ranges[0][1]
if gap>1.5:continue
samples=np.concatenate([sample_line(pa,.2),sample_line(pb,.2)])
fit=cv2.fitLine(samples.astype('float32'),cv2.DIST_HUBER,0,.0001,.0001).ravel();axis=fit[:2];origin=fit[2:];normal=np.array([-axis[1],axis[0]])
if np.max(abs((samples-origin)@normal))>.18:continue
t=(samples-origin)@axis;q=origin+np.array([t.min(),t.max()])[:,None]*axis
candidate=LineString(q);conflict=False
for k,(other,_) in enumerate(out):
if k in [i,j]:continue
cross=candidate.intersection(other)
if cross.geom_type=='Point' and .3<candidate.project(cross)<candidate.length-.3 and .3<other.project(cross)<other.length-.3:
conflict=True;break
if conflict:continue
out[i]=(candidate,sorted(set(idsa+idsb)));out.pop(j);changed=True;break
if changed:break
return out,dict(input_planes=len(lines),exposed_chains=len(out),suppressed_recess_overlap_m=suppressed)
def regularize_paint(p,tolerance=.10):
"""Fit a thin paint object by its centreline/width; retain unknown symbols.
The generic fallback preserves holes and symbol topology. Templates are
deliberately not forced on an unrecognised arrow, letter or bicycle.
"""
if p.area<.05:return p,'small-observation'
coords=np.array(p.exterior.coords)[:,:2];o=coords.mean(0)
_,_,vectors=np.linalg.svd(coords-o,full_matrices=False);u=vectors[0];n=np.array([-u[1],u[0]])
t=(coords-o)@u;s=(coords-o)@n;length=float(t.max()-t.min());extent=float(s.max()-s.min())
if length<1.5 or length/max(extent,.01)<3 or p.interiors:
return p.simplify(.045,preserve_topology=True),'observed-symbol'
# Sample perpendicular sections of the filled paint. Branched objects are
# not modelled as a strip; they retain their observed symbol geometry.
centers=[];widths=[];ambiguous=0
for x in np.linspace(t.min()+.05,t.max()-.05,max(3,int(length/.12))):
segment=LineString(o+x*u+np.array([-extent-1,extent+1])[:,None]*n);cross=p.intersection(segment)
pieces=[cross] if cross.geom_type=='LineString' else [g for g in getattr(cross,'geoms',[]) if g.geom_type=='LineString']
pieces=[g for g in pieces if g.length>.02]
if len(pieces)!=1:ambiguous+=1;continue
q=pieces[0];centers.append(q.interpolate(.5,normalized=True).coords[0]);widths.append(q.length)
if len(centers)<8 or ambiguous>len(centers)*.12:return p.simplify(.045,preserve_topology=True),'branched-observation'
points=np.array(centers)
offset=(points-o)@n;long=(points-o)@u
offset=median_filter(offset,size=3,mode='nearest');points=o+long[:,None]*u+offset[:,None]*n
approx=cv2.approxPolyDP(points.astype('float32'),tolerance,False).reshape(-1,2).astype(float)
if len(approx)<2:return p,'unfitted'
# Width of a sloping/zigzag stroke is its orthogonal width, not its slice width.
tangent=np.gradient(points,axis=0);tangent/=np.maximum(np.linalg.norm(tangent,axis=1)[:,None],1e-8)
normal_width=np.asarray(widths)*abs(tangent@u)
width=float(np.median(normal_width));spread=float(np.quantile(normal_width,.9)-np.quantile(normal_width,.1))
if not .055<=width<=.65 or spread>max(.25,width*1.1):return p.simplify(.045,preserve_topology=True),'variable-width-observation'
axis=LineString(approx)
if not axis.is_simple:return p,'branched-observation'
fitted=axis.buffer(width/2,cap_style=2,join_style=2,mitre_limit=2)
# Shape agreement gate prevents regularising away arrowheads / real paint.
agreement=p.intersection(fitted).area/max(p.union(fitted).area,1e-9)
displacement=p.hausdorff_distance(fitted)
if agreement<.58 or displacement>.3:return p.simplify(.045,preserve_topology=True),'rejected-strip-fit'
return fitted,'parametric-paint-strip'