Preserve offline geometry, marking, replay and evaluation pipelines with source manifests and synthetic tests. Research qualification does not activate these methods as production navigation.
87 lines
6.0 KiB
Python
87 lines
6.0 KiB
Python
"""Template hypotheses in metric object coordinates; never site coordinates."""
|
|
import numpy as np,cv2,shapely
|
|
from shapely.geometry import Polygon,LineString
|
|
from shapely.ops import unary_union
|
|
from shapely.affinity import rotate,translate
|
|
from scipy.optimize import minimize
|
|
from road_glyph_presets import arrow
|
|
|
|
def template(kind,L,W,stroke):
|
|
if kind!='letter_A':return arrow(kind,L,W,stroke)
|
|
# A is an original parametric preset. Arrows use the attributed SVG library.
|
|
outer=LineString([(0,-W/2),(L,0),(0,W/2)]).buffer(stroke/2,cap_style=2,join_style=3)
|
|
bar=LineString([(L*.3,-W*.35),(L*.3,W*.35)]).buffer(stroke/2,cap_style=2)
|
|
return unary_union([outer,bar])
|
|
|
|
def fit_symbol(p,heading=None,diagnostics=None,allowed_kinds=None):
|
|
if p.geom_type!='Polygon' or p.area<.25:return None
|
|
points=np.array(p.exterior.coords)[:,:2];rect=cv2.minAreaRect(points.astype('float32'));corners=cv2.boxPoints(rect);edges=np.roll(corners,-1,axis=0)-corners;k=np.argmax(np.linalg.norm(edges,axis=1));u=edges[k]/np.linalg.norm(edges[k]);L=np.linalg.norm(edges[k]);W=min(rect[1]);origin=np.array(rect[0]);ang=np.arctan2(u[1],u[0]);fill=p.area/(L*W)
|
|
if not (1.2<L<9 and .35<W<3 and L/W>1.2 and .09<fill<.75):return None
|
|
# A fixed-resolution local evidence patch avoids manipulating full scene pixels.
|
|
cell=.04;lo=np.array(p.bounds[:2])-.6;hi=np.array(p.bounds[2:])+.6;shape=np.ceil((hi-lo)/cell).astype(int)[::-1]
|
|
if max(shape)>350:return None
|
|
target=np.zeros(shape,np.uint8)
|
|
def draw(poly):
|
|
out=np.zeros(shape,np.uint8)
|
|
for part in ([poly] if poly.geom_type=='Polygon' else getattr(poly,'geoms',[])):
|
|
if part.geom_type!='Polygon' or part.is_empty:continue
|
|
cv2.fillPoly(out,[np.rint((np.array(part.exterior.coords)[:,:2]-lo)/cell).astype('int32')],1)
|
|
for hole in part.interiors:cv2.fillPoly(out,[np.rint((np.array(hole.coords)[:,:2]-lo)/cell).astype('int32')],0)
|
|
return out
|
|
target=draw(p);expanded=cv2.dilate(target,cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(5,5)))
|
|
# The counter supplies a strong object identity cue, independent of a noisy
|
|
# semantic mask. A bounded 8 cm closing tolerates small wear breaks.
|
|
closed=p.buffer(.08).buffer(-.08)
|
|
counters=[Polygon(h)for part in ([closed]if closed.geom_type=='Polygon'else getattr(closed,'geoms',[]))if part.geom_type=='Polygon'for h in part.interiors]
|
|
has_counter=any(h.area>.05*L*W for h in counters)
|
|
variants=['letter_A']if has_counter else ['straight_arrow','left_arrow','right_arrow','straight_left_arrow','straight_right_arrow'];best=None
|
|
if heading is not None:ang=float(np.arctan2(heading[1],heading[0]))
|
|
for kind in variants:
|
|
if allowed_kinds is not None and kind not in allowed_kinds:continue
|
|
for flip in [0,np.pi]:
|
|
a=ang+flip;uu=np.array([np.cos(a),np.sin(a)]);base=origin-uu*L/2
|
|
x0=np.array([base[0],base[1],a,L,W,.16]);bounds=[(base[0]-.4,base[0]+.4),(base[1]-.4,base[1]+.4),(a-.16,a+.16),(L*.85,L*1.15),(W*.75,W*1.25),(.08,.32)]
|
|
def polygon(x):
|
|
m=template(kind,x[3],x[4],x[5]);m=rotate(m,x[2],origin=(0,0),use_radians=True);return translate(m,x[0],x[1])
|
|
def loss(x):
|
|
m=draw(polygon(x));wide=cv2.dilate(m,cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(5,5)))
|
|
coverage=(m&expanded).sum()/max(m.sum(),1);recall=(wide&target).sum()/max(target.sum(),1)
|
|
overlap=(m&target).sum()/max((m|target).sum(),1)
|
|
return 1-(.6*2*coverage*recall/max(coverage+recall,1e-6)+.4*overlap)+.03*abs(x[3]/L-1)
|
|
score=loss(x0)
|
|
if kind!='letter_A' and (W<.60 or W/x0[5]<3.5):continue
|
|
# A worn letter may have an open counter; missing topology is not a veto.
|
|
if score>.8:continue
|
|
fit=minimize(loss,x0,method='Powell',bounds=bounds,options=dict(maxiter=25,xtol=.004,ftol=.004));m=polygon(fit.x);r=draw(m)
|
|
coverage=float((r&expanded).sum()/max(r.sum(),1));recall=float((cv2.dilate(r,np.ones((5,5),np.uint8))&target).sum()/max(target.sum(),1));f1=2*coverage*recall/max(coverage+recall,1e-6);overlap=float((r&target).sum()/max((r|target).sum(),1));score=.6*f1+.4*overlap
|
|
if diagnostics is not None:diagnostics.append(dict(kind=kind,coverage=coverage,recall=recall,score=score,overlap=overlap,counter=has_counter,parameters=fit.x.tolist()))
|
|
if kind=='letter_A':
|
|
x=fit.x;bar=LineString([(x[3]*.3,-x[4]*.30),(x[3]*.3,x[4]*.30)]).buffer(x[5]/2,cap_style=2)
|
|
bar=translate(rotate(bar,x[2],origin=(0,0),use_radians=True),x[0],x[1]);support=draw(bar)
|
|
if (support&expanded).sum()/max(support.sum(),1)<.6:continue
|
|
# Positive shape overlap alone confuses arrow heads and triangular signs
|
|
# with A. Its counter is negative evidence and must stay largely unpainted.
|
|
holes=unary_union([Polygon(h)for part in ([m]if m.geom_type=='Polygon'else m.geoms)if part.geom_type=='Polygon'for h in part.interiors])
|
|
core=holes.buffer(-.08)
|
|
mask=draw(core)
|
|
if mask.sum()<8 or (mask&expanded).sum()/mask.sum()>.15:continue
|
|
elif kind.startswith('straight_') and kind!='straight_arrow':
|
|
# A compound arrow needs its lateral branch, even if a straight arrow
|
|
# alone matches most of the template area.
|
|
x=fit.x;u=np.array([np.cos(x[2]),np.sin(x[2])]);n=np.array([-u[1],u[0]])
|
|
yy,xx=np.mgrid[:r.shape[0],:r.shape[1]];xy=np.stack([lo[0]+xx*cell-x[0],lo[1]+yy*cell-x[1]],axis=-1);side=xy@n
|
|
# Artwork is bbox-centered; use the outer quarter on the branch side.
|
|
sign=1 if 'left'in kind else -1
|
|
branch=(r>0)&(side*sign>x[4]*.24)
|
|
if branch.sum()<5 or (branch&expanded).sum()/branch.sum()<.8:continue
|
|
longitudinal=xy@u;head=(r>0)&(longitudinal>x[3]*.8)
|
|
if head.sum()<5 or (head&expanded).sum()/head.sum()<.85:continue
|
|
elif kind in ['left_arrow','right_arrow']:
|
|
x=fit.x;u=np.array([np.cos(x[2]),np.sin(x[2])]);n=np.array([-u[1],u[0]])
|
|
yy,xx=np.nonzero(target);xy=np.c_[lo[0]+xx*cell-x[0],lo[1]+yy*cell-x[1]];longitudinal=xy@u;side=xy@n
|
|
front=side[longitudinal>x[3]*.72];tail=side[longitudinal<x[3]*.32];sign=1 if kind=='left_arrow'else -1
|
|
if len(front)<5 or len(tail)<5 or sign*(np.mean(front)-np.mean(tail))<.22*x[4]:continue
|
|
if coverage>=.72 and recall>=.86 and (best is None or score>best[1]):best=(m,score,kind,recall,fit.x.tolist())
|
|
if best and best[1]>=.80:return best
|
|
return None
|