Add vector infrastructure maps and persistent location experience
This commit is contained in:
@@ -0,0 +1,6 @@
|
||||
*
|
||||
!Dockerfile
|
||||
!*.py
|
||||
!.build
|
||||
!.build/vma-source.tar.gz
|
||||
!.build/terrain.py
|
||||
@@ -0,0 +1,2 @@
|
||||
.build/
|
||||
__pycache__/
|
||||
@@ -0,0 +1,21 @@
|
||||
ARG BASE_IMAGE=ndc/mission-core-lab-v1-goose:sg3.2.0-cu117-v1
|
||||
FROM ${BASE_IMAGE}
|
||||
LABEL com.nodedc.product="mission-core" com.nodedc.stack="urban-mapping" com.nodedc.role="vector-extractor" com.nodedc.managed-by="compose"
|
||||
ENV PATH=/opt/conda/envs/goose/bin:$PATH PYTHONUNBUFFERED=1 OMP_NUM_THREADS=4 PYTHONDONTWRITEBYTECODE=1
|
||||
RUN python -m pip install --no-cache-dir numpy==1.23.5 yapf==0.40.1 \
|
||||
https://download.openmmlab.com/mmcv/dist/cu117/torch1.13.0/mmcv_full-1.7.0-cp39-cp39-manylinux1_x86_64.whl \
|
||||
mmdet==2.28.2 mmsegmentation==0.30.0 shapely==1.8.5.post1 \
|
||||
numba==0.57.1 scikit-image==0.19.3 scikit-learn==1.3.0 \
|
||||
nuscenes-devkit==1.1.9 lyft-dataset-sdk==0.0.8 plyfile==0.7.4 \
|
||||
trimesh==3.23.5 networkx==2.8.8 similaritymeasures==0.6.0 \
|
||||
gdown==5.2.0 einops==0.6.1 timm==0.6.13
|
||||
RUN python -m pip install --no-cache-dir --no-deps --no-build-isolation mmdet3d==1.0.0rc6
|
||||
ADD .build/vma-source.tar.gz /opt/
|
||||
ENV PYTHONPATH=/opt/VMA-a6e98e8f704e72499b33da84715ba39e8705e02e
|
||||
WORKDIR /opt/VMA-a6e98e8f704e72499b33da84715ba39e8705e02e
|
||||
RUN python -c "import torch,mmcv,mmdet,mmdet3d; import projects.mmdet3d_plugin; print(torch.__version__,mmcv.__version__,mmdet3d.__version__)"
|
||||
ENTRYPOINT ["/opt/conda/envs/goose/bin/python"]
|
||||
|
||||
COPY *.py /app/
|
||||
COPY .build/terrain.py /app/terrain.py
|
||||
ENV PYTHONPATH=/app:/opt/VMA-a6e98e8f704e72499b33da84715ba39e8705e02e
|
||||
@@ -0,0 +1,42 @@
|
||||
# Vector infrastructure module
|
||||
|
||||
Offline GPU batch container, separate from simulation and the Gaussian renderer.
|
||||
Qualified on Worker006, NVIDIA RTX4090 / Windows Docker WSL. No Mac inference.
|
||||
VMA source MIT, author repository https://github.com/hustvl/VMA, commit and public
|
||||
checkpoint hashes pinned in `assets.py`. Author code is loaded unchanged. The
|
||||
installed CUDA11.7 / Torch1.13.1 base is an explicit external image prerequisite;
|
||||
this is portability to a similarly provisioned NVIDIA worker, not arbitrary-host support.
|
||||
|
||||
Prepare source on the worker: `python prepare.py --source .build`. This also
|
||||
packages the canonical simulation GLB coordinate loader; it never forks it.
|
||||
Build with `DOCKER_BUILDKIT=0 docker compose build vectorizer` on Worker006.
|
||||
The environment workaround affects only this build command. Prepare public weights
|
||||
with the built image, explicit network enabled and only the model directory mounted:
|
||||
`python /app/prepare.py --weights /assets`. Runtime mounts in `compose.yaml` are
|
||||
read-only except outputs; inference runs with network disabled.
|
||||
|
||||
Supply `VECTOR_INPUT`, `VECTOR_ASSETS`, `VECTOR_PACKAGE`, `VECTOR_OUTPUT`. Run
|
||||
`docker compose run --rm vectorizer` for native 1000x1000 overlapping model crops.
|
||||
Then run the same service with `/app/vector_map.py --candidates /output/candidates.json
|
||||
--job /input/job.json --image /input/crossing-top.png --geometry
|
||||
/input/crossing-top.geometry.npz --atlas /input/surface-atlas.npz --package /package
|
||||
--output /output`. Input images, calibration, observed ground atlas and job come
|
||||
from the parent mapping module. Use the parent `atlas.export_dxf` for XYZ DXF.
|
||||
The measured source and collider revisions remain attached to every product.
|
||||
|
||||
Outputs are line objects and polygon footprints, not contours of every mask pixel.
|
||||
The upstream decoder's automatic threshold relaxation is disabled. Fixed confidence
|
||||
and cross-crop suppression retain empty results. Actual visible stripe paint is fit
|
||||
only inside a model-detected zebra envelope; missing stripes are not invented.
|
||||
Heights are intersections with the original collider, checked against rendered
|
||||
visible ground. Missing/occluded sections stay open; the collider is never modified.
|
||||
All products remain observation-only, unreviewed, without route permission.
|
||||
|
||||
Accepted engineering scope: a visually inspected 60m crossing tile, two crossing
|
||||
areas and 14 stripe footprints. Arrow boxes are excluded: their paint geometry did not pass visual acceptance.
|
||||
Curbs remain partial, labels may be wrong, and
|
||||
Gaussian top views distort building sides. This is not a survey accuracy claim,
|
||||
complete city topology, building-footprint map, or a LiDAR360MLS equivalent.
|
||||
The same versioned module can process further tiles; each needs coverage and visual
|
||||
acceptance before using it as a planning constraint. The UI keeps Gaussian,
|
||||
collision, combined and vector-plan views in the existing scene.
|
||||
@@ -0,0 +1,7 @@
|
||||
"""Pinned public author releases; no private scene leaves the worker."""
|
||||
COMMIT = "a6e98e8f704e72499b33da84715ba39e8705e02e"
|
||||
ARCHIVE_SHA = "758fe52c4831d0a66dfd6578d789e63c8680e43a7d57ef9f51b5d6424d469b80"
|
||||
WEIGHTS = {
|
||||
"sd_line.pth": {"drive_id":"1hDmSJ8As5Ur-IF232knLBbjnlZZXV4PK", "sha256":"84c594317fea56118cb3e80aaf346f5eaa05c9a815c2b18022cece002ad9b54d"},
|
||||
"sd_box.pth": {"drive_id":"1Sy3fD6fVSSM2oFf11z3WaKC3LH6sRy_j", "sha256":"85010253a1619b8cf493da2353a7ff57908b4915366a580d38b02a633dfb062b"},
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
name: ndc-vector-mapping
|
||||
services:
|
||||
vectorizer:
|
||||
image: ndc-mission-core-vector-mapping:${VECTOR_VERSION:-vma3}
|
||||
build:
|
||||
context: .
|
||||
dockerfile: Dockerfile
|
||||
gpus: all
|
||||
cpus: 4
|
||||
mem_limit: 12g
|
||||
shm_size: 1g
|
||||
network_mode: none
|
||||
restart: "no"
|
||||
labels:
|
||||
com.nodedc.product: mission-core
|
||||
com.nodedc.stack: urban-mapping
|
||||
com.nodedc.role: vector-extractor
|
||||
com.nodedc.managed-by: compose
|
||||
volumes:
|
||||
- ${VECTOR_INPUT:?set rendered tile directory}:/input:ro
|
||||
- ${VECTOR_ASSETS:?set pinned model directory}:/assets:ro
|
||||
- ${VECTOR_PACKAGE:?set exact world package}:/package:ro
|
||||
- ${VECTOR_OUTPUT:?set result directory}:/output
|
||||
command: ["/app/infer_vectors.py", "--image", "/input/crossing-top.png", "--assets", "/assets", "--output", "/output"]
|
||||
@@ -0,0 +1,73 @@
|
||||
"""Bounded native VMA inference; no resampling, forced detections or route authority."""
|
||||
import argparse, hashlib, json, time
|
||||
from pathlib import Path
|
||||
import numpy as np
|
||||
import torch
|
||||
import mmcv
|
||||
from mmcv.runner import load_checkpoint
|
||||
from mmdet3d.models import build_model
|
||||
from PIL import Image
|
||||
import projects.mmdet3d_plugin # registers the authors' detector unchanged
|
||||
|
||||
|
||||
def sha(path):
|
||||
h=hashlib.sha256()
|
||||
with Path(path).open('rb') as stream:
|
||||
for block in iter(lambda:stream.read(8*1024**2),b''):h.update(block)
|
||||
return h.hexdigest()
|
||||
|
||||
|
||||
def main():
|
||||
p=argparse.ArgumentParser();p.add_argument('--image',type=Path,required=True)
|
||||
p.add_argument('--assets',type=Path,required=True);p.add_argument('--output',type=Path,required=True)
|
||||
p.add_argument('--kinds',nargs='+',choices=['line','box'],default=['line','box'])
|
||||
p.add_argument('--threshold',type=float,default=.3)
|
||||
args=p.parse_args();args.output.mkdir(parents=True,exist_ok=True)
|
||||
assert 0 < args.threshold <= 1, 'Invalid score threshold'
|
||||
assert torch.cuda.is_available(),'GPU worker required'
|
||||
torch.set_num_threads(4)
|
||||
rgb=np.asarray(Image.open(args.image).convert('RGB'))
|
||||
h,w=rgb.shape[:2]
|
||||
assert 1000<=w<=4000 and 1000<=h<=4000,'Bounded native 1000-pixel crops required'
|
||||
# Native model inputs are 1000x1000. Overlap keeps edge objects observable.
|
||||
positions=[(x,y) for y in sorted(set([*range(0,h-999,800),h-1000]))
|
||||
for x in sorted(set([*range(0,w-999,800),w-1000]))]
|
||||
from assets import WEIGHTS
|
||||
manifest=WEIGHTS
|
||||
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()
|
||||
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.
|
||||
mean=image.new_tensor([.485,.456,.406])[:,None,None]
|
||||
std=image.new_tensor([.229,.224,.225])[:,None,None]
|
||||
with torch.inference_mode():
|
||||
result=model(return_loss=False,rescale=True,img=((image-mean)/std)[None],
|
||||
img_metas=[dict(img_shape=(1000,1000))])[0]['pts_bbox']
|
||||
for i,score in enumerate(result['scores_3d'].tolist()):
|
||||
if score<args.threshold:continue
|
||||
label=int(result['labels_3d'][i]);points=result['pts_3d'][i].tolist()
|
||||
points=[[a+x,b+y] for a,b in points]
|
||||
predictions.append(dict(kind=kind,class_name=cfg.map_classes[label],score=score,
|
||||
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,
|
||||
elapsed_seconds=timings,authority='unreviewed-observations',features=predictions)
|
||||
(args.output/'candidates.json').write_text(json.dumps(doc,indent=2,allow_nan=False))
|
||||
print(json.dumps(dict(features=len(predictions),elapsed=timings)),flush=True)
|
||||
|
||||
if __name__=='__main__':main()
|
||||
@@ -0,0 +1,32 @@
|
||||
"""Explicit worker-only preparation, separate from network-isolated inference."""
|
||||
import argparse, hashlib, json, urllib.request
|
||||
from pathlib import Path
|
||||
from assets import COMMIT, ARCHIVE_SHA, WEIGHTS
|
||||
|
||||
def digest(path):
|
||||
h=hashlib.sha256()
|
||||
with path.open('rb') as f:
|
||||
for chunk in iter(lambda:f.read(8388608),b''):h.update(chunk)
|
||||
return h.hexdigest()
|
||||
|
||||
def acquire(path, expected, download):
|
||||
path.parent.mkdir(parents=True,exist_ok=True)
|
||||
if path.exists() and digest(path)==expected:return
|
||||
part=path.with_suffix(path.suffix+'.partial')
|
||||
download(part)
|
||||
if digest(part)!=expected:
|
||||
part.unlink(missing_ok=True);raise ValueError('Downloaded artifact hash mismatch')
|
||||
part.replace(path)
|
||||
|
||||
if __name__=='__main__':
|
||||
p=argparse.ArgumentParser();p.add_argument('--source',type=Path);p.add_argument('--weights',type=Path);a=p.parse_args()
|
||||
if a.source:
|
||||
import shutil
|
||||
a.source.mkdir(parents=True,exist_ok=True)
|
||||
shutil.copy2(Path(__file__).resolve().parents[2]/'ai-polygon/terrain.py',a.source/'terrain.py')
|
||||
acquire(a.source/'vma-source.tar.gz',ARCHIVE_SHA,lambda path:urllib.request.urlretrieve('https://codeload.github.com/hustvl/VMA/tar.gz/'+COMMIT,path))
|
||||
if a.weights:
|
||||
import gdown
|
||||
for name, item in WEIGHTS.items():
|
||||
acquire(a.weights/name,item['sha256'],lambda path:gdown.download(id=item['drive_id'],output=str(path),quiet=False))
|
||||
(a.weights/'manifest.json').write_text(json.dumps(WEIGHTS,indent=2))
|
||||
@@ -0,0 +1,38 @@
|
||||
"""Exact vertical intersections with the existing metric collider, bounded to a tile."""
|
||||
import math
|
||||
from collections import defaultdict
|
||||
import numpy as np
|
||||
from terrain import load_glb
|
||||
|
||||
|
||||
class ColliderHeight:
|
||||
def __init__(self,path,rotation,bounds,plane):
|
||||
vertices,faces=load_glb(path,rotation)
|
||||
triangles=vertices[faces];lo=triangles[:,:,:2].min(1);hi=triangles[:,:,:2].max(1)
|
||||
bounds=np.asarray(bounds,float);centre=triangles.mean(1)
|
||||
expected=np.column_stack([centre[:,:2],np.ones(len(centre))])@plane
|
||||
normal=np.cross(triangles[:,1]-triangles[:,0],triangles[:,2]-triangles[:,0])
|
||||
admit=((hi>=bounds[0]-1)&(lo<=bounds[1]+1)).all(1)&(np.abs(centre[:,2]-expected)<=.75)
|
||||
admit&=np.abs(normal[:,2])>np.linalg.norm(normal,axis=1)*.5
|
||||
self.triangles=triangles[admit];self.cells=defaultdict(list)
|
||||
for index,triangle in enumerate(self.triangles):
|
||||
low=np.maximum(np.floor(triangle[:,:2].min(0)),np.floor(bounds[0]-1)).astype(int)
|
||||
high=np.minimum(np.floor(triangle[:,:2].max(0)),np.ceil(bounds[1]+1)).astype(int)
|
||||
for x in range(low[0],high[0]+1):
|
||||
for y in range(low[1],high[1]+1):self.cells[(x,y)].append(index)
|
||||
if not len(self.triangles):raise ValueError('No collider ground in mapping tile')
|
||||
|
||||
def sample(self,xy,reference):
|
||||
heights=np.full(len(xy),np.nan)
|
||||
for i,(x,y) in enumerate(xy):
|
||||
ids=self.cells.get((math.floor(x),math.floor(y)),[])
|
||||
if not ids:continue
|
||||
tri=self.triangles[ids];a,b,c=tri[:,0],tri[:,1],tri[:,2]
|
||||
den=(b[:,1]-c[:,1])*(a[:,0]-c[:,0])+(c[:,0]-b[:,0])*(a[:,1]-c[:,1])
|
||||
okay=np.abs(den)>1e-9;a,b,c,den=a[okay],b[okay],c[okay],den[okay]
|
||||
u=((b[:,1]-c[:,1])*(x-c[:,0])+(c[:,0]-b[:,0])*(y-c[:,1]))/den
|
||||
v=((c[:,1]-a[:,1])*(x-c[:,0])+(a[:,0]-c[:,0])*(y-c[:,1]))/den
|
||||
inside=(u>=-1e-6)&(v>=-1e-6)&(u+v<=1+1e-6)
|
||||
z=(u*a[:,2]+v*b[:,2]+(1-u-v)*c[:,2])[inside]
|
||||
if len(z):heights[i]=z[np.argmin(np.abs(z-reference[i]))]
|
||||
return heights
|
||||
@@ -0,0 +1,167 @@
|
||||
"""Metric object assembly from VMA; private raster evidence stays on the worker.
|
||||
|
||||
The height reference rejects non-ground projections, it never edits the collider.
|
||||
Unknown/occluded sections are split, not filled with an invented road surface.
|
||||
"""
|
||||
import argparse, json, hashlib
|
||||
from pathlib import Path
|
||||
import numpy as np
|
||||
import cv2
|
||||
from PIL import Image
|
||||
from shapely.geometry import LineString, Polygon
|
||||
from scipy.ndimage import median_filter
|
||||
|
||||
CLASS_MAP={'curb':'curb','lane':'road_marking','stopline':'road_marking','Crosswalk':'crosswalk_area'}
|
||||
|
||||
|
||||
def digest(path):
|
||||
h=hashlib.sha256()
|
||||
with Path(path).open('rb') as f:
|
||||
for b in iter(lambda:f.read(8388608),b''):h.update(b)
|
||||
return h.hexdigest()
|
||||
|
||||
|
||||
def select_objects(candidates):
|
||||
"""Class-aware overlap suppression, with provenance from all agreeing crops."""
|
||||
accepted=[]
|
||||
for item in sorted(candidates,key=lambda f:-f['score']):
|
||||
if item['class_name'] not in CLASS_MAP:continue
|
||||
p=np.asarray(item['points'],float)
|
||||
geom=Polygon(p[:4]) if item['kind']=='box' else LineString(p)
|
||||
if not geom.is_valid or geom.is_empty:continue
|
||||
duplicate=None
|
||||
for keep in accepted:
|
||||
if keep['kind']!=item['kind']:continue
|
||||
if item['kind']=='box' and keep['class_name']!=item['class_name']:continue
|
||||
other=keep['_geometry']
|
||||
if item['kind']=='box':
|
||||
match=geom.intersection(other).area/max(geom.union(other).area,1e-9)>.5
|
||||
else:
|
||||
match=(geom.intersection(other.buffer(2)).length>.85*geom.length
|
||||
and geom.length<=other.length*1.25)
|
||||
if match:duplicate=keep;break
|
||||
if duplicate is not None:
|
||||
duplicate['support_tiles'].append(item['tile_xy']);continue
|
||||
accepted.append({**item,'_geometry':geom,'support_tiles':[item['tile_xy']]})
|
||||
return accepted
|
||||
|
||||
|
||||
class HeightLift:
|
||||
def __init__(self,geometry,atlas):
|
||||
self.depth=median_filter(geometry['depth'],size=3)
|
||||
self.alpha=geometry['alpha'];self.k=geometry['intrinsics'];self.inverse=np.linalg.inv(geometry['view'])
|
||||
self.height,self.width=self.depth.shape
|
||||
# Robust height envelope fitted only to already observed ground returns.
|
||||
z=atlas['z'];rr,cc=np.where(np.isfinite(z))
|
||||
assert len(rr)>=100,'Insufficient observed ground reference'
|
||||
cell=float(atlas['cell_m']);bounds=atlas['bounds'];h=z.shape[0]
|
||||
x=bounds[0,0]+(cc+.5)*cell;y=bounds[0,1]+(h-rr-.5)*cell
|
||||
a=np.column_stack([x,y,np.ones(len(x))]);keep=np.ones(len(x),bool)
|
||||
for _ in range(4):
|
||||
self.plane=np.linalg.lstsq(a[keep],z[rr[keep],cc[keep]],rcond=None)[0]
|
||||
residual=np.abs(a@self.plane-z[rr,cc]);keep=residual<=max(.15,3*float(np.median(residual)))
|
||||
self.reference_xy=np.column_stack([x[keep],y[keep]])
|
||||
self.collider=None
|
||||
|
||||
def lift(self,pixels):
|
||||
p=np.asarray(pixels,float);c=np.clip(np.rint(p[:,0]).astype(int),0,self.width-1);r=np.clip(np.rint(p[:,1]).astype(int),0,self.height-1)
|
||||
xy=(p+.5-self.k[:2,2])/np.diag(self.k)[:2]
|
||||
xyz=np.column_stack([xy,self.depth[r,c],np.ones(len(p))])@self.inverse.T
|
||||
residual=np.abs(xyz[:,2]-np.column_stack([xyz[:,:2],np.ones(len(p))])@self.plane)
|
||||
valid=(self.alpha[r,c]>=.5)&(residual<=.75)&np.isfinite(xyz).all(1)
|
||||
if self.collider is not None:
|
||||
heights=self.collider.sample(xyz[:,:2],xyz[:,2])
|
||||
valid&=np.isfinite(heights)&(np.abs(heights-xyz[:,2])<=.5)
|
||||
xyz[:,2]=heights
|
||||
valid&=(p[:,0]>=0)&(p[:,0]<self.width)&(p[:,1]>=0)&(p[:,1]<self.height)
|
||||
return xyz[:,:3],valid
|
||||
|
||||
|
||||
def paint_stripes(rgb,quad):
|
||||
"""Fit only visible stripe paint within a detected crossing envelope."""
|
||||
quad=np.asarray(quad[:4],np.float32)
|
||||
width=int(round(np.linalg.norm(quad[3]-quad[0])));height=int(round(np.linalg.norm(quad[1]-quad[0])))
|
||||
if min(width,height)<10:return []
|
||||
dest=np.float32([[0,0],[0,height-1],[width-1,height-1],[width-1,0]])
|
||||
transform=cv2.getPerspectiveTransform(quad,dest)
|
||||
crop=cv2.warpPerspective(rgb,transform,(width,height))
|
||||
gray=cv2.cvtColor(crop,cv2.COLOR_RGB2GRAY)
|
||||
# Work on actual brightness, rejecting shadow/scan gaps and thin dashed edges.
|
||||
_,mask=cv2.threshold(gray,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)
|
||||
mask=cv2.morphologyEx(mask,cv2.MORPH_OPEN,np.ones((2,2),np.uint8))
|
||||
contours,_=cv2.findContours(mask,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
|
||||
boxes=[]
|
||||
for contour in contours:
|
||||
rect=cv2.minAreaRect(contour);a,b=sorted(rect[1]);area=cv2.contourArea(contour)
|
||||
if not (a>=2 and b>=.55*min(width,height) and b/a>=3 and area/max(a*b,1)>=.5):continue
|
||||
corners=cv2.boxPoints(rect)
|
||||
corners=cv2.perspectiveTransform(corners[None],np.linalg.inv(transform))[0]
|
||||
boxes.append(corners.tolist())
|
||||
# A single white fragment cannot establish a zebra pattern.
|
||||
return boxes if len(boxes)>=3 else []
|
||||
|
||||
|
||||
def assemble(args):
|
||||
candidates=json.loads(args.candidates.read_text());job=json.loads(args.job.read_text())
|
||||
assert digest(args.image)==candidates['source_image_sha256'],'Different source image'
|
||||
rgb=np.asarray(Image.open(args.image).convert('RGB'));lift=HeightLift(np.load(args.geometry),np.load(args.atlas))
|
||||
from surface_height import ColliderHeight
|
||||
terrain=json.loads((args.package/'terrain.json').read_text())
|
||||
name=job['source']['collider_sha256']+'.decoded.glb'
|
||||
meta=json.loads((args.package/name.replace('.glb','.json')).read_text())
|
||||
assert meta['source_sha256']==job['source']['collider_sha256']
|
||||
assert digest(args.package/name)==meta['sha256'],'Collider hash mismatch'
|
||||
lift.collider=ColliderHeight(args.package/name,terrain['collision_rotation'],job['bounds_xy'],lift.plane)
|
||||
features=[];rejected=[]
|
||||
def add(item,pixels,kind,cls,role):
|
||||
xyz,valid=lift.lift(pixels)
|
||||
if kind=='Polygon':
|
||||
if not valid.all():return
|
||||
rings=[np.vstack([xyz,xyz[0]]).round(4).tolist()]
|
||||
else:
|
||||
rings=xyz.round(4).tolist()
|
||||
identifier=hashlib.sha256(json.dumps([cls,kind,rings],sort_keys=True).encode()).hexdigest()[:16]
|
||||
features.append(dict(type='Feature',id=identifier,properties=dict(
|
||||
**{'class':cls},authority='observation-only',route_permission='unassigned',
|
||||
source_class=item['class_name'],confidence=round(item['score'],4),
|
||||
geometry_role=role,review_status='unreviewed',height_source='collider-intersection-visual-ground-checked',
|
||||
support_tiles=item['support_tiles']),geometry=dict(type=kind,coordinates=rings)))
|
||||
objects=select_objects(candidates['features'])
|
||||
for item in objects:
|
||||
if item['kind']=='box':
|
||||
points=item['points'][:4]
|
||||
add(item,points,'Polygon',CLASS_MAP[item['class_name']],'object-envelope')
|
||||
if item['class_name']=='Crosswalk':
|
||||
for stripe in paint_stripes(rgb,points):
|
||||
add(item,stripe,'Polygon','crosswalk_marking','paint-footprint')
|
||||
continue
|
||||
curve=item['_geometry'].simplify(1.,preserve_topology=True)
|
||||
# Sample every <=5cm at the native 5cm/px image resolution before lifting.
|
||||
samples=np.array([curve.interpolate(d).coords[0] for d in np.linspace(0,curve.length,max(2,int(np.ceil(curve.length))+1))])
|
||||
xyz,valid=lift.lift(samples)
|
||||
# Split at missing/above-ground evidence; no across-gap extrapolation.
|
||||
segments=np.split(np.arange(len(samples)),np.flatnonzero(np.diff(valid.astype(int)))+1)
|
||||
for segment in segments:
|
||||
if len(segment)<2 or not valid[segment].all():continue
|
||||
segment_xyz=xyz[segment]
|
||||
if np.linalg.norm(np.diff(segment_xyz[:,:2],axis=0),axis=1).sum()<1.:continue
|
||||
# Metric simplification after height validation retains native shape.
|
||||
simplified=LineString(segment_xyz[:,:2]).simplify(.05)
|
||||
indices=[segment[np.argmin(np.linalg.norm(segment_xyz[:,:2]-xy,axis=1))] for xy in simplified.coords]
|
||||
add(item,samples[indices],'LineString',CLASS_MAP[item['class_name']],'boundary' if item['class_name']=='curb' else 'paint-axis')
|
||||
doc=dict(schema_version='missioncore.urban-map/v2',type='FeatureCollection',
|
||||
coordinate_system=dict(frame='scene-local',units='metres',up='Z',georeferenced=False),
|
||||
source=dict(world_sha256=job['source']['world_sha256'],collider_sha256=job['source']['collider_sha256'],
|
||||
image_sha256=candidates['source_image_sha256'],vma_commit=candidates['vma_commit'],weights=candidates['weights']),
|
||||
coverage=dict(cell_m=float(1/lift.k[0,0]),accepted_cells=0,kind='objects-only',extent_xy=job['bounds_xy']),
|
||||
review_status='unreviewed',features=features)
|
||||
args.output.mkdir(parents=True,exist_ok=True)
|
||||
(args.output/'urban-map.json').write_text(json.dumps(doc,ensure_ascii=False,allow_nan=False,indent=2))
|
||||
(args.output/'assembly.json').write_text(json.dumps(dict(raw_candidates=len(candidates['features']),objects=len(objects),
|
||||
features=len(features),ground_reference_plane=lift.plane.tolist()),indent=2))
|
||||
print(json.dumps(dict(features=len(features),classes={c:sum(f['properties']['class']==c for f in features) for c in set(f['properties']['class'] for f in features)})),flush=True)
|
||||
|
||||
if __name__=='__main__':
|
||||
p=argparse.ArgumentParser()
|
||||
for name in ['candidates','job','image','geometry','atlas','package','output']:p.add_argument('--'+name,type=Path,required=True)
|
||||
assemble(p.parse_args())
|
||||
Reference in New Issue
Block a user