Preserve offline geometry, marking, replay and evaluation pipelines with source manifests and synthetic tests. Research qualification does not activate these methods as production navigation.
55 lines
3.9 KiB
Python
55 lines
3.9 KiB
Python
"""OpenCV raster / SciPy registration with global orientation initialization."""
|
|
import numpy as np, cv2, shapely
|
|
from shapely.geometry import Polygon
|
|
from scipy.optimize import minimize
|
|
from catalog_templates import bicycle
|
|
|
|
def fit_bicycle(p,all_hypotheses=False,proposal_only=False):
|
|
if p.is_empty or p.area<.025:return None
|
|
rect=cv2.minAreaRect(np.asarray(p.convex_hull.exterior.coords,'float32')[:,:2]);corners=cv2.boxPoints(rect);edges=np.roll(corners,-1,axis=0)-corners;k=np.argmax(np.linalg.norm(edges,axis=1));L=float(np.linalg.norm(edges[k]));W=float(min(rect[1]));u=edges[k]/L;ang=np.arctan2(u[1],u[0]);origin=np.asarray(rect[0]);fill=p.area/max(L*W,1e-6)
|
|
if not(.35<L<4.5 and .25<W<2.2 and 1.05<L/W<4 and .10<fill<.70):return None
|
|
closed=p.buffer(.04).buffer(-.04)
|
|
holes=[Polygon(h)for q in ([closed]if closed.geom_type=='Polygon'else getattr(closed,'geoms',[]))if q.geom_type=='Polygon'for h in q.interiors]
|
|
# Semantic seeding supplies class identity; holes are checked in the fitted preset negative space.
|
|
cell=min(.02,max(.005,W/80));lo=np.asarray(p.bounds[:2])-.4;hi=np.asarray(p.bounds[2:])+.4;size=np.ceil((hi-lo)/cell).astype(int)[::-1]
|
|
def draw(poly):
|
|
m=np.zeros(size,np.uint8)
|
|
for q in ([poly]if poly.geom_type=='Polygon'else getattr(poly,'geoms',[])):
|
|
if q.is_empty or q.geom_type!='Polygon':continue
|
|
cv2.fillPoly(m,[np.rint((np.asarray(q.exterior.coords)[:,:2]-lo)/cell).astype('int32')],1)
|
|
for h in q.interiors:cv2.fillPoly(m,[np.rint((np.asarray(h.coords)[:,:2]-lo)/cell).astype('int32')],0)
|
|
return m
|
|
target=draw(p);radius=max(1,int(round(min(.04,W*.06)/cell)));kernel=cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(2*radius+1,2*radius+1));near=cv2.dilate(target,kernel);best=None
|
|
def quality(x):
|
|
m=draw(bicycle(x,fast=True));wide=cv2.dilate(m,kernel);cover=float((m&near).sum()/max(m.sum(),1));recall=float((wide&target).sum()/max(target.sum(),1));iou=float((m&target).sum()/max((m|target).sum(),1));return cover,recall,.6*2*cover*recall/max(cover+recall,1e-6)+.4*iou
|
|
coordinates=shapely.get_coordinates(p)
|
|
seeds=[]
|
|
# Global orientation search, rotated around the symbol centre. The final
|
|
# parameters still use the shared SVG base-point convention.
|
|
def from_center(x):
|
|
cx,cy,a,ll,ww,b=x
|
|
return np.r_[np.array([cx,cy])-ll/2*np.array([np.cos(a),np.sin(a)]),a,ll,ww,b]
|
|
for a in np.arange(24)*np.pi/12:
|
|
axis=np.array([np.cos(a),np.sin(a)]);normal=np.array([-axis[1],axis[0]])
|
|
uv=np.c_[coordinates@axis,coordinates@normal]
|
|
for trim in [0.,.02]:
|
|
low,high=np.quantile(uv,[trim,1-trim],axis=0);ll,ww=high-low
|
|
if min(ll,ww)<.3:continue
|
|
center=((low+high)/2)[0]*axis+((low+high)/2)[1]*normal
|
|
x=np.r_[center,a,ll,ww,0.];seeds.append((quality(from_center(x))[2],x))
|
|
if proposal_only:return max((score for score,_ in seeds),default=0.)
|
|
starts=[]
|
|
for score,x in sorted(seeds,key=lambda v:-v[0]):
|
|
if any(abs(np.arctan2(np.sin(x[2]-q[2]),np.cos(x[2]-q[2])))<np.deg2rad(25)for q in starts):continue
|
|
starts.append(x)
|
|
if len(starts)==6:break
|
|
hypotheses=[]
|
|
for x in starts:
|
|
cx,cy,a,ll,ww,_=x
|
|
bounds=[(cx-.30,cx+.30),(cy-.30,cy+.30),(a-.26,a+.26),(ll*.80,ll*1.20),(ww*.75,ww*1.25),(-.02,.025)]
|
|
opt=minimize(lambda z:1-quality(from_center(z))[2],x,method='Powell',bounds=bounds,options=dict(maxiter=40,xtol=.002,ftol=.002))
|
|
z=from_center(opt.x if quality(from_center(opt.x))[2]>=quality(from_center(x))[2]else x);q=quality(z)
|
|
clean=z.copy();clean[5]=0.
|
|
hypothesis=dict(polygon=bicycle(clean),score=q[2],support=q[0],recall=q[1],parameters=clean.tolist(),raster_blur_m=float(z[5]));hypotheses.append(hypothesis)
|
|
return sorted(hypotheses,key=lambda x:-x['score'])if all_hypotheses else max(hypotheses,key=lambda x:x['score'],default=None)
|