Preserve offline geometry, marking, replay and evaluation pipelines with source manifests and synthetic tests. Research qualification does not activate these methods as production navigation.
84 lines
5.0 KiB
Python
84 lines
5.0 KiB
Python
"""Bootstrap the existing Gaussian orthophoto adapter from original scan poses.
|
|
|
|
Uniform 40 m grid with 10 m overlap, within 20 m of the scanner path. Gaussian
|
|
RGB/expected depth supplies the terrain samples. No collider or point cloud.
|
|
The broad scanner-relative cut is only a bootstrap; ortho_terrain performs the
|
|
existing independent height/frame admission before the production observation.
|
|
"""
|
|
from pathlib import Path
|
|
import json, math, time, gc
|
|
import numpy as np
|
|
import torch
|
|
from scipy.spatial import cKDTree
|
|
from plyfile import PlyData
|
|
from PIL import Image
|
|
from gsplat import rasterization
|
|
from mapping import camera, digest
|
|
from coordinate_cache import transformed
|
|
from survey_grid import corridor_cells
|
|
|
|
R=Path('/blind'); S=Path('/base_survey'); S.mkdir(exist_ok=True)
|
|
request=json.loads((R/'request.json').read_text())
|
|
pose_path=R/'poses.json'
|
|
poses=np.asarray([p['T']for p in json.loads(pose_path.read_text())['poses']],float)
|
|
assert poses.ndim==2 and poses.shape[1]==3 and np.isfinite(poses).all()
|
|
source=Path('/input')/request['source']['ply']
|
|
assert digest(source)==request['source']['sha256']
|
|
T=np.asarray(request['source']['source_to_world'],float)
|
|
data=PlyData.read(source,mmap='r')['vertex'].data
|
|
assert all(n in data.dtype.names for n in ['opacity','rot_0','scale_0','f_dc_0'])
|
|
world=transformed(data,T,str(source),proof_path=S/'coordinate-cache-proof.json')
|
|
tree=cKDTree(poses[:,:2]); relative=np.empty(len(data),np.float32);distance=relative.copy()
|
|
for begin in range(0,len(data),250000):
|
|
p=world[begin:begin+250000];dd,ix=tree.query(p[:,:2]);distance[begin:begin+len(p)]=dd
|
|
relative[begin:begin+len(p)]=p[:,2]-poses[ix,2]
|
|
origin=np.floor((poses[:,:2].min(0)-20)/40)*40
|
|
extent=np.ceil((poses[:,:2].max(0)+20-origin)/40).astype(int)
|
|
cells=corridor_cells(poses[:,:2],origin,extent)
|
|
tiles=[];start=time.monotonic()
|
|
rest=sorted([n for n in data.dtype.names if n.startswith('f_rest_')],key=lambda n:int(n.split('_')[-1]))
|
|
for ix,iy in cells:
|
|
lo=origin+np.array([ix,iy])*40;hi=lo+40;centre=(lo+hi)/2
|
|
close=np.linalg.norm(np.maximum(np.maximum(lo-poses[:,:2],poses[:,:2]-hi),0),axis=1)<=20
|
|
if not close.any():continue
|
|
bounds=np.array([lo-10,hi+10]);name=f'tile-{ix:03d}-{iy:03d}'
|
|
mask=((world[:,:2]>=bounds[0]-10)&(world[:,:2]<=bounds[1]+10)).all(1)
|
|
mask&=(distance<=30)&(relative>=-3.0)&(relative<=.25)
|
|
d=data[mask].copy()
|
|
if len(d)<100:continue
|
|
top_z=float(poses[close,2].max()+25)
|
|
spec=dict(id='top',projection='ortho',size=[600,600],width_m=60,
|
|
eye=[*centre,top_z],target=[*centre,top_z-1],up=[0,1,0])
|
|
def tensor(names):return torch.tensor(np.column_stack([d[n]for n in names]),device='cuda',dtype=torch.float32)
|
|
means=tensor(['x','y','z']);quats=tensor([f'rot_{i}'for i in range(4)])
|
|
scales=tensor([f'scale_{i}'for i in range(3)]).exp();opacity=tensor(['opacity']).squeeze(-1).sigmoid()
|
|
dc=tensor([f'f_dc_{i}'for i in range(3)])[:,None,:]
|
|
sh=torch.cat([dc,tensor(rest).reshape(len(d),3,-1).transpose(1,2)],dim=1)if rest else dc
|
|
view,k=camera(spec)
|
|
with torch.inference_mode():
|
|
rgbd,aa,_=rasterization(means,quats,scales,opacity,sh,
|
|
torch.tensor(view@T,device='cuda',dtype=torch.float32)[None],torch.tensor(k,device='cuda')[None],
|
|
600,600,sh_degree=int(math.sqrt(sh.shape[1]))-1,camera_model='ortho',render_mode='RGB+ED',packed=True)
|
|
rgbd=rgbd[0].cpu().numpy();aa=aa[0,:,:,0].cpu().numpy()
|
|
z=np.where(aa>.8,view[2,3]-rgbd[:,:,3],np.nan)
|
|
if np.isfinite(z).sum()<100:
|
|
del means,quats,scales,opacity,dc,sh,rgbd,aa,d;gc.collect();torch.cuda.empty_cache();continue
|
|
folder=S/name;folder.mkdir(exist_ok=True)
|
|
rgbd[:,:,:3]+=1-aa[:,:,None]
|
|
Image.fromarray(np.uint8(np.clip(rgbd[:,:,:3],0,1)*255)).save(folder/'bootstrap.png')
|
|
np.savez_compressed(folder/'surface-atlas.npz',z=z.astype(np.float32),bounds=bounds,cell_m=.1)
|
|
spec['size']=[1200,1200]
|
|
job=dict(schema_version='missioncore.urban-mapping-job/v1',source=request['source'],bounds_xy=bounds.tolist(),views=[spec])
|
|
(folder/'job.json').write_text(json.dumps(job))
|
|
tiles.append(dict(id=name,status='surveyed',core_bounds=[lo.tolist(),hi.tolist()],bounds_xy=bounds.tolist()))
|
|
print(json.dumps(dict(stage='pose-survey',tiles=len(tiles),name=name,ground_pixels=int(np.isfinite(z).sum()))),flush=True)
|
|
del means,quats,scales,opacity,dc,sh,rgbd,aa,d;gc.collect();torch.cuda.empty_cache()
|
|
if not tiles:raise ValueError('No Gaussian ground supports the native trajectory frame')
|
|
(S/'tile-index.json').write_text(json.dumps(dict(tiles=tiles,bounds_xy=[poses[:,:2].min(0).tolist(),poses[:,:2].max(0).tolist()])))
|
|
(S/'request.json').write_text(json.dumps(request))
|
|
(S/'bootstrap-report.json').write_text(json.dumps(dict(tiles=len(tiles),poses=len(poses),seconds=time.monotonic()-start,
|
|
source_sha256=digest(source),poses_sha256=digest(pose_path),manual_rois=[],
|
|
surface_source='Gaussian expected depth only; broad scanner-relative pre-cut [-3,+.25]m',
|
|
camera_planning='uniform 40m grid / 10m halo within 20m of original scanner positions',
|
|
frame_admission='pending existing ortho_terrain validation'),indent=2))
|