"""Shared semantic-area geometry for offline urban plans. Classes are 0 unknown, 1 carriageway, 2 pedestrian area. Pixel costs are model observations, not calibrated safety probabilities. All metric tolerances are engineering defaults; they are not a survey-accuracy claim. """ import numpy as np import cv2 import shapely from shapely.geometry import shape from shapely.ops import unary_union, polygonize from rasterio.features import shapes from affine import Affine from scipy.sparse import coo_matrix from scipy.sparse.csgraph import maximum_flow, breadth_first_order CELL = .1 def grid_edges(rgb,weight): h,w=rgb.shape[:2];ids=np.arange(h*w).reshape(h,w);us=[];vs=[];ws=[] gray=cv2.cvtColor(rgb,cv2.COLOR_RGB2GRAY).astype(float) gray=cv2.GaussianBlur(gray,(0,0),2) for dy,dx,scale in [(0,1,1),(1,0,1),(1,1,.7071),(1,-1,.7071)]: ya=slice(0,h-dy);yb=slice(dy,h) xa=slice(max(0,-dx),min(w,w-dx));xb=slice(max(0,dx),min(w,w+dx)) us.append(ids[ya,xa].ravel());vs.append(ids[yb,xb].ravel()) diff=np.abs(gray[ya,xa]-gray[yb,xb]).ravel() ws.append(weight*scale*(.4+.6*np.exp(-diff**2/(2*12**2)))) return np.concatenate(us),np.concatenate(vs),np.concatenate(ws) def energy(labels,costs,edges): l=labels.ravel();u,v,w=edges return float(costs.reshape(3,-1)[l,np.arange(len(l))].sum()+np.sum(w*(l[u]!=l[v]))) def potts(labels,costs,rgb,weight=3,iterations=2): labels=np.asarray(labels) costs=np.asarray(costs) if labels.ndim != 2 or costs.shape != (3,*labels.shape) or rgb.shape != (*labels.shape,3): raise ValueError("Labels, unary costs and RGB must have matching grids") if not np.isfinite(costs).all() or not np.isfinite(rgb).all() or costs.min()<0 or not np.isin(labels,[0,1,2]).all(): raise ValueError("Invalid semantic-area observations") if weight<0 or iterations<1 or iterations>10: raise ValueError("Invalid optimisation limits") labels=labels.astype('uint8',copy=True);h,w=labels.shape;n=h*w;ids=np.arange(n);edges=grid_edges(rgb,weight);a,b,pair=edges trace=[energy(labels,costs,edges)] for cycle in range(iterations): for alpha in [0,1,2]: l=labels.ravel();D=costs.reshape(3,-1);u0=D[l,ids].astype(float);u1=D[alpha].astype(float).copy() e00=pair*(l[a]!=l[b]);e01=pair*(l[a]!=alpha);e10=pair*(alpha!=l[b]) c=(e01+e10-e00)/2 np.add.at(u1,a,e10-e00-c);np.add.at(u1,b,e01-e00-c) shift=np.minimum(u0,u1);u0-=shift;u1-=shift row=np.r_[np.full(n,n),ids,a,b];col=np.r_[ids,np.full(n,n+1),b,a] cap=np.maximum(np.rint(np.r_[u0,u1,c,c]*1000),0).astype('int64') graph=coo_matrix((cap,(row,col)),shape=(n+2,n+2)).tocsr();graph.eliminate_zeros() flow=maximum_flow(graph,n,n+1);res=graph-flow.flow;res.data=(res.data>0).astype('int64');res.eliminate_zeros() reachable=breadth_first_order(res,n,directed=True,return_predecessors=False);reachable=reachable[reachable