"""Robust long curb alignment from coherent OpenCV line segments.""" import cv2,numpy as np from shapely.geometry import LineString,Point from plan_continuity import resample,distances from plan_junctions import unit from plan_refinement import clamped_spline import qualify_junctions as q def fit_line_consensus(local,weights,band): local=np.asarray(local,float);weights=np.asarray(weights,float) if len(local)<20 or local.shape!=(len(weights),2)or not np.isfinite(local).all()or not np.isfinite(weights).all()or np.any(weights<0)or weights.sum()<=0:raise ValueError('At least twenty finite weighted observations required') candidates=[] for angle in np.linspace(-.08,.08,33): residual=local[:,1]-angle*local[:,0] for offset in np.arange(-band,band+.001,.05): support=float(np.sum(weights*np.exp(-.5*((residual-offset)/.13)**2))) candidates.append((support,angle,offset)) best=max(candidates);_,slope,offset=best chosen=abs(local[:,1]-slope*local[:,0]-offset)<.24 fit=cv2.fitLine(local[chosen].astype('float32'),cv2.DIST_HUBER,.15,.001,.001).ravel();slope=float(fit[1]/fit[0]);offset=float(fit[3]-slope*fit[2]) if chosen.sum()<10 or np.ptp(local[chosen,0])<5:raise ValueError('Line support is too short') return slope,offset,chosen,sorted(candidates,reverse=True)[:15] def refine_long_edge(points,field,band=2.): p=resample(points,.3);line=LineString(p);axis=unit(p[-1,:2]-p[0,:2]);normal=np.array([-axis[1],axis[0]]);origin=p[len(p)//2,:2] sign=np.sign(np.mean(field.material(p[:,:2]+normal)-field.material(p[:,:2]-normal)))or 1 segments=[];samples=[];weights=[] for tile,_ in field.frames: e=field.load(tile);detected=cv2.createLineSegmentDetector(cv2.LSD_REFINE_STD).detect(cv2.cvtColor(e.image,cv2.COLOR_RGB2GRAY))[0] if detected is None:continue for raw in detected[:,0,:]: ends=q.world(raw.reshape(2,2),e.g);v=ends[1]-ends[0];length=np.linalg.norm(v) if length<.8 or abs(unit(v)@axis)<.985:continue mid=ends.mean(0) if line.distance(Point(mid))>band or min(line.project(Point(mid)),line.length-line.project(Point(mid)))<2:continue if field.frames[field.owners(mid[None,:])[0]][0]!=tile:continue pp=np.linspace(ends[0],ends[1],max(4,int(length/.15)));score,w=e.score(pp,np.tile(normal,(len(pp),1)),sign) weight=float(np.mean(w)*np.clip(np.mean(score)+.15,.05,2.)) segments.append(dict(ends=ends.tolist(),length_m=float(length),weight=weight)) samples.extend(pp);weights.extend([weight]*len(pp)) if len(samples)<20:raise ValueError('Insufficient coherent line evidence') samples=np.asarray(samples);weights=np.asarray(weights);local=np.c_[(samples-origin)@axis,(samples-origin)@normal] # Line consensus limits the influence of discontinuous white splat borders. slope,offset,chosen,candidates=fit_line_consensus(local,weights,band) target=p[:,:2].copy();along=(target-origin)@axis;target=origin+along[:,None]*axis+(slope*along+offset)[:,None]*normal curve,model=clamped_spline(p,target,np.ones(len(p)),spacing=12.,smoothness=80.) deviation=LineString(curve).hausdorff_distance(line) if deviation>band+.1:raise ValueError('Line consensus escaped displacement band') model.update(method='opencv-lsd-line-consensus-huber-clamped-spline',max_displacement_m=deviation,road_sign=float(sign),evidence_segments=len(segments),inlier_samples=int(chosen.sum()),line_origin=origin.tolist(),line_axis=axis.tolist(),line_slope=slope,line_offset=offset) return curve,model,dict(segments=segments,top_hypotheses=candidates,target_xy=target.tolist())