feat(research): preserve urban geometry pipelines and qualification suites
Preserve offline geometry, marking, replay and evaluation pipelines with source manifests and synthetic tests. Research qualification does not activate these methods as production navigation.
This commit is contained in:
@@ -0,0 +1,67 @@
|
||||
"""Read existing orthographic survey tiles in place; bounded four-tile cache."""
|
||||
import json
|
||||
from collections import OrderedDict
|
||||
from pathlib import Path
|
||||
import cv2
|
||||
import numpy as np
|
||||
from PIL import Image
|
||||
|
||||
|
||||
class SurveyEvidence:
|
||||
def __init__(self, root):
|
||||
self.root = Path(root)
|
||||
self.tiles = [t for t in json.loads((self.root/'tile-index.json').read_text())['tiles'] if t['status']=='surveyed']
|
||||
self.cache = OrderedDict()
|
||||
|
||||
def load(self, tile):
|
||||
key = tile['id']
|
||||
if key not in self.cache:
|
||||
folder = self.root/key
|
||||
with np.load(folder/'top.geometry.npz') as g:
|
||||
data = {k:g[k] for k in ('view','intrinsics','alpha','depth')}
|
||||
rgb = np.asarray(Image.open(folder/'top.png').convert('RGB'))
|
||||
data['gray'] = cv2.GaussianBlur(cv2.cvtColor(rgb, cv2.COLOR_RGB2GRAY).astype(np.float32), (3,3), .6)
|
||||
self.cache[key] = data
|
||||
if len(self.cache)>4:self.cache.popitem(last=False)
|
||||
self.cache.move_to_end(key)
|
||||
return self.cache[key]
|
||||
|
||||
def support(self, points, key):
|
||||
"""Return observed-ground and oriented image support for each XYZ sample.
|
||||
|
||||
Paint needs a bright ridge, a boundary needs cross-line contrast. Image
|
||||
contrast alone never proves ground: depth and alpha must also agree.
|
||||
"""
|
||||
p = np.asarray(points, float); n = len(p)
|
||||
ground, signal = np.zeros(n, bool), np.zeros(n, bool)
|
||||
tangent = np.gradient(p[:, :2], axis=0)
|
||||
normal = np.column_stack([-tangent[:,1], tangent[:,0]])
|
||||
normal /= np.maximum(np.linalg.norm(normal, axis=1)[:,None], 1e-9)
|
||||
for tile in self.tiles:
|
||||
low, high = np.asarray(tile['core_bounds'])
|
||||
ids = np.flatnonzero(((p[:,:2]>=low-.1)&(p[:,:2]<=high+.1)).all(1))
|
||||
if not len(ids):continue
|
||||
g = self.load(tile); k = g['intrinsics']; view = g['view']; gray = g['gray']
|
||||
q = p[ids]; cam = np.c_[q, np.ones(len(q))]@view.T
|
||||
uv = cam[:,:2]*np.diag(k)[:2]+k[:2,2]-.5
|
||||
h,w = gray.shape
|
||||
valid = ((uv>6)&(uv<[w-7,h-7])).all(1)
|
||||
c,r = np.rint(uv).astype(int).T; c=np.clip(c,0,w-1);r=np.clip(r,0,h-1)
|
||||
valid &= (g['alpha'][r,c]>=.65)&np.isfinite(g['depth'][r,c])&(np.abs(cam[:,2]-g['depth'][r,c])<=.5)
|
||||
def at(offset):
|
||||
shifted = q.copy(); shifted[:,:2] += normal[ids]*offset
|
||||
xy = (np.c_[shifted,np.ones(len(q))]@view.T)[:,:2]*np.diag(k)[:2]+k[:2,2]-.5
|
||||
return cv2.remap(gray, xy[:,0].astype(np.float32)[None], xy[:,1].astype(np.float32)[None], cv2.INTER_LINEAR, borderMode=cv2.BORDER_REPLICATE)[0]
|
||||
center = np.maximum.reduce([at(x) for x in (-.05,0,.05)])
|
||||
left,right = at(-.25),at(.25)
|
||||
if key[0]=='road_marking':
|
||||
supported = (center > np.maximum(left,right)+7)&(center>75)
|
||||
else:
|
||||
supported = np.maximum.reduce([np.abs(left-right), np.abs(center-left), np.abs(center-right)])>8
|
||||
ground[ids] |= valid; signal[ids] |= valid&supported
|
||||
return ground, signal
|
||||
|
||||
def bridge(self, points, key):
|
||||
ground, signal = self.support(points, key)
|
||||
required = .9 if key[0]=='road_marking' else .7
|
||||
return bool(ground.all() and signal.mean()>=required)
|
||||
@@ -0,0 +1,83 @@
|
||||
"""Metric curve operations; no projection, classification or route authority."""
|
||||
import warnings
|
||||
import numpy as np
|
||||
from scipy.interpolate import splprep, splev
|
||||
from shapely.geometry import LineString, Point
|
||||
|
||||
|
||||
def distance(points):
|
||||
return np.r_[0., np.cumsum(np.linalg.norm(np.diff(points[:, :2], axis=0), axis=1))]
|
||||
|
||||
|
||||
def sample(points, step=.15):
|
||||
points = np.asarray(points, float)
|
||||
d = distance(points)
|
||||
keep = np.r_[True, np.diff(d) > 1e-7]
|
||||
points, d = points[keep], d[keep]
|
||||
if len(d) < 2:
|
||||
return points
|
||||
at = np.linspace(0, d[-1], max(2, int(np.ceil(d[-1] / step)) + 1))
|
||||
return np.column_stack([np.interp(at, d, points[:, i]) for i in range(3)])
|
||||
|
||||
|
||||
def lift_piece(piece, original):
|
||||
"""Keep Z from the original metric curve after a planar overlap operation."""
|
||||
line = LineString(original[:, :2]); d = distance(original)
|
||||
xy = np.asarray(piece.coords)[:, :2]
|
||||
at = [line.project(Point(p)) for p in xy]
|
||||
return np.column_stack([xy, np.interp(at, d, original[:, 2])])
|
||||
|
||||
|
||||
def end_direction(points, end):
|
||||
p = sample(points if end == 0 else points[::-1], .2)
|
||||
delta = p[0, :2] - p[min(4, len(p)-1), :2]
|
||||
return delta / max(np.linalg.norm(delta), 1e-9)
|
||||
|
||||
|
||||
def smooth(points, tolerance=.12):
|
||||
"""Piecewise cubic B-splines, fixed endpoints/corners, bounded XYZ deviation.
|
||||
|
||||
The renderer consumes sampled XYZ. The actual knots/controls are retained
|
||||
for CAD consumers, including linear spans where fitting is inappropriate.
|
||||
"""
|
||||
points = np.asarray(points, float)
|
||||
line = LineString(points[:, :2])
|
||||
if line.length < .3 or not line.is_simple:
|
||||
return points, []
|
||||
# Detect structural corners on a simplified curve, not on pixel noise.
|
||||
skeleton = np.asarray(line.simplify(.12).coords)
|
||||
corners = []
|
||||
for i in range(1, len(skeleton)-1):
|
||||
a, b = skeleton[i]-skeleton[i-1], skeleton[i+1]-skeleton[i]
|
||||
if np.dot(a, b) < .766 * np.linalg.norm(a) * np.linalg.norm(b):
|
||||
corners.append(int(np.argmin(np.linalg.norm(points[:, :2]-skeleton[i], axis=1))))
|
||||
cuts = sorted(set([0, *corners, len(points)-1]))
|
||||
result, curves = [], []
|
||||
for low, high in zip(cuts, cuts[1:]):
|
||||
original = points[low:high+1]
|
||||
p = sample(original, .25)
|
||||
reference = LineString(original[:, :2])
|
||||
output = original; curve = dict(degree=1, controls=original.round(5).tolist())
|
||||
if len(p) >= 4:
|
||||
weights = np.ones(len(p)); weights[[0, -1]] = 1e6
|
||||
for factor in (1., .25, .0625):
|
||||
with warnings.catch_warnings():
|
||||
warnings.simplefilter('error', RuntimeWarning)
|
||||
try:
|
||||
tck, _ = splprep(p.T, w=weights, s=len(p)*(.07**2)*factor, k=3)
|
||||
candidate = np.asarray(splev(np.linspace(0, 1, max(4, int(reference.length/.15)+1)), tck)).T
|
||||
except (ValueError, RuntimeWarning):
|
||||
continue
|
||||
candidate[[0, -1]] = original[[0, -1]]
|
||||
fitted = LineString(candidate[:, :2])
|
||||
at = distance(candidate); expected_z = np.interp(at / max(at[-1], 1e-9), distance(p)/distance(p)[-1], p[:, 2])
|
||||
if (fitted.is_simple and fitted.hausdorff_distance(reference) <= tolerance
|
||||
and .94 <= fitted.length/reference.length <= 1.06
|
||||
and np.max(np.abs(candidate[:, 2]-expected_z)) <= .08):
|
||||
output = candidate
|
||||
curve = dict(degree=3, knots=np.asarray(tck[0]).round(8).tolist(),
|
||||
controls=np.asarray(tck[1]).T.round(5).tolist())
|
||||
break
|
||||
result.extend(output if not result else output[1:])
|
||||
curves.append(curve)
|
||||
return np.asarray(result), curves
|
||||
@@ -37,15 +37,21 @@ def main():
|
||||
predictions=[];timings={}
|
||||
for kind in args.kinds:
|
||||
weights=args.assets/('sd_'+kind+'.pth')
|
||||
assert sha(weights)==manifest[weights.name]['sha256'],'Checkpoint hash mismatch'
|
||||
cfg=mmcv.Config.fromfile('projects/configs/vma_res152_e80_'+kind+'.py')
|
||||
cfg.model.pretrained=None;cfg.model.train_cfg=None
|
||||
# Upstream coder relaxes its threshold until it finds a detection. Keep
|
||||
# all native top-k scores and enforce a FIXED threshold after decoding.
|
||||
cfg.model.pts_bbox_head.bbox_coder.score_threshold=None
|
||||
model=build_model(cfg.model,test_cfg=cfg.get('test_cfg')).eval()
|
||||
load_checkpoint(model,str(weights),map_location='cpu',strict=True)
|
||||
model.cuda();start=time.monotonic()
|
||||
global _models
|
||||
if '_models' not in globals(): _models = {}
|
||||
stat = weights.stat()
|
||||
key = (str(weights), stat.st_size, stat.st_mtime_ns)
|
||||
if key not in _models:
|
||||
assert sha(weights)==manifest[weights.name]['sha256'],'Checkpoint hash mismatch'
|
||||
cfg=mmcv.Config.fromfile('projects/configs/vma_res152_e80_'+kind+'.py')
|
||||
cfg.model.pretrained=None;cfg.model.train_cfg=None
|
||||
# Fixed threshold: never relax until a detection appears.
|
||||
cfg.model.pts_bbox_head.bbox_coder.score_threshold=None
|
||||
model=build_model(cfg.model,test_cfg=cfg.get('test_cfg')).eval()
|
||||
load_checkpoint(model,str(weights),map_location='cpu',strict=True)
|
||||
_models[key] = (cfg, model.cuda())
|
||||
cfg, model = _models[key]
|
||||
start=time.monotonic()
|
||||
for x,y in positions:
|
||||
crop=rgb[y:y+1000,x:x+1000]
|
||||
image=torch.from_numpy(crop.copy()).permute(2,0,1).float().cuda()/255.
|
||||
@@ -62,7 +68,7 @@ def main():
|
||||
points=points,tile_xy=[x,y]))
|
||||
print(json.dumps(dict(kind=kind,tile=[x,y],detections=int((result['scores_3d']>=args.threshold).sum()))),flush=True)
|
||||
timings[kind]=time.monotonic()-start
|
||||
del model;torch.cuda.empty_cache()
|
||||
|
||||
doc=dict(schema_version='missioncore.vector-candidates/v1',source_image_sha256=sha(args.image),
|
||||
vma_commit='a6e98e8f704e72499b33da84715ba39e8705e02e',weights=manifest,
|
||||
input_size=[w,h],native_crop_size=1000,threshold=args.threshold,
|
||||
|
||||
@@ -0,0 +1,188 @@
|
||||
"""Whole-location contour consolidation, independent of inference and navigation.
|
||||
|
||||
native detections -> same-class overlap removal -> unambiguous endpoint
|
||||
graph with image-checked bridges -> corner-preserving cubic B-splines
|
||||
|
||||
All thresholds are metric. Missing coverage, branching, road-marking gaps and
|
||||
different heights are never joined just to produce a more attractive drawing.
|
||||
"""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
from collections import defaultdict
|
||||
from pathlib import Path
|
||||
import numpy as np
|
||||
import networkx as nx
|
||||
import warnings
|
||||
from scipy.spatial import cKDTree
|
||||
from shapely.geometry import LineString, shape
|
||||
from shapely.ops import unary_union, linemerge
|
||||
from shapely.strtree import STRtree
|
||||
from shapely.errors import ShapelyDeprecationWarning
|
||||
from contour_geometry import distance, end_direction, lift_piece, sample, smooth
|
||||
|
||||
VERSION = 'missioncore.contour-consolidation/v1'
|
||||
|
||||
|
||||
def semantic(f):
|
||||
p=f['properties']
|
||||
return p['class'], p.get('source_class'), p.get('geometry_role')
|
||||
|
||||
|
||||
class SpatialLines:
|
||||
"""GEOS spatial index; the pinned Shapely 1.8 returns geometry objects."""
|
||||
def __init__(self, records):
|
||||
self.records={id(a['line']):a for a in records}
|
||||
with warnings.catch_warnings():
|
||||
warnings.simplefilter('ignore', category=ShapelyDeprecationWarning)
|
||||
self.tree=STRtree([a['line'] for a in records])
|
||||
def near(self, line, radius=.2):
|
||||
return sorted((self.records[id(g)] for g in self.tree.query(line.buffer(radius))),
|
||||
key=lambda a:(a['ids'],a['line'].wkt))
|
||||
|
||||
|
||||
def consolidate(document, evidence=None, progress=lambda done,total:None):
|
||||
"""Pure input contract: returns a new document and an auditable edit receipt."""
|
||||
features=document['features']
|
||||
if len(features)>20000:raise ValueError('Contour refinement exceeds feature budget')
|
||||
report=dict(schema_version=VERSION, input_features=len(features),
|
||||
duplicates=[], removed_noise=[], trimmed_overlap_m=0., joins=[], smoothed_curves=0)
|
||||
lines=[]; other=[]; progress(0,4)
|
||||
for f in features:
|
||||
if f['geometry']['type']!='LineString' or f['properties']['class'] not in ('curb','road_marking'):
|
||||
other.append(f);continue
|
||||
p=np.asarray(f['geometry']['coordinates'],float)
|
||||
p=p[np.r_[True,np.linalg.norm(np.diff(p[:,:2],axis=0),axis=1)>1e-7]]
|
||||
if len(p)<2:continue
|
||||
lines.append(dict(f=f,p=p,key=semantic(f),line=LineString(p[:,:2]),ids=[f['id']],gaps=[]))
|
||||
# Prefer the stronger observation; remove only close, same-height overlap.
|
||||
spatial=SpatialLines(lines); accepted=set(); records=[]
|
||||
for a in sorted(lines,key=lambda a:(-a['f']['properties']['confidence'],-a['line'].length,a['f']['id'])):
|
||||
masks=[]
|
||||
for b in spatial.near(a['line']):
|
||||
if id(b) not in accepted or a['key']!=b['key'] or a['line'].distance(b['line'])>.15:continue
|
||||
if min(a['line'].length,b['line'].length)<1. and abs(np.dot(end_direction(a['p'],0),end_direction(b['p'],0)))<.94:continue
|
||||
if abs(np.median(a['p'][:,2])-np.median(b['p'][:,2]))>.15:continue
|
||||
mask=b['line'].buffer(.15,cap_style=2)
|
||||
overlap=a['line'].intersection(mask).length
|
||||
# A transverse crossing only occupies a tiny part of a line.
|
||||
if overlap>=min(1.,.8*a['line'].length):masks.append(mask)
|
||||
uncovered=a['line'].difference(unary_union(masks)) if masks else a['line']
|
||||
if uncovered.length<.2*a['line'].length:
|
||||
report['duplicates'].append(a['f']['id']);continue
|
||||
accepted.add(id(a))
|
||||
pieces=[uncovered] if uncovered.geom_type=='LineString' else list(getattr(uncovered,'geoms',[]))
|
||||
report['trimmed_overlap_m']+=a['line'].length-uncovered.length
|
||||
for piece in pieces:
|
||||
if piece.geom_type!='LineString' or piece.length<.25:continue
|
||||
p=lift_piece(piece,a['p'])
|
||||
records.append({**a,'p':p,'line':LineString(p[:,:2])})
|
||||
progress(1,4)
|
||||
endpoints=np.array([a['p'][e] for a in records for e in (0,-1)])
|
||||
tree=cKDTree(endpoints[:,:2]) if len(endpoints) else None
|
||||
# Remove isolated, short, weak fragments only when the survey also rejects them.
|
||||
keep=[]
|
||||
for i,a in enumerate(records):
|
||||
neighbours=set(tree.query_ball_point(endpoints[2*i,:2],1.))|set(tree.query_ball_point(endpoints[2*i+1,:2],1.))
|
||||
isolated=all(j//2==i for j in neighbours)
|
||||
if evidence and isolated and a['line'].length<1.5 and a['f']['properties']['confidence']<.5:
|
||||
ground,signal=evidence.support(sample(a['p'],.1),a['key'])
|
||||
if ground.mean()>.8 and signal.mean()<.25:
|
||||
report['removed_noise'].append(a['f']['id']);continue
|
||||
keep.append(a)
|
||||
records=keep
|
||||
endpoints=np.array([a['p'][e] for a in records for e in (0,-1)])
|
||||
tree=cKDTree(endpoints[:,:2]) if len(endpoints) else None
|
||||
candidates=defaultdict(list); blockers=SpatialLines(records)
|
||||
openings=[shape(f['geometry']) for f in other if f['properties']['class']=='curb_cut']
|
||||
for i,q in enumerate(endpoints):
|
||||
a=records[i//2];va=end_direction(a['p'],i%2)
|
||||
junction=[j for j in tree.query_ball_point(q[:2],.18) if records[j//2]['key']==a['key']]
|
||||
if len(set(j//2 for j in junction))>2:continue
|
||||
maximum=1.25 if a['key'][0]=='curb' else (.2 if a['key'][1]=='stopline' else .5)
|
||||
for j in tree.query_ball_point(q[:2],maximum):
|
||||
if j<=i or i//2==j//2:continue
|
||||
b=records[j//2]
|
||||
if a['key']!=b['key']:continue
|
||||
other_junction=[k for k in tree.query_ball_point(endpoints[j,:2],.18) if records[k//2]['key']==a['key']]
|
||||
if len(set(k//2 for k in other_junction))>2:continue
|
||||
delta=endpoints[j,:2]-q[:2];gap=float(np.linalg.norm(delta));vb=end_direction(b['p'],j%2)
|
||||
if np.dot(va,-vb)<.94 or abs(q[2]-endpoints[j,2])>.12+.12*gap:continue
|
||||
if gap>.02 and min(np.dot(va,delta/gap),np.dot(-vb,delta/gap))<.85:continue
|
||||
bridge=LineString([q[:2],endpoints[j,:2]])
|
||||
if any(bridge.intersects(o) for o in openings):continue
|
||||
if gap>.02 and any(c is not a and c is not b and bridge.crosses(c['line']) for c in blockers.near(bridge)):continue
|
||||
bridge_points=sample(np.array([q,endpoints[j]]),.05) if gap>.02 else np.array([q,endpoints[j]])
|
||||
if gap>.12 and (evidence is None or not evidence.bridge(bridge_points,a['key'])):continue
|
||||
cost=gap+1-np.dot(va,-vb)
|
||||
candidates[i].append((cost,j));candidates[j].append((cost,i))
|
||||
# Mutual, separated best matches: no greedy choice at a branching/ambiguous end.
|
||||
best={}
|
||||
for i,options in candidates.items():
|
||||
options.sort()
|
||||
if len(options)==1 or options[1][0]-options[0][0]>.15:best[i]=options[0][1]
|
||||
links={i:j for i,j in best.items() if best.get(j)==i}
|
||||
# NetworkX identifies components; GEOS owns line assembly and orientation.
|
||||
graph=nx.Graph();graph.add_nodes_from(range(len(records)))
|
||||
for i,j in links.items():
|
||||
if i<j:graph.add_edge(i//2,j//2,ends=(i,j))
|
||||
chains=[]
|
||||
for component in nx.connected_components(graph):
|
||||
members=[records[i] for i in sorted(component)]
|
||||
segments=[LineString(a['p']) for a in members]; gaps=[]; joins=[]
|
||||
for _,_,edge in graph.subgraph(component).edges(data=True):
|
||||
i,j=edge['ends'];q,p=endpoints[i],endpoints[j]
|
||||
gap=float(np.linalg.norm(q[:2]-p[:2]))
|
||||
if gap>1e-7:
|
||||
segments.append(LineString([q,p]))
|
||||
gaps.append(dict(from_xyz=q.round(4).tolist(),to_xyz=p.round(4).tolist(),length_m=round(gap,4),
|
||||
evidence='image-and-ground' if gap>.12 else 'endpoint-tolerance',height_source='endpoint-interpolation'))
|
||||
joins.append(dict(sources=[records[i//2]['ids'][0],records[j//2]['ids'][0]],gap_m=round(gap,4)))
|
||||
merged=linemerge(segments)
|
||||
if merged.geom_type!='LineString' or not merged.is_simple:
|
||||
chains.extend(members);continue
|
||||
report['joins'].extend(joins)
|
||||
chains.append({**members[0],'p':np.asarray(merged.coords),'ids':sorted({i for a in members for i in a['ids']}),'gaps':gaps})
|
||||
progress(2,4)
|
||||
output=list(other)
|
||||
for a in chains:
|
||||
p,curves=smooth(a['p'])
|
||||
original=LineString(a['p'][:,:2]); fitted=LineString(p[:,:2])
|
||||
if any(fitted.crosses(b['line']) and not original.crosses(b['line']) for b in blockers.near(fitted) if not set(a['ids'])&set(b['ids'])):
|
||||
p=a['p'];curves=[]
|
||||
report['smoothed_curves']+=sum(c['degree']==3 for c in curves)
|
||||
coordinates=p.round(4).tolist()
|
||||
ident=hashlib.sha256(json.dumps([a['key'],coordinates],sort_keys=True).encode()).hexdigest()[:20]
|
||||
props={**a['f']['properties'],'review_status':'unreviewed','consolidation':dict(version=VERSION,
|
||||
source_ids=a['ids'],inferred_gaps=a['gaps'],max_fit_deviation_m=.12,splines=curves)}
|
||||
output.append(dict(type='Feature',id='contour-'+ident,properties=props,geometry=dict(type='LineString',coordinates=coordinates)))
|
||||
progress(3,4)
|
||||
report.update(output_features=len(output),input_lines=len(lines),output_lines=len(output)-len(other),
|
||||
inferred_gap_m=round(sum(g['length_m'] for a in chains for g in a['gaps']),4),
|
||||
trimmed_overlap_m=round(report['trimmed_overlap_m'],3))
|
||||
result={**document,'features':output,'analysis':{**document.get('analysis',{}),'contour_refinement':{k:v for k,v in report.items() if k not in ('duplicates','removed_noise','joins')}}}
|
||||
progress(4,4)
|
||||
return result,report
|
||||
|
||||
|
||||
def refine_file(source, survey, output):
|
||||
from contour_evidence import SurveyEvidence
|
||||
output.mkdir(parents=True,exist_ok=True)
|
||||
def progress(done,total):
|
||||
p=output/'progress.json.tmp';p.write_text(json.dumps(dict(phase='refining',completed=done,total=total)));p.replace(output/'progress.json')
|
||||
import scipy, shapely
|
||||
payload=source.read_bytes()
|
||||
result,report=consolidate(json.loads(payload),SurveyEvidence(survey),progress)
|
||||
provenance=dict(raw_map_sha256=hashlib.sha256(payload).hexdigest(),
|
||||
libraries=dict(shapely=shapely.__version__,scipy=scipy.__version__,networkx=nx.__version__))
|
||||
report.update(provenance)
|
||||
result['analysis']['contour_refinement'].update(provenance)
|
||||
(output/'urban-map.json').write_text(json.dumps(result,ensure_ascii=False,allow_nan=False))
|
||||
(output/'contour-refinement.json').write_text(json.dumps(report,ensure_ascii=False,indent=2))
|
||||
print(json.dumps({k:v for k,v in report.items() if k not in ('duplicates','removed_noise','joins')}),flush=True)
|
||||
|
||||
|
||||
if __name__=='__main__':
|
||||
p=argparse.ArgumentParser()
|
||||
for name in ('source','survey','output'):p.add_argument('--'+name,type=Path,required=True)
|
||||
a=p.parse_args();refine_file(a.source,a.survey,a.output)
|
||||
@@ -0,0 +1,75 @@
|
||||
"""Run native VMA over the surveyed tiles, then assemble one metric map."""
|
||||
import argparse
|
||||
import json
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
from vector_map import assemble, digest
|
||||
|
||||
|
||||
def merge(index, documents, request):
|
||||
# Load geometry after the VMA runtime; this pinned GEOS/CUDA stack is order-sensitive.
|
||||
from shapely.geometry import box, shape, mapping
|
||||
features=[]
|
||||
for tile,document in documents:
|
||||
low,high=tile['core_bounds'];core=box(*low,*high)
|
||||
for f in document['features']:
|
||||
geom=shape(f['geometry'])
|
||||
if geom.geom_type=='Polygon':
|
||||
centre=geom.centroid
|
||||
if not low[0]<=centre.x<high[0] or not low[1]<=centre.y<high[1]:continue
|
||||
pieces=[geom]
|
||||
else:
|
||||
clipped=geom.intersection(core)
|
||||
pieces=[clipped] if clipped.geom_type=='LineString' else list(getattr(clipped,'geoms',[]))
|
||||
for j,piece in enumerate(pieces):
|
||||
if piece.is_empty or piece.geom_type not in ('Polygon','LineString'):continue
|
||||
if piece.geom_type=='LineString' and piece.length<.25:continue
|
||||
features.append({**f,'id':f"{tile['id']}-{f['id']}-{j}", 'geometry':json.loads(json.dumps(mapping(piece)))})
|
||||
if len(features)>20000:raise ValueError('Infrastructure result exceeds feature budget')
|
||||
# Known gaps are retained as coverage facts; they never become inferred roads.
|
||||
return dict(schema_version='missioncore.urban-map/v2',type='FeatureCollection',
|
||||
coordinate_system=dict(frame='scene-local',units='metres',up='Z',georeferenced=False),
|
||||
source={**request['source'], 'vma_commit':'a6e98e8f704e72499b33da84715ba39e8705e02e', 'weights':__import__('assets').WEIGHTS},coverage=dict(kind='objects-only',cell_m=.05,accepted_cells=0,extent_xy=index['bounds_xy']),
|
||||
analysis=dict(job_key=request['key'],provider_sha256=request['identity']['provider_sha256'],scope='whole-scene',
|
||||
tiles_total=len(index['tiles']),tiles_mapped=len(documents),tiles_without_ground=len(index['tiles'])-len(documents),
|
||||
tiles=[{k:v for k,v in t.items() if k!='job'} for t in index['tiles']]),
|
||||
review_status='unreviewed',features=features)
|
||||
|
||||
|
||||
def run(root,assets,package,survey=None):
|
||||
survey=survey or root
|
||||
request=json.loads((root/'request.json').read_text());index=json.loads((survey/'tile-index.json').read_text())
|
||||
from infer_vectors import main as infer
|
||||
documents=[]
|
||||
for i,tile in enumerate(index['tiles']):
|
||||
(root/'progress.json.tmp').write_text(json.dumps(dict(phase='vectorizing',completed=i,total=len(index['tiles']))))
|
||||
(root/'progress.json.tmp').replace(root/'progress.json')
|
||||
if tile['status']!='surveyed':continue
|
||||
folder=survey/tile['id'];out=root/tile['id']/'vectors';out.mkdir(parents=True,exist_ok=True)
|
||||
receipt=out/'vector-receipt.json'
|
||||
valid=False
|
||||
if receipt.exists():
|
||||
old=json.loads(receipt.read_text())
|
||||
valid=old['source']==digest(folder/'survey-receipt.json') and digest(out/'urban-map.json')==old['result']
|
||||
if not valid:
|
||||
sys.argv=['infer_vectors','--image',str(folder/'top.png'),'--assets',str(assets),'--output',str(out)]
|
||||
infer()
|
||||
assemble(SimpleNamespace(candidates=out/'candidates.json',job=folder/'job.json',image=folder/'top.png',
|
||||
geometry=folder/'top.geometry.npz',atlas=folder/'surface-atlas.npz',package=package,output=out))
|
||||
receipt.write_text(json.dumps(dict(source=digest(folder/'survey-receipt.json'),result=digest(out/'urban-map.json'))))
|
||||
documents.append((tile,json.loads((out/'urban-map.json').read_text())))
|
||||
result=merge(index,documents,request)
|
||||
raw=root/'urban-map.raw.json'
|
||||
raw.write_text(json.dumps(result,ensure_ascii=False,allow_nan=False))
|
||||
from refine_contours import refine_file
|
||||
refine_file(raw,survey,root)
|
||||
(root/'progress.json.tmp').write_text(json.dumps(dict(phase='assembling',completed=len(index['tiles']),total=len(index['tiles']))))
|
||||
(root/'progress.json.tmp').replace(root/'progress.json')
|
||||
result=json.loads((root/'urban-map.json').read_text())
|
||||
print(json.dumps(dict(features=len(result['features']),tiles=len(index['tiles']),mapped=len(documents))),flush=True)
|
||||
|
||||
if __name__=='__main__':
|
||||
p=argparse.ArgumentParser();p.add_argument('--root',type=Path,required=True);p.add_argument('--assets',type=Path,required=True);p.add_argument('--package',type=Path,required=True)
|
||||
p.add_argument('--survey',type=Path)
|
||||
a=p.parse_args();run(a.root,a.assets,a.package,a.survey)
|
||||
Reference in New Issue
Block a user