Preserve offline geometry, marking, replay and evaluation pipelines with source manifests and synthetic tests. Research qualification does not activate these methods as production navigation.
109 lines
7.3 KiB
Python
109 lines
7.3 KiB
Python
"""Discover whole, previously missing crossings from semantic paint proposals.
|
|
|
|
OpenCV directional morphology separates merged worn bars; existing SciPy
|
|
profiles fit a shared family. Independent original views certify contrast and
|
|
finite ends. No scene coordinates, fabricated slots, or existing-stripe seed.
|
|
"""
|
|
import cv2,numpy as np
|
|
from shapely.geometry import Polygon
|
|
from fit_scene import world,project
|
|
from layer_common import sample
|
|
from scipy.ndimage import gaussian_filter1d
|
|
VERSION='whole-crossing-discovery-v2'
|
|
POLICY=dict(min_bars=3,min_length_m=1.5,max_length_m=9.,min_width_m=.22,max_width_m=.85,
|
|
min_contrast=8.,min_column_support=.6,min_valid=.90,max_period_error_m=.20,
|
|
minimum_period_m=.65,maximum_period_m=1.8,min_semantic=.3)
|
|
|
|
def primitives(rgb,cross,vehicle,g,labels,low,high):
|
|
# Work only in automatically proposed crossing components, at native scale.
|
|
size=rgb.shape[0];cell=60/size
|
|
cross=cv2.resize(cross.astype('float32'),(size,size));veh=cv2.resize(vehicle.astype('float32'),(size,size))
|
|
context=cv2.dilate((cross>.3).astype('uint8'),cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(int(.7/cell)*2+1,)*2))
|
|
n,cc,stats,_=cv2.connectedComponentsWithStats(context,8);result=[]
|
|
for i in range(1,n):
|
|
x,y,w,h,area=stats[i]
|
|
if area*cell*cell<2:continue
|
|
patch=rgb[y:y+h,x:x+w];gray=cv2.cvtColor(patch,cv2.COLOR_RGB2GRAY);hsv=cv2.cvtColor(patch,cv2.COLOR_RGB2HSV)
|
|
k=int(.85/cell)//2*2+1;ridge=cv2.morphologyEx(gray,cv2.MORPH_TOPHAT,cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(k,k)))
|
|
domain=(cc[y:y+h,x:x+w]==i)&(veh[y:y+h,x:x+w]<.25)
|
|
threshold=cv2.threshold(ridge[domain],0,255,cv2.THRESH_BINARY|cv2.THRESH_OTSU)[0]if domain.any()else 255
|
|
mask=(domain&(ridge>max(8,threshold*.65))&(hsv[:,:,1]<110)&(gray>65)).astype('uint8')
|
|
lines=cv2.HoughLinesP(mask*255,1,np.pi/360,threshold=20,minLineLength=.8/cell,maxLineGap=.25/cell)
|
|
hypotheses=[]
|
|
for l in []if lines is None else lines[:,0]:
|
|
a,b=l.reshape(2,2);v=(b-a).astype(float);length=np.linalg.norm(v);v/=max(length,1e-8)
|
|
if any(abs(v@q)>np.cos(np.deg2rad(5))for q in hypotheses):continue
|
|
hypotheses.append(v)
|
|
if len(hypotheses)==12:break
|
|
for v in hypotheses:
|
|
side=int(.8/cell)//2*2+1;kernel=np.zeros((side,side),'uint8');center=np.array([side//2]*2)
|
|
cv2.line(kernel,tuple(np.rint(center-v*(side//2)).astype(int)),tuple(np.rint(center+v*(side//2)).astype(int)),1,max(1,int(.06/cell)))
|
|
# Close small wear along bars, then remove perpendicular connectors.
|
|
bridged=cv2.morphologyEx(mask,cv2.MORPH_CLOSE,np.ones((max(3,int(.10/cell)),)*2,'uint8'))
|
|
opened=cv2.morphologyEx(bridged,cv2.MORPH_OPEN,kernel)
|
|
contours,_=cv2.findContours(opened,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
|
|
for c in contours:
|
|
rect=cv2.minAreaRect(c);width,length=np.sort(rect[1])*cell
|
|
if not(.18<width<1.05 and 1.2<length<10 and cv2.contourArea(c)*cell**2/max(length*width,1e-8)>.55):continue
|
|
box=cv2.boxPoints(rect)+[x,y];poly=Polygon(world((box+.5)*1200/size-.5,g))
|
|
if not poly.is_valid:continue
|
|
xy=np.array(poly.exterior.coords);centerxy=np.array(poly.centroid.coords)
|
|
if np.mean(sample(labels,xy,low,high)==1)<.8:continue
|
|
uv=np.rint(rect[0]).astype(int);uv=np.clip(uv,[0,0],[w-1,h-1])
|
|
if cross[y+uv[1],x+uv[0]]<.25:continue
|
|
if any(poly.intersection(q).area/min(poly.area,q.area)>.5 for q in result):continue
|
|
result.append(poly)
|
|
return result
|
|
|
|
def sample_view(xy,tile,views):
|
|
g=views.geometry(tile);rgb,vehicle=views.inputs(tile);uv=project(xy,g).astype('float32');native=(uv+.5)*rgb.shape[0]/1200-.5
|
|
def read(a,coords):return cv2.remap(a,coords[:,0,None],coords[:,1,None],cv2.INTER_LINEAR).reshape(len(coords),-1)
|
|
colors=read(rgb,native);alpha=read(g['alpha'].astype('float32'),uv).ravel();veh=read(vehicle,uv).ravel()
|
|
observed=(uv.min(1)>=5)&(uv.max(1)<1195)&(alpha>.65)&(veh<.25)
|
|
return colors,observed
|
|
|
|
def evidence(poly,views):
|
|
from crosswalk_family import rectangle_info
|
|
box,c,u,v=rectangle_info(np.array(poly.exterior.coords));a=(box-c)@u;b=(box-c)@v;L=float(np.ptp(a));W=float(np.ptp(b))
|
|
stations=np.linspace(-L*.4,L*.4,max(20,int(L/.06)));offsets=np.array([-.5*W-.18,-W*.25,0,W*.25,.5*W+.18])
|
|
xy=c+stations[None,:,None]*u+offsets[:,None,None]*v
|
|
ends=c+np.array([-L/2-.35,L/2+.35])[:,None,None]*u+np.linspace(-.25*W,.25*W,7)[None,:,None]*v
|
|
points=np.vstack([xy.reshape(-1,2),ends.reshape(-1,2)]);records=[]
|
|
ordered=sorted(views.tiles,key=lambda t:np.linalg.norm(np.mean(t['bounds_xy'],axis=0)-c))
|
|
for t in ordered:
|
|
uv=project(points,views.geometry(t['id']))
|
|
cover=(uv.min(1)>=5)&(uv.max(1)<1195)
|
|
if cover[:xy.size//2].mean()<.7:continue
|
|
colors,valid=sample_view(points,t['id'],views);gray=cv2.cvtColor(colors.reshape(1,-1,3),cv2.COLOR_RGB2GRAY).ravel().astype(float)
|
|
grid=gray[:xy.size//2].reshape(5,-1);cols=valid[:xy.size//2].reshape(5,-1).all(0)
|
|
if cols.mean()<.7:continue
|
|
delta=(grid[1:4]-(grid[0]+grid[4])/2)[:,cols]
|
|
end=gray[xy.size//2:].reshape(2,7);endvalid=valid[xy.size//2:].reshape(2,7);tip_valid=endvalid.mean(1)
|
|
tips=[float(np.median(grid[1:4,cols])-np.median(end[k,endvalid[k]]))for k in range(2)if tip_valid[k]>=.85]
|
|
contrast=float(np.median(delta));column=float((np.mean(delta>POLICY['min_contrast'],axis=0)>=2/3).mean())
|
|
rec=dict(tile=t['id'],valid=float(valid.mean()),body_valid=float(cols.mean()),tip_valid=tip_valid.tolist(),contrast=contrast,column_support=column,tip_contrast=min(tips)if tips else 0.,observed_tips=len(tips),length_m=L,width_m=W)
|
|
records.append(rec)
|
|
if len(records)>=2 and all(r['valid']>.99 for r in records):break
|
|
return sorted(records,key=lambda r:-(r['body_valid']+min(r['tip_valid'])))[:2]
|
|
|
|
def supported(records):
|
|
# One render must show the complete finite bar and both blank tips. A
|
|
# second overlapping render verifies its observed body, even at tile edges.
|
|
return len(records)==2 and records[0]['body_valid']>=POLICY['min_valid']and records[0]['observed_tips']==2 and all(r['body_valid']>=.7 and r['contrast']>=POLICY['min_contrast']and r['column_support']>=POLICY['min_column_support']and(not r['observed_tips']or r['tip_contrast']>=4)for r in records)
|
|
|
|
def periodic(positions):
|
|
gaps=np.diff(np.sort(positions))
|
|
if len(gaps)<2:return False
|
|
period=float(np.median(gaps));return POLICY['minimum_period_m']<=period<=POLICY['maximum_period_m']and float(np.max(abs(gaps-period)))<=POLICY['max_period_error_m']
|
|
|
|
def aligned_with_anchors(poly,anchors):
|
|
from crossing_completion import observations,model
|
|
from crosswalk_family import rectangle_info
|
|
obs=observations(anchors)
|
|
if len(obs)<3:return False
|
|
m=model(obs);centers=np.sort(m['centers']);gaps=np.diff(centers);gaps=gaps[(gaps>.65)&(gaps<1.8)]
|
|
if len(gaps)<2:return False
|
|
period=float(np.median(gaps));box,c,u,v=rectangle_info(np.array(poly.exterior.coords));station=float((c-m['origin'])@m['v']);distance=float(np.min(abs(centers-station)));slots=round(distance/period)
|
|
width=float(np.ptp((box-c)@v))
|
|
return abs(u@m['u'])>.995 and abs(width-m['width'])<=.15 and 1<=slots<=2 and abs(distance-slots*period)<=.18
|