Orbit around the Volvo yourself
Explore one persistent 3D scene reconstructed from RGB. Scene, vehicle and detection data load only when requested; RGB previews load one camera frame at a time.
RGB only · 3DGSDrag: orbit · Scroll/pinch: zoom · Right drag: pan
PandaSet: Scale AI / Hesai · Volvo S90: lazercar, CC BY 4.0 · Sources and terms
The RGB clip is reconstructed offline; viewpoint changes are interactive in your browser. Scale is relative and surrounding traffic is part of a static scene. The Volvo is a separately rendered foreground 3D reference.
Turn ordinary camera frames into a persistent 3D road scene, then drag to look around a Volvo S90 reference. Start with the interactive example and its mouse-control recording. The GPU workflow accepts RGB pixels only and estimates camera calibration, camera poses and geometry from those images.
Pipeline identity: this lab directly runs standalone NVIDIA 3DGRUT/3DGUT, with Mask R-CNN for source-RGB perception. The separate NuRec + Harmonizer + Alpamayo comparison and RGB + LiDAR NuRec experiment use different pipelines. Their model calls are not part of this viewer.
How it works
- InputStart from RGB pixels
162 JPEGs · uint8[H,W,3] → feature matchesThe input guard excludes depth, LiDAR, supplied calibration, GPS and camera poses.
- ProcessRecover cameras, then learn the scene
COLMAP K[3,3] + poses[4,4] + XYZ → 400k GaussiansNVIDIA 3DGUT learns a static scene on one RTX 5090. RGB alone leaves global scale ambiguous.
- OutputRecognize real road users
RGB → class, score, bbox and instance mask → approximate contactMask R-CNN runs on actual photos. Markers use an RGB road-plane assumption; model scores are not measured accuracy.
- Move the viewing camera
Mouse drag → camera change → new-view RGBSpark renders the same 3D scene. The Volvo is a real mesh reference; the replay path comes from estimated cameras.
1. How can images describe a 3D road?
One pixel gives color, not distance. COLMAP finds distinctive image patches, matches the same features in overlapping photos, and estimates camera locations and 3D points that explain those matches. Bundle adjustment refines the estimates to reduce the distance between observed image features and their projected 3D points.
The example uses 162 RGB images from six camera directions. Each image is at most 1024 pixels wide. The input folder contains JPEG pixels; original EXIF, provided intrinsics, sensor poses, depth, GPS, IMU and LiDAR are excluded. The downloader selects camera JPEGs and the original license file, without fetching other sensor files.
RGB: uint8[height,width,3]
Matched feature locations: pixel pairs across overlapping images
Estimated camera K: float[3,3]
Estimated camera pose: float[4,4]
Triangulated sparse points: float[N,3] + RGB
K contains pixel focal lengths and the image's optical center. A pose places a camera in the reconstructed world. Camera axes are right/down/forward; the viewer aligns the estimated road to a Z-up display. The full values are in cameras.json.
The recorded example connected all 162 images and recovered about 29,000 sparse points. Its reprojection error is an image-consistency measurement, not a claim of centimeter-level road accuracy. Camera poses are estimated from RGB, not copied from the dataset.
Here is one actual undistorted front-camera frame. K is in pixels; camera_position uses normalized viewer units. Its near-zero x/y is the display origin around the middle capture, not a GPS reading. The height 0.9482 is relative to the median camera height normalized to 1.
{
"image": "front_camera/39.jpg",
"time_seconds": 3.9,
"K": [
[
1055.495,
0.0,
512.0
],
[
0.0,
1056.31,
284.5
],
[
0.0,
0.0,
1.0
]
],
"image_size": [
1024,
569
],
"camera_position": [
-0.0,
0.0,
0.9482
]
}
2. What does NVIDIA 3DGUT learn?
NVIDIA's open-source 3DGRUT provides the 3DGUT renderer and training workflow. It initializes from the RGB-derived COLMAP points and optimizes many small colored 3D ellipsoids: Gaussians. Their positions, scales, rotations, opacity and view-dependent color are adjusted so rendered views resemble the input photos.
This preset runs 16,000 iterations and keeps 400,000 Gaussians. The full PLY contains degree-3 spherical-harmonic color; the roughly 7.8 MB SPZ preview retains all Gaussians with degree-1 color. It is a compressed 3D scene, not a collection of pre-rendered camera angles. No pretrained depth model or gated neural-model weights are needed.
All images contribute to camera recovery. A photometric train/validation split exists inside 3DGRUT, but the saved example is not an independent novel-view benchmark. Moving traffic is baked into a static scene and can produce ghosts or streaks. Unknown or occluded surfaces can be incomplete.
3. What happens when I drag or replay the path?
Spark projects and blends the same Gaussians for the current browser camera. Dragging changes that camera in 3D; zooming changes its distance, and panning shifts its target. A different view therefore reveals actual parallax, gaps and occlusion artifacts in the reconstruction.
The Volvo S90 Recharge is a real 3D mesh by lazercar, simplified to a roughly 1 MB GLB with credited CC BY 4.0 rights. It is an added foreground position reference, with its own camera-dependent perspective. It does not identify the collection vehicle. Its foreground rendering and display shadow do not validate interactions with surrounding objects.
The path slider follows camera motion estimated by COLMAP. It does not invoke a driving policy or apply steering controls. The Driver button hides the reference mesh and uses the estimated front camera's pose and field of view.
Uncalibrated RGB has an unknown global scale. The viewer normalizes estimated camera-to-road height to one display unit and gives the car a relative display size. Its road plane is fitted to triangulated RGB feature tracks, not LiDAR. These units are not measured meters.
4. Recognize cars and pedestrians in the actual RGB
The new perception stage runs TorchVision Mask R-CNN ResNet50 FPN v2, COCO_V1, on the undistorted camera photos. Its backbone extracts image features, region proposals select candidate objects, and separate heads predict a class, confidence score, bounding box and instance mask. No dataset object annotations are read.
RGB uint8[H,W,3] → float32[3,H,W] in [0,1] → CUDA inference
boxes: float[N,4] in original undistorted-image pixels
labels: int64[N] e.g. person, car, truck
scores: float[N] model confidence, not calibrated accuracy
masks: float[N,1,H,W] → mask > 0.5 → cropped binary raster → RLE
The demo keeps scores ≥ 0.8 and six road-user classes: person, car, truck, bus, bicycle and motorcycle. Here is a real pedestrian prediction from the left camera:
{
"image": "left_camera/39.jpg",
"class": "person",
"score": 0.9982,
"bbox_xyxy": [
274.1,
316.64,
294.92,
364.5
],
"cropped_mask_size": [
21,
49
],
"contact_pixel": [
280.0,
363.0
],
"estimated_ground_xyz": [
-5.95426,
11.1151,
0.0
]
}
The box is about 21×48 pixels; the saved mask is a cropped 21×49 binary raster, not a full-image mask. Alternating zero/one run lengths compress it for the browser. The model's 0.9982 score does not establish that its prediction is correct. Missed objects and false detections remain possible.
How does that become a 3D marker? Take a pixel near the bottom of the predicted mask, cast a ray using COLMAP's estimated K and camera pose, and intersect it with the RGB-derived road plane. This supplies an approximate contact point, in relative viewer units. It is not a learned 3D bounding box, measured distance or ground-truth object pose. Horizon rays, far intersections and edge-truncated objects remain 2D-only. Sidewalk height, slopes, occlusion and mask errors can shift the marker.
The six views are paired by nominal frame number; supplied sensor timestamps and calibration are excluded. Nearby cross-camera estimates are merged, and a short class/position association assigns temporary IDs. These IDs may switch and are not identities, measured velocities or unique-object counts. The UI uses class labels and draws at most 24 nearby markers; highlighted labels follow the selected source camera. Overlay markers do not establish correct physical occlusion.
Use Recognition on/off to compare the original RGB with the predictions. Switch camera direction to inspect the source evidence. Cyan marks vehicles; amber marks people; purple marks cycles. The RGB panel and 3D markers advance with the same capture-frame selection. The background remains one static Gaussian reconstruction, so its moving-traffic ghosts do not disappear when the detection time changes.
Tesla's official driving-visualization documentation informs the ego-centered presentation and emphasis on surrounding road users. This lab combines separately inspectable reconstruction and detection stages; it does not reproduce Tesla's proprietary network, Reality View internals or driving-control system.
First time? Get the lab files
Open a terminal on the NVIDIA GPU machine for GPU labs, or on your own computer for CPU-only steps. Press Enter after each line. You can copy a multi-line command block as a whole.
cd "$HOME"
git clone https://github.com/james-joobs/awesome-nvidia-physical-ai.git
cd awesome-nvidia-physical-ai
pwd
This example clones into your home folder. If you already cloned the repo, skip git clone and enter your project folder. In each new terminal, check that pwd ends in awesome-nvidia-physical-ai so commands can find the labs/ files.
Run the lab
1. Explore the saved result without a CUDA GPU
Use the interactive viewer on this page or open the English mouse-control recording. The same scene supports rotation, zoom, pan, driver view and path replay. Your browser needs WebGL2 for 3D; viewing the MP4 and checking evidence do not require NVIDIA hardware.
python3 labs/rgb-reality-view/check.py
The checker verifies the RGB-only provenance, compressed model count, transforms, interaction trace and file hashes. Add --decode-video with FFmpeg installed to decode both complete recordings.
To open the bundled 3D scene locally without training, run this from the repository and visit http://127.0.0.1:8090/. The viewer uses pinned public JavaScript modules, so it needs an internet connection:
python3 labs/rgb-reality-view/serve.py --root site/public/showcase/rgb-reality-view
2. Prepare the GPU machine
The tested reconstruction machine runs Linux x86_64 with one RTX 5090 32 GB and about 32 GB system RAM. Install a working NVIDIA driver, CUDA 12.8 or 12.9 development toolkit, Python, a C++ compiler, uv, Git and Node.js/npm. The setup creates isolated Python environments and compiles only for compute capability 12.0. It does not replace system CUDA or other services.
Start with Linux GPU onboarding and the official uv installer if needed. In the repository terminal:
nvidia-smi
export RGB_VIEW_ROOT="$HOME/physical-ai-labs/rgb-road"
python3 labs/rgb-reality-view/pipeline.py --root "$RGB_VIEW_ROOT" setup
The first setup downloads several GB of dependencies and builds native extensions. Source commits and core package versions are pinned. If several toolkits are installed, the runner selects a compatible 12.8/12.9 directory; you can pass --cuda-home /path/to/cuda-12.9. The nvcc found first in your shell can be older than the toolkit actually needed for RTX 5090.
3. Reconstruct the public RGB example
Review the source and asset terms. The example is PandaSet scene 001 from a pinned unofficial community mirror. The original payload license and the different first-party CC BY-SA notice are preserved. Our new example scene and recordings carry CC BY-SA 4.0 and the original dataset terms; the source code's MIT license is separate.
For the complete workflow:
python3 labs/rgb-reality-view/pipeline.py --root "$RGB_VIEW_ROOT" all
Or run each stage so you can inspect its output:
python3 labs/rgb-reality-view/pipeline.py --root "$RGB_VIEW_ROOT" example
python3 labs/rgb-reality-view/pipeline.py --root "$RGB_VIEW_ROOT" sfm
python3 labs/rgb-reality-view/pipeline.py --root "$RGB_VIEW_ROOT" train
python3 labs/rgb-reality-view/pipeline.py --root "$RGB_VIEW_ROOT" export
python3 labs/rgb-reality-view/pipeline.py --root "$RGB_VIEW_ROOT" perceive
python3 labs/rgb-reality-view/pipeline.py --root "$RGB_VIEW_ROOT" serve
Open http://127.0.0.1:8090/ on that machine. When using a remote GPU host, forward the local viewer port from your own computer with ssh -L 8090:127.0.0.1:8090 your-gpu-host, then open the same local address. Replace your-gpu-host with your own SSH alias.
| Stage | Output | What to inspect |
|---|---|---|
| RGB example / ingest | work/images/, input-manifest.json |
JPEG files only; no supplied calibration or sensor data |
| COLMAP | sfm-result.json, sfm-selected/, undistorted/sparse/0/ |
Registered-image counts match the selected and undistorted models |
| 3DGUT | training-result.json, train/.../export_last.ply |
Completed iterations, observed runtime, sampled GPU memory |
| Viewer export | viewer/road.spz, cameras.json, volvo-s90.glb |
A single 3D model, RGB-derived camera path and separate car mesh |
Use a fresh output folder for a different capture. Do not replace this pipeline's COLMAP outputs with another lab's point cloud. The input guard rejects extra sidecars, altered files or a manifest declaring non-RGB sensor inputs.
4. Bring your own camera footage
For one RGB video, FFmpeg extracts frames and the same RGB-only stages recover its cameras. Start with overlapping, translated views of a mostly static road; spinning in place or filming textureless surfaces gives weak geometry.
python3 labs/rgb-reality-view/pipeline.py \
--root "$HOME/physical-ai-labs/my-road" \
--video "/absolute/path/to/road.mp4" --sample-fps 3 all
For synchronized surrounding camera streams, extract images into separate camera folders, then use --input /path/to/rgb-folders --front-folder front_camera all. The folder names group images by lens; no external calibration is required by this preset. A single forward-facing camera supports the surfaces it actually sees; rear or hidden regions need additional observations.
Check the result
The recorded sample uses 162 RGB frames, one RTX 5090, 16,000 training steps and 400,000 Gaussians. Input feature matching and camera recovery took about a minute; the reference training loop took about two minutes. Installation, first compilation, compression and browser loading are separate. Exact observed values and scope are in recorded.json.
python3 labs/rgb-reality-view/check.py --decode-video
The recording's mouse events are saved with before/after camera positions. They confirm that dragging changed the real 3D camera and path playback advanced the estimated frame. The renderer runs in the viewing browser; reconstruction and training run on the single NVIDIA GPU.
This is offline RGB reconstruction with an interactive viewer, not live on-vehicle perception or closed-loop autonomous driving. It gives a reproducible foundation for studying image-only geometry, neural rendering and ego-centered visualization.
Example run and recording
Original RGB reconstruction: mouse orbit and driver view
The same 400k-Gaussian scene before adding object perception. Actual mouse rotation, pan, zoom and camera-path replay.
Source code
pipeline.py
View files on GitHub"""Reproduce an RGB-only driving-scene reconstruction on one RTX 5090.
All outputs stay local. Model/scene/data rights are separate from this MIT code.
Use --help; the bilingual guide explains setup, own videos, and source licenses.
"""
import argparse,hashlib,json,os,platform,re,shutil,subprocess,time
from pathlib import Path
from input_guard import verify_rgb_inputs
LAB=Path(__file__).resolve().parent
PIN='dfd3d54c8c612003fb7948443edf7778f2bcd5ec'
p=argparse.ArgumentParser();p.add_argument('--root',type=Path,default=Path(os.environ.get('RGB_VIEW_ROOT',str(Path.home()/'physical-ai-labs/rgb-road'))));p.add_argument('--input',type=Path,help='Your RGB image folder, optionally one subfolder per camera');p.add_argument('--video',type=Path,help='Your RGB video, extracted locally with FFmpeg');p.add_argument('--sample-fps',type=float,default=3);p.add_argument('--capture-fps',type=float,default=10);p.add_argument('--front-folder',default='front_camera');p.add_argument('--cuda-home',type=Path);p.add_argument('--iterations',type=int,default=16000);p.add_argument('--port',type=int,default=8090);p.add_argument('stage',choices=['setup','example','ingest','sfm','train','export','serve','perceive','all']);a=p.parse_args();root=a.root.expanduser().resolve();root.mkdir(parents=True,exist_ok=True);sfm_py=root/'.venv/bin/python';source=root/'3dgrut';gpu_py=source/'.venv/bin/python'
def run(args,**kwargs):return subprocess.run([str(x) for x in args],check=True,**kwargs)
def uv_path():
uv=shutil.which('uv') or str(Path.home()/'.local/bin/uv')
if not Path(uv).is_file():raise SystemExit('Install uv first: https://docs.astral.sh/uv/getting-started/installation/')
return uv
def cuda_home():
candidates=[a.cuda_home] if a.cuda_home else [Path('/usr/local/cuda'),*Path('/usr/local').glob('cuda-*')]
valid=[]
for d in candidates:
if not d or not (d/'bin/nvcc').is_file():continue
text=subprocess.check_output([str(d/'bin/nvcc'),'--version'],text=True);m=re.search(r'release (\d+)\.(\d+)',text)
if m and (int(m[1]),int(m[2])) in [(12,8),(12,9)]:valid.append((int(m[2]),d.resolve()))
if not valid:raise SystemExit('This preset needs a CUDA 12.8/12.9 toolkit. Pass --cuda-home /path/to/cuda; CUDA 12.0 cannot compile for RTX 5090.')
return max(valid,key=lambda pair:pair[0])[1]
def gpu_env():
cuda=cuda_home();return {**os.environ,'CUDA_HOME':str(cuda),'PATH':f'{cuda}/bin:{os.environ.get("PATH","")}','TORCH_CUDA_ARCH_LIST':'12.0','MAX_JOBS':'2','OMP_NUM_THREADS':'8','CUDA_VISIBLE_DEVICES':'0','WANDB_MODE':'disabled','UV_INDEX':'pytorch=https://download.pytorch.org/whl/cu128'}
def setup():
if platform.system()!='Linux' or platform.machine() not in {'x86_64','AMD64'}:raise SystemExit('GPU reconstruction preset: Linux x86_64. The viewer and saved-result checks also run on Mac/Windows.')
uv=uv_path();env=gpu_env()
if not sfm_py.exists():run([uv,'venv','--python','3.11',sfm_py.parent.parent])
run([uv,'pip','install','--python',sfm_py,'pycolmap-cuda12==3.13.0','Pillow==13.0.0','numpy==2.4.6','scipy==1.17.1','plyfile==1.1.5','imageio-ffmpeg==0.6.0'])
if not source.exists():run(['git','clone','--recursive','https://github.com/nv-tlabs/3dgrut.git',source])
head=subprocess.check_output(['git','-C',str(source),'rev-parse','HEAD'],text=True).strip()
if head!=PIN:
if subprocess.check_output(['git','-C',str(source),'status','--porcelain'],text=True).strip():raise SystemExit('The 3DGRUT checkout has edits. Use a fresh output folder; your changes were preserved.')
run(['git','-C',source,'checkout',PIN]);run(['git','-C',source,'submodule','update','--init','--recursive'])
if not gpu_py.exists():run([uv,'venv','--python','3.11',gpu_py.parent.parent])
run([uv,'pip','install','--python',gpu_py,'torch==2.8.0','torchvision==0.23.0','--index-url','https://download.pytorch.org/whl/cu128'])
run([uv,'pip','install','--python',gpu_py,'-c',LAB/'constraints.txt','-e',str(source)+'[gui]'],env=env)
installed=subprocess.run([str(gpu_py),'-c','import tinycudann'],env=env,capture_output=True)
if installed.returncode:run([uv,'pip','install','--python',gpu_py,'--no-build-isolation',source/'thirdparty/tiny-cuda-nn/bindings/torch'],env=env)
run([uv,'pip','install','--python',gpu_py,'kaolin==0.18.0','-f','https://nvidia-kaolin.s3.us-east-2.amazonaws.com/torch-2.8.0_cu128.html'],env=env)
run([uv,'pip','install','--python',gpu_py,'--no-build-isolation','-r',source/'requirements_extra.txt','slangtorch==1.3.18','pycolmap-cuda12==3.13.0'],env=env)
run([gpu_py,'-c','import torch,tinycudann,kaolin,ppisp,slangtorch;from fused_ssim import fused_ssim;assert torch.cuda.is_available();print("GPU environment ready:",torch.cuda.get_device_name(0))'],env=env)
(root/'setup.done.json').write_text(json.dumps({'3dgrut_commit':PIN,'torch':'2.8.0+cu128','sfm':'pycolmap-cuda12 3.13.0','cuda_toolkit':str(cuda_home().name),'arch':'12.0','reconstruction_pretrained_weights_required':False,'perception_weights':'public TorchVision COCO_V1; downloaded on first perception run'},indent=2)+'\n')
def ingest():
if a.video:
ffmpeg=shutil.which('ffmpeg')
if not ffmpeg:ffmpeg=subprocess.check_output([str(sfm_py),'-c','import imageio_ffmpeg;print(imageio_ffmpeg.get_ffmpeg_exe())'],text=True).strip()
frames=root/'video-rgb/camera';frames.mkdir(parents=True,exist_ok=True);run([ffmpeg,'-v','error','-i',a.video,'-vf',f'fps={a.sample_fps}','-q:v','2',frames/'%06d.jpg']);src=frames.parent
elif a.input:src=a.input
else:raise SystemExit('Use --input /path/to/RGB or --video /path/to/clip.mp4; omit both for the public example in stage all.')
run([sfm_py,LAB/'prepare_images.py','--input',src,'--output',root/'work'])
(root/'ingest.json').write_text(json.dumps({'kind':'video' if a.video else 'images','sample_fps':a.sample_fps if a.video else a.capture_fps,'front_folder':'camera' if a.video else a.front_folder},indent=2)+'\n')
def sfm():
verify_rgb_inputs(root/'work');run([sfm_py,LAB/'sfm.py','--root',root/'work','--device','cuda'],env=gpu_env())
def train():
verify_rgb_inputs(root/'work')
expected=json.loads((root/'work/sfm-result.json').read_text())['registered_images']
count=int(subprocess.check_output([str(sfm_py),'-c','import sys,pycolmap as c;print(c.Reconstruction(sys.argv[1]).num_reg_images())',str(root/'work/undistorted/sparse/0')],text=True).strip())
if count!=expected:raise RuntimeError('The selected and undistorted RGB model have different image counts; rerun the sfm stage.')
env=gpu_env();out=root/'train';args=[gpu_py,source/'train.py','--config-name','apps/colmap_3dgut_mcmc.yaml',f'path={root}/work/undistorted',f'out_dir={out}','experiment_name=rgb-only',f'n_iterations={a.iterations}','num_workers=2','strategy.add.max_n_gaussians=400000','export_ply.enabled=true','export_usd.enabled=false','test_last=false','with_gui=false','with_viser_gui=false','compute_extra_metrics=false','enable_frame_timings=true','log_frequency=100','enable_writer=false','dataset.load_exif=false']
start=time.perf_counter();samples=[]
import fcntl
with open(os.environ.get('GPU_LOCK','/tmp/rgb-reality-view.gpu.lock'),'w') as lock:
fcntl.flock(lock,fcntl.LOCK_EX)
with (root/'train.log').open('w') as log:
child=subprocess.Popen([str(x) for x in args],cwd=source,env=env,stdout=log,stderr=subprocess.STDOUT)
while child.poll() is None:
try:
values=subprocess.check_output(['nvidia-smi','--query-gpu=memory.used,utilization.gpu','--format=csv,noheader,nounits'],text=True).splitlines()[0].split(',');samples.append({'t_seconds':time.perf_counter()-start,'gpu_memory_mib':int(values[0]),'utilization_percent':int(values[1])})
except (subprocess.SubprocessError,ValueError):pass
time.sleep(1)
if child.returncode:raise SystemExit(f'Training failed. Inspect {root/"train.log"}; raw logs stay in your output folder.')
log=(root/'train.log').read_text(errors='replace');tables=re.findall(r'│\s*(\d+)\s*│\s*(\d+)\s*│\s*([\d.]+)\s*s\s*│',log);models=list(out.rglob('export_last.ply'))
if not models or not tables:raise RuntimeError('No completed model and observed training summary were found')
artifact=max(models,key=lambda p:p.stat().st_mtime);steps,epochs,seconds=tables[-1]
report={'3dgrut_commit':PIN,'training_steps':int(steps),'epochs':int(epochs),'training_loop_seconds':float(seconds),'wall_seconds_including_compile':time.perf_counter()-start,'gpu_count':1,'gpu_memory_mib_sampled_total_peak':max((s['gpu_memory_mib'] for s in samples),default=0),'memory_scope':'nvidia-smi total GPU usage sampled each second; includes display/background allocations','input_manifest_sha256':hashlib.sha256((root/'work/input-manifest.json').read_bytes()).hexdigest(),'dataset_type':'COLMAP estimated from RGB','test_last':False,'evaluation_scope':'No independent novel-view accuracy claim. All images inform SfM; photometric train/validation split is not a sensor-exclusion benchmark.','ply':str(artifact.relative_to(root))}
(root/'training-result.json').write_text(json.dumps(report,indent=2)+'\n');print('TRAIN_COMPLETE',json.dumps(report),flush=True)
def perceive():
verify_rgb_inputs(root/'work')
# Older local installs may predate the perception extension.
run([uv_path(),'pip','install','--python',gpu_py,'pycolmap-cuda12==3.13.0'])
import fcntl
with open(os.environ.get('GPU_LOCK','/tmp/rgb-reality-view.gpu.lock'),'w') as lock:
fcntl.flock(lock,fcntl.LOCK_EX);run([gpu_py,LAB/'perceive.py','--root',root],env=gpu_env())
def export():
verify_rgb_inputs(root/'work');report=json.loads((root/'training-result.json').read_text());folder=a.front_folder
ingest=json.loads((root/'ingest.json').read_text()) if (root/'ingest.json').exists() else {}
if ingest.get('kind')=='video':folder='camera'
if folder=='front_camera':
groups={row['image'].split('/')[0] for row in verify_rgb_inputs(root/'work')['images']}
if folder not in groups and len(groups)==1:folder=next(iter(groups))
out=root/'viewer';run([sfm_py,LAB/'prepare_viewer.py','--root',root/'work','--output',out,'--front-folder',folder,'--capture-fps',ingest.get('sample_fps',a.capture_fps)])
npm=shutil.which('npm')
if not npm:raise SystemExit('Install Node.js/npm to create the compressed browser model; the full RGB-only PLY has already been saved.')
run([npm,'exec','--yes','--package=@playcanvas/splat-transform@3.12.0','--','splat-transform','-w',root/report['ply'],'--filter-harmonics','1',out/'road.spz','--spz-version','3'])
shutil.copy2(LAB/'assets/volvo-s90.glb',out/'volvo-s90.glb')
for name in ['viewer.html','viewer.js','viewer.css','perception-view.js','policy-view.js']:shutil.copy2(LAB/name,out/name)
shutil.copy2(LAB/'assets/VEHICLE-LICENSE.txt',out/'VEHICLE-LICENSE.txt')
if (root/'PANDASET-DATA-LICENSE.txt').exists():shutil.copy2(root/'PANDASET-DATA-LICENSE.txt',out/'PANDASET-DATA-LICENSE.txt');credits=(LAB/'assets/EXAMPLE-ATTRIBUTION.txt').read_text()
else:credits='Scene: user-provided RGB images; preserve their original rights.\n'+(LAB/'assets/VEHICLE-LICENSE.txt').read_text()
(out/'ATTRIBUTION.txt').write_text(credits);print('VIEWER_READY',str(out),flush=True)
if a.stage=='setup':setup()
elif a.stage=='example':run([sfm_py,LAB/'fetch_example.py','--root',root])
elif a.stage=='ingest':ingest()
elif a.stage=='sfm':sfm()
elif a.stage=='train':train()
elif a.stage=='export':export()
elif a.stage=='perceive':perceive()
elif a.stage=='serve':run(['python3',LAB/'serve.py','--root',root/'viewer','--port',a.port])
else:
if not (root/'setup.done.json').exists():setup()
if a.input or a.video:ingest()
else:run([sfm_py,LAB/'fetch_example.py','--root',root])
sfm();train();export();perceive();run(['python3',LAB/'serve.py','--root',root/'viewer','--port',a.port])
prepare_images.py
View files on GitHub"""Create a pixel-only input folder. Never read depth, poses, GPS or LiDAR files."""
import argparse,hashlib,json
from pathlib import Path
from PIL import Image,ImageOps
EXTENSIONS={'.jpg','.jpeg','.png','.webp'}
def prepare(source,output,stride=1,max_side=1024):
source=Path(source);output=Path(output);images=output/'images'
if images.exists() and any(images.rglob('*')):raise ValueError('Use a fresh output folder to prevent mixing RGB and previous reconstruction inputs')
images.mkdir(parents=True,exist_ok=True);rows=[]
folders=sorted({p.parent for p in source.rglob('*') if p.is_file() and p.suffix.lower() in EXTENSIONS})
for folder in folders:
files=sorted(p for p in folder.iterdir() if p.is_file() and p.suffix.lower() in EXTENSIONS)[::stride]
camera=folder.relative_to(source).as_posix().replace('/','_') if folder!=source else 'camera'
for i,p in enumerate(files):
im=ImageOps.exif_transpose(Image.open(p)).convert('RGB');im.thumbnail((max_side,max_side),Image.Resampling.LANCZOS)
target=images/camera/f'{p.stem}.jpg';target.parent.mkdir(parents=True,exist_ok=True)
# Fresh RGB pixels: do not copy EXIF, GPS, camera K, ICC or other sidecars.
im.info.clear();im.save(target,format='JPEG',quality=96)
rows.append({'image':target.relative_to(images).as_posix(),'width':im.width,'height':im.height,'sha256':hashlib.sha256(target.read_bytes()).hexdigest()})
if len(rows)<8:raise ValueError('At least eight overlapping RGB frames are needed')
manifest={'schema':1,'input':'RGB pixels only','external_sensor_inputs':[],'supplied_camera_poses':False,'supplied_intrinsics':False,'supplied_depth':False,'supplied_ground_plane':False,'stride':stride,'max_side':max_side,'images':rows}
(output/'input-manifest.json').write_text(json.dumps(manifest,indent=2)+'\n');print('RGB_ONLY_INPUT',len(rows),'images',flush=True)
return manifest
if __name__=='__main__':
p=argparse.ArgumentParser();p.add_argument('--input',type=Path,required=True);p.add_argument('--output',type=Path,required=True);p.add_argument('--stride',type=int,default=1);p.add_argument('--max-side',type=int,default=1024);a=p.parse_args();prepare(a.input,a.output,a.stride,a.max_side)
input_guard.py
View files on GitHub"""Enforce the RGB-only contract before feature matching or training."""
import hashlib,json
from pathlib import Path
def verify_rgb_inputs(root):
root=Path(root);manifest=json.loads((root/'input-manifest.json').read_text());images=root/'images';listed={row['image'] for row in manifest['images']};actual={p.relative_to(images).as_posix() for p in images.rglob('*') if p.is_file()}
if actual!=listed or any(Path(p).suffix.lower() not in {'.jpg','.jpeg','.png'} for p in actual):raise ValueError('RGB input directory contains unexpected files; reconstruction stopped')
if len(listed)!=len(manifest['images']):raise ValueError('Duplicate RGB input names')
for row in manifest['images']:
path=images/row['image']
if not path.resolve().is_relative_to(images.resolve()):raise ValueError('RGB path leaves the image folder')
if hashlib.sha256(path.read_bytes()).hexdigest()!=row['sha256']:raise ValueError('RGB input hash changed')
if manifest['external_sensor_inputs'] or any(manifest[k] for k in ['supplied_camera_poses','supplied_intrinsics','supplied_depth','supplied_ground_plane']):raise ValueError('This pipeline accepts RGB pixels only')
return manifest
fetch_example.py
View files on GitHub"""Fetch only PandaSet JPEG RGB frames and original terms from a pinned mirror.
No intrinsics, poses, timestamps, LiDAR, depth or annotation files are fetched.
The community mirror is not an official publisher; original terms are preserved.
"""
import argparse,hashlib,json,struct,time,zlib
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path,PurePosixPath
from urllib.request import Request,urlopen
from index_zip import RemoteZip,REVISION,SIZE
from prepare_images import prepare
import zipfile
p=argparse.ArgumentParser();p.add_argument('--root',type=Path,required=True);p.add_argument('--scene',default='001');p.add_argument('--stride',type=int,default=3);a=p.parse_args();root=a.root;root.mkdir(parents=True,exist_ok=True)
with zipfile.ZipFile(RemoteZip()) as z:infos=z.infolist()
url=f'https://huggingface.co/datasets/georghess/pandaset/resolve/{REVISION}/pandaset.zip?download=true&rgb={int(time.time())}'
cameras={'front_camera','front_left_camera','front_right_camera','left_camera','right_camera','back_camera'}
selected=[]
for i in infos:
parts=PurePosixPath(i.filename).parts
if len(parts)==5 and parts[:3]==('pandaset',a.scene,'camera') and parts[3] in cameras and parts[4].endswith('.jpg') and int(Path(parts[4]).stem)%a.stride==0:selected.append(i)
license_info=next(i for i in infos if i.filename==f'pandaset/{a.scene}/LICENSE.txt')
def fetch(start,end):
for retry in range(5):
try:
with urlopen(Request(url,headers={'Range':f'bytes={start}-{end}'}),timeout=120) as res:
if res.status!=206 or res.headers.get('Content-Range')!=f'bytes {start}-{end}/{SIZE}':raise ValueError('Wrong archive byte range')
data=res.read(end-start+2)
if len(data)!=end-start+1:raise ValueError('Truncated archive member')
return data
except Exception:
if retry==4:raise
time.sleep(1+retry)
def read_member(i):
fields=struct.unpack('<4s5H3L2H',fetch(i.header_offset,i.header_offset+29))
if fields[0]!=b'PK\x03\x04':raise ValueError('Invalid ZIP header')
start=i.header_offset+30+fields[-2]+fields[-1];data=fetch(start,start+i.compress_size-1)
data=zlib.decompress(data,-15) if i.compress_type==8 else data if i.compress_type==0 else None
if data is None or len(data)!=i.file_size or zlib.crc32(data)!=i.CRC:raise ValueError('ZIP CRC/size mismatch')
return data
terms=read_member(license_info);(root/'PANDASET-DATA-LICENSE.txt').write_bytes(terms)
def save(i):
relative=PurePosixPath(i.filename).relative_to(f'pandaset/{a.scene}/camera');target=root/'downloaded-rgb'/str(relative);target.parent.mkdir(parents=True,exist_ok=True);data=read_member(i);target.write_bytes(data);return {'file':str(relative),'bytes':len(data),'zip_crc32':i.CRC,'sha256':hashlib.sha256(data).hexdigest()}
with ThreadPoolExecutor(max_workers=8) as pool:receipt=list(pool.map(save,selected))
(root/'download-result.json').write_text(json.dumps({'source':'PandaSet by Scale AI and Hesai','mirror':'https://huggingface.co/datasets/georghess/pandaset','mirror_status':'unofficial community mirror','revision':REVISION,'files':receipt,'downloaded_modalities':['RGB JPEG'],'did_not_download':['LiDAR','depth','poses','intrinsics','GPS','IMU','timestamps','annotations'],'verification':'Per-file CRC and size checked, per-file SHA-256 recorded; full archive SHA-256 not checked for range download'},indent=2)+'\n')
prepare(root/'downloaded-rgb',root/'work',stride=1)
print('RGB_EXAMPLE_COMPLETE',len(receipt),'RGB frames; original terms retained',flush=True)
sfm.py
View files on GitHub"""Recover intrinsics, camera poses and sparse 3D using only RGB image matches."""
import argparse,hashlib,json,time
from pathlib import Path
import pycolmap as c
p=argparse.ArgumentParser();p.add_argument('--root',type=Path,required=True);p.add_argument('--features',type=int,default=4096);p.add_argument('--device',choices=['auto','cpu','cuda'],default='auto');a=p.parse_args();r=a.root;start=time.perf_counter()
from input_guard import verify_rgb_inputs
manifest=verify_rgb_inputs(r);listed={row['image'] for row in manifest['images']}
db=r/'database.db';device=getattr(c.Device,a.device);ex=c.FeatureExtractionOptions();ex.max_image_size=1024;ex.num_threads=8;ex.sift.max_num_features=a.features
c.extract_features(str(db),str(r/'images'),camera_mode=c.CameraMode.PER_FOLDER,camera_model='SIMPLE_RADIAL',extraction_options=ex,device=device)
print('SIFT_COMPLETE',round(time.perf_counter()-start,2),flush=True)
mt=c.FeatureMatchingOptions();mt.num_threads=8;mt.max_num_matches=8192;mt.guided_matching=True
c.match_exhaustive(str(db),matching_options=mt,device=device)
print('MATCHING_COMPLETE',round(time.perf_counter()-start,2),flush=True)
options=c.IncrementalPipelineOptions();options.num_threads=8;options.ba_refine_focal_length=True;options.ba_refine_extra_params=True
(r/'sparse').mkdir(exist_ok=True)
models=c.incremental_mapping(str(db),str(r/'images'),str(r/'sparse'),options=options)
if not models:raise RuntimeError('RGB-only SfM could not register a connected scene; capture more overlapping views')
model=max(models.values(),key=lambda m:m.num_reg_images())
if model.num_reg_images()<len(listed)*.8:raise RuntimeError('Fewer than 80% of RGB images registered in one scene. Capture more overlap.')
# Returned model IDs need not match the output directory ordering. Export the
# selected in-memory reconstruction to an independent folder in binary AND text.
selected=r/'sfm-selected';selected.mkdir(exist_ok=True);model.write(str(selected));model.write_text(str(selected))
report={'pycolmap':c.__version__,'cuda_build':bool(c.has_cuda),'device':a.device,'input_images':len(listed),'registered_images':model.num_reg_images(),'sparse_points':model.num_points3D(),'mean_reprojection_error_px':model.compute_mean_reprojection_error(),'elapsed_seconds':time.perf_counter()-start,'selected_model':'sfm-selected','intrinsics':'estimated from RGB, SIMPLE_RADIAL shared per image folder','camera_poses':'estimated by COLMAP SfM; no dataset poses, GPS, IMU or LiDAR','scale':'arbitrary SfM units before explicitly labeled display normalization'}
(r/'sfm-result.json').write_text(json.dumps(report,indent=2)+'\n');print('SFM_COMPLETE',report,flush=True)
und=c.UndistortCameraOptions();und.max_image_size=1024
c.undistort_images(str(r/'undistorted'),str(selected),str(r/'images'),undistort_options=und)
# 3DGRUT expects the COLMAP sparse/0 layout; keep the MVS root model too.
normalized=r/'undistorted/sparse/0';normalized.mkdir(exist_ok=True);undistorted=c.Reconstruction(str(r/'undistorted/sparse'))
if undistorted.num_reg_images()!=model.num_reg_images():raise RuntimeError('Undistorted model does not match the selected RGB reconstruction')
undistorted.write(str(normalized))
print('UNDISTORTED',flush=True)
prepare_viewer.py
View files on GitHub"""Create viewer alignment and an ego path from RGB-derived COLMAP geometry.
No original sensor poses or depth are read. Metric scale is not observable from
uncalibrated RGB alone. We normalize the estimated camera-to-road distance to
one viewer unit; the car's relative size is a display convention, not metrology.
"""
import argparse,hashlib,json,math
from pathlib import Path
import numpy as np
import pycolmap as c
p=argparse.ArgumentParser();p.add_argument('--root',type=Path,required=True);p.add_argument('--output',type=Path,required=True);p.add_argument('--front-folder',default='front_camera');p.add_argument('--capture-fps',type=float,default=10);a=p.parse_args();r=a.root;out=a.output;out.mkdir(parents=True,exist_ok=True)
model=c.Reconstruction(str(r/'undistorted/sparse/0'));front=sorted([im for im in model.images.values() if im.name.split('/')[0]==a.front_folder],key=lambda im:im.name)
if len(front)<3:raise ValueError('Choose a front-facing image folder with at least three registered frames')
def pose(im):
m=np.eye(4);m[:3]=im.cam_from_world().matrix();return np.linalg.inv(m)
C=np.array([pose(im) for im in front]);up=np.median(-C[:,:3,1],axis=0);up/=np.linalg.norm(up);forward=np.median(C[:,:3,2],axis=0);forward-=up*forward.dot(up);forward/=np.linalg.norm(forward);left=np.cross(up,forward);left/=np.linalg.norm(left)
# Candidate road correspondences are actual triangulated points observed in the
# central lower part of the front RGB images; no provided road plane is loaded.
ids=set()
for im in front:
cam=model.cameras[im.camera_id]
for pt in im.points2D:
x,y=pt.xy
if .15*cam.width<x<.85*cam.width and .60*cam.height<y<.95*cam.height and pt.point3D_id in model.points3D:
point=model.points3D[pt.point3D_id]
if point.error<2 and point.track.length()>=3:ids.add(pt.point3D_id)
if len(ids)<30:raise ValueError('Not enough RGB-derived road features to align a ground plane; capture textured road or choose another clip')
P=np.array([model.points3D[i].xyz for i in ids]);center=np.median(C[:,:3,3],axis=0);depth=np.median(np.linalg.norm(P-center,axis=1));threshold=max(depth*.004,1e-5);rng=np.random.default_rng(17);best=None
for _ in range(1600):
q=P[rng.choice(len(P),3,replace=False)];n=np.cross(q[1]-q[0],q[2]-q[0]);length=np.linalg.norm(n)
if length<1e-10:continue
n/=length
if abs(n.dot(up))<math.cos(math.radians(18)):continue
if n.dot(up)<0:n=-n
d=-n.dot(q[0]);inside=np.abs(P@n+d)<threshold;score=int(inside.sum())
if best is None or score>best[0]:best=(score,n,d,inside)
if best is None or best[0]<25:raise ValueError('Could not fit a defensible road plane from RGB features')
Q=P[best[3]];mean=Q.mean(axis=0);_,_,vh=np.linalg.svd(Q-mean,full_matrices=False);n=vh[-1]
if n.dot(up)<0:n=-n
d=-n.dot(mean);heights=C[:,:3,3]@n+d;height=float(np.median(heights))
if height<=0:raise ValueError('Estimated road plane lies above the camera')
forward-=n*forward.dot(n);forward/=np.linalg.norm(forward);left=np.cross(n,forward);left/=np.linalg.norm(left);R=np.stack([forward,left,n]);origin=C[len(C)//2,:3,3]-n*heights[len(C)//2];scale=1/height
T=np.eye(4);T[:3,:3]=R*scale;T[:3,3]=-R@origin*scale
rows=[]
for im,M,h in zip(front,C,heights):
position=(R@(M[:3,3]-origin))*scale;ground=position.copy();ground[2]-=h*scale;direction=R@M[:3,2];yaw=math.atan2(direction[1],direction[0]);rot=R@M[:3,:3];cam=model.cameras[im.camera_id];K=cam.calibration_matrix()
try:seconds=int(Path(im.name).stem)/a.capture_fps
except ValueError:seconds=len(rows)/a.capture_fps
rows.append({'image':im.name,'time_seconds':seconds,'camera_position':position.tolist(),'camera_rotation_opencv':rot.tolist(),'ground_position':ground.tolist(),'yaw_radians':yaw,'K':K.tolist(),'image_size':[cam.width,cam.height]})
geometry={'schema':1,'world_to_viewer':T.tolist(),'up_axis':'Z','units':'normalized camera-height units; not measured meters','scale_assumption':'RGB/SfM scale is ambiguous. Median estimated camera-to-road distance is normalized to 1. Vehicle scale 1/1.8 is a display proportion, not a measurement.','road_plane_source':'RANSAC + least-squares on triangulated RGB feature tracks in lower front-camera image regions','road_plane_candidates':len(P),'road_plane_inliers':len(Q),'road_plane_rms_viewer_units':float(np.sqrt(np.mean((Q@n+d)**2))*scale),'source_camera':'COLMAP estimated intrinsics and camera poses; no source dataset calibration or poses','frames':rows,'vehicle':{'file':'volvo-s90.glb','scale':1/1.8,'model_axis':'glTF Y-up, nose +X; rotate +90 degrees around X into viewer Z-up','role':'added ego-position reference; not the original capture vehicle or an OEM dynamics model'},'default_frame':len(rows)//2}
(out/'cameras.json').write_text(json.dumps(geometry,indent=2)+'\n');print('VIEWER_GEOMETRY',len(rows),'front poses; plane',len(Q),'inliers; RMS',geometry['road_plane_rms_viewer_units'],flush=True)
perceive.py
View files on GitHub"""Detect/segment real RGB road users and project approximate ground contacts.
Runs on the same single GPU after reconstruction. Reads only reconstructed RGB
images/cameras; never imports PandaSet annotations, LiDAR or sensor metadata.
"""
import argparse
from collections import Counter
import hashlib,json,math,time
from pathlib import Path
import numpy as np
from PIL import Image
import pycolmap
import torch
from torchvision.models.detection import maskrcnn_resnet50_fpn_v2, MaskRCNN_ResNet50_FPN_V2_Weights
from torchvision.transforms.functional import pil_to_tensor
from input_guard import verify_rgb_inputs
from perception_geometry import ground_contact,rle_encode,associate
p=argparse.ArgumentParser();p.add_argument('--root',type=Path,required=True);p.add_argument('--score',type=float,default=.8);a=p.parse_args();root=a.root;work=root/'work';out=root/'viewer';verify_rgb_inputs(work)
if not 0<a.score<1:raise ValueError('Score must be between 0 and 1')
geometry=json.loads((out/'cameras.json').read_text());T=np.array(geometry['world_to_viewer']);scale=np.linalg.norm(T[0,:3]);R=T[:3,:3]/scale
model=pycolmap.Reconstruction(str(work/'undistorted/sparse/0'));images={im.name:im for im in model.images.values()};cams=sorted({Path(n).parts[0] for n in images});frames=[]
weights=MaskRCNN_ResNet50_FPN_V2_Weights.COCO_V1
checkpoint=Path(torch.hub.get_dir())/'checkpoints'/Path(weights.url).name
expected_sha256='73cbd0190fcbe3ba339921fbce2c3a0b6bb9126c9a133c85e43a2a8e060a109e'
if not checkpoint.exists():
checkpoint.parent.mkdir(parents=True,exist_ok=True);torch.hub.download_url_to_file(weights.url,str(checkpoint),hash_prefix=expected_sha256)
if hashlib.sha256(checkpoint.read_bytes()).hexdigest()!=expected_sha256:raise ValueError('Detector checkpoint hash differs from the pinned public weights')
categories=weights.meta['categories'];keep={'person','car','truck','bus','bicycle','motorcycle'}
torch.set_num_threads(8);torch.backends.cuda.matmul.allow_tf32=True;torch.cuda.reset_peak_memory_stats();start=time.perf_counter();net=maskrcnn_resnet50_fpn_v2(weights=weights,min_size=640,max_size=1024,box_score_thresh=a.score).eval().cuda();timings=[];counts=Counter();localized=0;file_hashes={}
with torch.inference_mode():
for fi,front in enumerate(geometry['frames']):
stem=Path(front['image']).stem;frame={'index':fi,'time_seconds':front['time_seconds'],'views':{}}
for camera in cams:
name=f'{camera}/{stem}.jpg'
if name not in images:continue
im=images[name];cam=model.cameras[im.camera_id];M=np.eye(4);M[:3]=im.cam_from_world().matrix();C=np.linalg.inv(M);position=(T@np.r_[C[:3,3],1])[:3];rotation=R@C[:3,:3];K=cam.calibration_matrix()
path=work/'undistorted/images'/name;rgb=Image.open(path).convert('RGB');tensor=pil_to_tensor(rgb).float().cuda()/255;torch.cuda.synchronize();before=time.perf_counter();pred=net([tensor])[0];torch.cuda.synchronize();timings.append(time.perf_counter()-before)
boxes=pred['boxes'].cpu().numpy();scores=pred['scores'].cpu().numpy();labels=pred['labels'].cpu().numpy();masks=pred['masks'].cpu().numpy();rows=[]
for bi,(box,score,label) in enumerate(zip(boxes,scores,labels)):
cls=categories[int(label)]
if cls not in keep or score<a.score:continue
x0=max(0,int(math.floor(box[0])));y0=max(0,int(math.floor(box[1])));x1=min(rgb.width,int(math.ceil(box[2])));y1=min(rgb.height,int(math.ceil(box[3])))
if x1-x0<8 or y1-y0<8:continue
mask=masks[bi,0]>.5;yy,xx=np.where(mask)
if len(xx)<15:continue
bottom=np.quantile(yy,.98);band=yy>=bottom;pixel=[float(np.median(xx[band])),float(np.median(yy[band]))]
contact=ground_contact(pixel,K.tolist(),rotation.tolist(),position.tolist())
# Edge-truncated objects have an unreliable ground-contact pixel.
if y1>=rgb.height-2 or x0<=1 or x1>=rgb.width-1:contact=None
tiny=Image.fromarray((mask[y0:y1,x0:x1]*255).astype('uint8'));tiny.thumbnail((96,160),Image.Resampling.NEAREST);bits=np.asarray(tiny)>0
row={'class':cls,'score':round(float(score),4),'bbox':[round(float(x),2) for x in box],'camera':camera,'mask':{'origin':[x0,y0],'extent':[x1-x0,y1-y0],'size':list(tiny.size),'counts':rle_encode(bits.ravel())},'contact_pixel':[round(x,2) for x in pixel],'ground_position':contact,'track_id':None};rows.append(row);counts[cls]+=1;localized+=contact is not None
target=out/'camera'/camera/f'{stem}.jpg';target.parent.mkdir(parents=True,exist_ok=True);rgb.thumbnail((640,640),Image.Resampling.LANCZOS);rgb.info.clear();rgb.save(target,quality=84);relative=target.relative_to(out).as_posix();file_hashes[relative]=hashlib.sha256(target.read_bytes()).hexdigest()
frame['views'][camera]={'image':relative,'image_size':[cam.width,cam.height],'detections':rows}
frames.append(frame)
print('PERCEPTION_FRAME',fi+1,'/',len(geometry['frames']),sum(len(v['detections']) for v in frame['views'].values()),flush=True)
tracks=associate(frames);checkpoint=Path(torch.hub.get_dir())/'checkpoints'/Path(weights.url).name
payload={'schema':1,'detector':'TorchVision Mask R-CNN ResNet50 FPN v2 / COCO_V1','score_threshold':a.score,'mask_threshold':.5,'classes':sorted(keep),'camera_names':cams,'default_camera':'left_camera' if 'left_camera' in cams else cams[0],'localization':'RGB-derived estimated K/poses + mask contact ray intersected with an RGB-derived road plane; relative units, not 3D ground truth','association':'Greedy class/position association over this short clip; IDs may switch, no identity or velocity claim','frames':frames}
(out/'perception.json').write_text(json.dumps(payload,separators=(',',':'))+'\n')
geometry['perception_file']='perception.json';(out/'cameras.json').write_text(json.dumps(geometry,indent=2)+'\n')
receipt={'recorded_date':'2026-11-23','inputs':['undistorted RGB pixels','COLMAP cameras estimated only from RGB','road plane estimated only from RGB feature tracks'],'uses_source_annotations':False,'uses_lidar':False,'uses_supplied_calibration':False,'torch':torch.__version__,'torchvision':'0.23.0','gpu':'NVIDIA GeForce RTX 5090','gpu_count':1,'weights_url':weights.url,'weights_sha256':hashlib.sha256(checkpoint.read_bytes()).hexdigest(),'weights_distribution':'public upstream download; not bundled','code_license':'TorchVision BSD-3-Clause; model-specific weights terms not separately stated on the upstream model page; training-data rights remain separate','camera_images':len(timings),'frames':len(frames),'detections_by_class':dict(counts),'localized_detection_observations':localized,'unlocalized_detection_observations':sum(counts.values())-localized,'short_clip_track_ids':tracks,'wall_seconds':time.perf_counter()-start,'cuda_forward_seconds_first':timings[0],'cuda_forward_seconds_mean_after_first':float(np.mean(timings[1:])),'timing_scope':'CUDA forward only excludes image decode, transfer and output packaging. Full wall time includes model load and packaging; not a real-time end-to-end FPS claim.','torch_peak_allocated_mib':torch.cuda.max_memory_allocated()/2**20,'torch_peak_reserved_mib':torch.cuda.max_memory_reserved()/2**20,'perception_sha256':hashlib.sha256((out/'perception.json').read_bytes()).hexdigest(),'rgb_preview_sha256':file_hashes}
(root/'perception-result.json').write_text(json.dumps(receipt,indent=2)+'\n');print('PERCEPTION_COMPLETE',json.dumps({k:v for k,v in receipt.items() if k!='rgb_preview_sha256'}),flush=True)
perception_geometry.py
View files on GitHub"""RGB road-plane projection and short-clip association, in relative viewer units.
This is an explicit ground-contact assumption, not a learned 3D detector.
"""
import math
VEHICLES = {'car', 'truck', 'bus'}
def family(label):
return 'vehicle' if label in VEHICLES else label
def ground_contact(pixel, K, rotation, position, max_range=45):
"""Intersect a pinhole RGB ray with z=0. Reject horizon/behind/far rays."""
u, v = pixel
ray = [(u-K[0][2])/K[0][0], (v-K[1][2])/K[1][1], 1]
direction = [sum(rotation[i][j]*ray[j] for j in range(3)) for i in range(3)]
if not all(math.isfinite(x) for x in direction+list(position)) or direction[2] >= -1e-4:
return None
t = -position[2]/direction[2]
if t <= 0:
return None
point = [position[i]+t*direction[i] for i in range(3)]
if math.dist(point[:2], position[:2]) > max_range:
return None
return [round(point[0], 5), round(point[1], 5), 0.0]
def rle_encode(values):
counts=[]; previous=0; length=0
for bit in values:
bit=int(bool(bit))
if bit==previous:length+=1
else:counts.append(length);length=1;previous=bit
counts.append(length)
return counts
def associate(frames):
"""Merge nearby cross-camera estimates, then associate by class/position.
No source annotations or identity labels. IDs may switch; missing objects are
not extrapolated. A merge is deliberately forbidden within the same camera.
"""
active={}; next_id=1
for fi, frame in enumerate(frames):
detections=[d for v in frame['views'].values() for d in v['detections'] if d['ground_position'] is not None]
clusters=[]
for d in sorted(detections, key=lambda d:-d['score']):
radius=.65 if family(d['class'])=='vehicle' else .25
candidates=[c for c in clusters if family(c['class'])==family(d['class']) and d['camera'] not in c['cameras'] and math.dist(c['position'][:2],d['ground_position'][:2])<radius]
if candidates:
c=min(candidates,key=lambda c:math.dist(c['position'][:2],d['ground_position'][:2]))
c['members'].append(d);c['cameras'].append(d['camera'])
else:
clusters.append({'class':d['class'],'score':d['score'],'position':d['ground_position'],'cameras':[d['camera']],'members':[d]})
used=set(); objects=[]
for c in clusters:
gate=2.0 if family(c['class'])=='vehicle' else .6
candidates=[(math.dist(t['position'][:2],c['position'][:2]),tid) for tid,t in active.items() if tid not in used and fi-t['frame']<=2 and family(t['class'])==family(c['class'])]
distance,tid=min(candidates,default=(float('inf'),None))
if distance>gate:tid=next_id;next_id+=1
used.add(tid);active[tid]={'position':c['position'],'class':c['class'],'frame':fi}
for d in c['members']:d['track_id']=tid
objects.append({'id':tid,'class':c['class'],'score':c['score'],'ground_position':c['position'],'cameras':c['cameras']})
frame['objects']=objects
active={tid:t for tid,t in active.items() if fi-t['frame']<=2}
return next_id-1
perception-view.js
View files on GitHub// Real detector output on source RGB + approximate contacts in the reconstructed world.
// This overlay is diagnostic; it does not supply vehicle controls or metric depth.
import * as T from 'three';
const COLORS={person:'#ffd369',car:'#56e2ed',truck:'#56e2ed',bus:'#56e2ed',bicycle:'#ba9cff',motorcycle:'#ba9cff'};
const NAMES={person:'사람',car:'차량',truck:'트럭',bus:'버스',bicycle:'자전거',motorcycle:'이륜차'};
const CAMERA_NAMES={front_camera:['Front','정면'],front_left_camera:['Front left','왼쪽 앞'],front_right_camera:['Front right','오른쪽 앞'],left_camera:['Left','왼쪽'],right_camera:['Right','오른쪽'],back_camera:['Rear','후면']};
export async function mountPerception({root,stage,scene,base,ko,config}) {
if(!config.perception_file)return {setFrame(){},state:()=>null,dispose(){}};
const response=await fetch(base+config.perception_file);if(!response.ok)throw new Error('Missing RGB perception outputs');const data=await response.json();
const visuals=document.createElement('div');visuals.className='rgb-visuals';stage.before(visuals);visuals.append(stage);
const panel=document.createElement('aside');panel.className='rgb-perception';panel.setAttribute('aria-label',ko?'실제 RGB 객체 인식 결과':'Actual RGB object detections');
const heading=document.createElement('div');heading.className='rgb-perception-heading';const title=document.createElement('strong');title.textContent=ko?'카메라 인식':'Camera perception';
const select=document.createElement('select');select.dataset.rgbCamera='';select.setAttribute('aria-label',ko?'인식 결과 카메라':'Detection camera');
for(const name of data.camera_names){const o=document.createElement('option');o.value=name;o.textContent=(CAMERA_NAMES[name]??[name,name])[ko?1:0];select.append(o);}select.value=data.default_camera;
heading.append(title,select);const canvas=document.createElement('canvas');canvas.dataset.rgbDetections='';canvas.setAttribute('aria-label',ko?'원본 RGB 위의 예측 마스크와 검출 박스':'Predicted masks and bounding boxes on original RGB');
const count=document.createElement('p');count.className='rgb-perception-count';count.dataset.rgbCounts='';const note=document.createElement('small');note.textContent=ko?'실제 RGB · 예측 마스크·박스':'Actual RGB · predicted masks and boxes';
panel.append(heading,canvas,count,note);visuals.append(panel);
const toolbar=document.createElement('div');toolbar.className='rgb-perception-tools';const toggle=document.createElement('button');toggle.type='button';toggle.dataset.rgbRecognition='';toggle.setAttribute('aria-pressed','true');toggle.textContent=ko?'인식 표시 켜짐':'Recognition on';
const explanation=document.createElement('span');explanation.textContent=ko?'3D 표시는 RGB 도로면 기반 위치 추정 · 상대 단위':'3D markers: RGB road-plane estimates · relative units';toolbar.append(toggle,explanation);visuals.after(toolbar);
const layer=new T.Group();scene.add(layer);let index=config.default_frame,enabled=true,serial=0,disposed=false,shown=0,viewCount=0;let currentObjects=[];const sprites=[],meshes=[];const cached=new Map();
const ringGeometry=new T.RingGeometry(.17,.22,32),poleGeometry=new T.BufferGeometry().setFromPoints([new T.Vector3(0,0,.03),new T.Vector3(0,0,.7)]);
const getImage=path=>{if(!cached.has(path)){cached.set(path,new Promise((resolve,reject)=>{const image=new Image();image.onload=()=>resolve(image);image.onerror=()=>reject(new Error('Missing RGB preview'));image.src=base+path;}));}return cached.get(path);};
function clear(){while(layer.children.length)layer.remove(layer.children[0]);for(const s of sprites){s.material.map.dispose();s.material.dispose();}sprites.length=0;for(const m of meshes)m.dispose();meshes.length=0;}
function tag(text,color){const c=document.createElement('canvas');c.width=224;c.height=46;const ctx=c.getContext('2d');ctx.fillStyle='#09191be6';ctx.beginPath();ctx.roundRect(0,0,224,46,8);ctx.fill();ctx.font='600 23px Arial,"Noto Sans KR",sans-serif';ctx.fillStyle=color;ctx.textAlign='center';ctx.fillText(text,112,31);const texture=new T.CanvasTexture(c);texture.colorSpace=T.SRGBColorSpace;const sprite=new T.Sprite(new T.SpriteMaterial({map:texture,transparent:true,depthTest:false,depthWrite:false,sizeAttenuation:false}));sprite.scale.set(.22,.06,1);sprites.push(sprite);return sprite;}
function drawMarkers(frame){clear();const ego=config.frames[index].ground_position;const objects=frame.objects.map(o=>({...o,distance:Math.hypot(o.ground_position[0]-ego[0],o.ground_position[1]-ego[1])})).filter(o=>o.distance<22).sort((a,b)=>a.distance-b.distance).slice(0,24);shown=objects.length;currentObjects=objects;
objects.forEach((o,i)=>{const color=COLORS[o.class]??'#56e2ed',group=new T.Group();group.position.set(...o.ground_position);const ringMaterial=new T.MeshBasicMaterial({color,transparent:true,opacity:.9,side:T.DoubleSide,depthTest:false,depthWrite:false});meshes.push(ringMaterial);const ring=new T.Mesh(ringGeometry,ringMaterial);ring.position.z=.025;group.add(ring);const lineMaterial=new T.LineBasicMaterial({color,transparent:true,opacity:.8,depthTest:false,depthWrite:false});meshes.push(lineMaterial);group.add(new T.Line(poleGeometry,lineMaterial));if(o.cameras.includes(select.value)&&(i<12||o.class==='person')){const label=tag(`${ko?NAMES[o.class]:o.class.toUpperCase()}`,color);label.position.z=.85;group.add(label);}group.traverse(node=>node.layers.set(1));layer.add(group);});layer.visible=enabled;
}
function maskCanvas(mask,color){const c=document.createElement('canvas');[c.width,c.height]=mask.size;const ctx=c.getContext('2d'),im=ctx.createImageData(c.width,c.height);const rgb=new T.Color(color);let pos=0;mask.counts.forEach((n,i)=>{for(let j=0;j<n;j++,pos++){if(i%2){const k=pos*4;im.data[k]=Math.round(rgb.r*255);im.data[k+1]=Math.round(rgb.g*255);im.data[k+2]=Math.round(rgb.b*255);im.data[k+3]=102;}}});ctx.putImageData(im,0,0);return c;}
async function drawRgb(frame){const key=select.value,view=frame.views[key];if(!view)return;const ticket=++serial;viewCount=view.detections.length;const tally={};for(const d of view.detections)tally[d.class]=(tally[d.class]??0)+1;count.textContent=Object.entries(tally).map(([name,n])=>`${ko?NAMES[name]:name} ${n}`).join(' · ')||(ko?'이 프레임에서 기준 이상 검출 없음':'No detections above threshold in this frame');
const image=await getImage(view.image);if(disposed||ticket!==serial)return;const [w,h]=view.image_size;canvas.width=640;canvas.height=Math.round(640*h/w);const ctx=canvas.getContext('2d');ctx.scale(640/w,640/w);ctx.drawImage(image,0,0,w,h);
if(enabled){
for(const d of view.detections){const color=COLORS[d.class]??'#56e2ed';ctx.drawImage(maskCanvas(d.mask,color),...d.mask.origin,...d.mask.extent);const [x0,y0,x1,y1]=d.bbox;ctx.strokeStyle=color;ctx.lineWidth=2.7;ctx.strokeRect(x0,y0,x1-x0,y1-y0);}
const people=view.detections.filter(d=>d.class==='person'),vehicles=view.detections.filter(d=>d.class!=='person').sort((a,b)=>(b.bbox[2]-b.bbox[0])*(b.bbox[3]-b.bbox[1])-(a.bbox[2]-a.bbox[0])*(a.bbox[3]-a.bbox[1])).slice(0,3),placed=[];
for(const d of [...people,...vehicles]){const color=COLORS[d.class]??'#56e2ed',[x0,y0,x1]=d.bbox;const text=`${ko?NAMES[d.class]:d.class} ${(d.score*100).toFixed(1)}%`;ctx.font='600 27px Arial,"Noto Sans KR",sans-serif';const tw=ctx.measureText(text).width+12;let x=Math.max(0,Math.min(w-tw,x0)),y=Math.max(31,y0);
for(let tries=0;tries<12&&placed.some(p=>x<p.x+p.w+5&&x+tw>p.x-5&&y-31<p.y+5&&y>p.y-31-5);tries++){y-=36;if(y<32){y=Math.max(31,y0);x=Math.min(w-tw,x+tw+6);}}
placed.push({x,y,w:tw});ctx.strokeStyle=color;ctx.lineWidth=1.4;ctx.beginPath();ctx.moveTo(x+tw/2,y);ctx.lineTo((x0+x1)/2,y0);ctx.stroke();ctx.fillStyle='#081819ec';ctx.fillRect(x,y-31,tw,33);ctx.fillStyle=color;ctx.fillText(text,x+6,y-7);
}
}
root.dataset.rgbPerceptionFrame=String(index);root.dataset.rgbPerceptionReady='true';
}
const onCamera=()=>{drawMarkers(data.frames[index]);drawRgb(data.frames[index]).catch(e=>{count.textContent=ko?'RGB 프레임을 불러오지 못했습니다.':'Could not load the RGB frame.';console.error(e);});};select.addEventListener('change',onCamera);
const onToggle=()=>{enabled=!enabled;layer.visible=enabled;toggle.setAttribute('aria-pressed',String(enabled));toggle.textContent=enabled?(ko?'인식 표시 켜짐':'Recognition on'):(ko?'인식 표시 꺼짐':'Recognition off');onCamera();};toggle.addEventListener('click',onToggle);
async function setFrame(i){index=i;const frame=data.frames[i];drawMarkers(frame);await drawRgb(frame);}
await setFrame(index);
return {annotations:()=>enabled?currentObjects.map(o=>({class:o.class,point:[o.ground_position[0],o.ground_position[1],o.ground_position[2]+.25]})):[],setFrame:i=>{setFrame(i).catch(console.error);},state:()=>({enabled,frame:index,camera:select.value,detections_in_camera:viewCount,markers:shown,people_in_camera:data.frames[index].views[select.value]?.detections.filter(d=>d.class==='person').length??0}),dispose(){disposed=true;serial++;select.removeEventListener('change',onCamera);toggle.removeEventListener('click',onToggle);clear();scene.remove(layer);ringGeometry.dispose();poleGeometry.dispose();cached.clear();toolbar.remove();panel.remove();}};
}
record_perception.mjs
View files on GitHub// Record actual RGB detections, segmentation and 3D marker interactions.
// Optional dependency: Playwright 1.60.0. No pre-rendered camera sweep is used.
import fs from 'node:fs';
import path from 'node:path';
import {pathToFileURL} from 'node:url';
const args=Object.fromEntries(process.argv.slice(2).reduce((pairs,s,i,all)=>{if(s.startsWith('--'))pairs.push([s.slice(2),all[i+1]]);return pairs;},[]));
const locale=args.language??'en',url=args.url??`http://127.0.0.1:8091/?lang=${locale}`,out=path.resolve(args.output??'rgb-perception-recording');fs.mkdirSync(out,{recursive:true});
const modulePath=process.env.PLAYWRIGHT_MODULE;const {chromium}=await import(modulePath?(path.isAbsolute(modulePath)?pathToFileURL(modulePath).href:modulePath):'playwright');
const browser=await chromium.launch({headless:true,channel:'chrome',args:process.platform==='darwin'?['--use-angle=metal']:[]});
const context=await browser.newContext({viewport:{width:1280,height:720},deviceScaleFactor:1,recordVideo:{dir:out,size:{width:1280,height:720}}});const page=await context.newPage(),born=Date.now(),video=page.video(),events=[],errors=[];
page.on('pageerror',e=>errors.push(e.message));page.on('console',m=>{if(m.type()==='error')errors.push(m.text());});
try{
await page.goto(url);await page.locator('[data-rgb-load]').click();await page.waitForSelector('[data-rgb-ready=true]',{timeout:120000});await page.waitForTimeout(1000);const trimStart=(Date.now()-born)/1000;
const root=page.locator('[data-rgb-viewer]'),stage=page.locator('[data-rgb-stage]'),box=await stage.boundingBox();
const snapshot=async action=>events.push({action,time_seconds:(Date.now()-born)/1000-trimStart,...await root.evaluate(r=>r.rgbViewerState())});
const drag=async(dx,dy,button='left')=>{const x=box.x+box.width*.43,y=box.y+box.height*.57;await page.mouse.move(x,y);await page.mouse.down({button});for(let i=1;i<=50;i++){await page.mouse.move(x+dx*i/50,y+dy*i/50);await page.waitForTimeout(32);}await page.mouse.up({button});await page.waitForTimeout(400);};
const initial=await root.evaluate(r=>r.rgbViewerState());if(!initial.perception||initial.perception.people_in_camera<1)throw new Error('Expected actual pedestrian detections in the selected RGB camera');
await snapshot('initial');await page.screenshot({path:path.join(out,`rgb-perception.${locale}.jpg`),type:'jpeg',quality:90});await page.waitForTimeout(2200);
await page.locator('[data-rgb-recognition]').click();await page.waitForTimeout(1600);await snapshot('recognition_off');
await page.locator('[data-rgb-recognition]').click();await page.waitForTimeout(1800);await snapshot('recognition_on');
await page.locator('[data-rgb-camera]').selectOption('front_camera');await page.waitForTimeout(1700);await snapshot('front_camera');
await page.locator('[data-rgb-camera]').selectOption('left_camera');await page.waitForTimeout(1700);await snapshot('left_camera');
await drag(-box.height*.45,0);await snapshot('orbit');await page.waitForTimeout(1300);
await page.locator('[data-rgb-preset=overhead]').click();await page.waitForTimeout(2200);await snapshot('overhead');
await page.locator('[data-rgb-preset=driver]').click();await page.locator('[data-rgb-camera]').selectOption('front_camera');await page.waitForTimeout(2400);await snapshot('driver');
await page.locator('[data-rgb-preset=chase]').click();await page.locator('[data-rgb-camera]').selectOption('left_camera');await page.locator('[data-rgb-play]').click();await page.waitForTimeout(4300);await page.locator('[data-rgb-play]').click();await snapshot('perception_replay');await page.waitForTimeout(1800);
if(events[0].camera.every((v,i)=>Math.abs(v-events.find(e=>e.action==='orbit').camera[i])<.01))throw new Error('Drag did not change camera pose');
if(events.at(-1).frame===events[0].frame)throw new Error('Path playback did not change the estimated frame');
if(events.find(e=>e.action==='recognition_off').perception.enabled||!events.find(e=>e.action==='recognition_on').perception.enabled)throw new Error('Recognition toggle failed');
if(errors.length)throw new Error('Viewer errors: '+errors.join('; '));
const duration=(Date.now()-born)/1000-trimStart;await context.close();const file=await video.path();const raw=path.join(out,`raw-perception.${locale}.webm`);fs.renameSync(file,raw);
fs.writeFileSync(path.join(out,`perception-interaction.${locale}.json`),JSON.stringify({language:locale,recording:'Actual browser viewport, driven by Playwright mouse/scroll/buttons',trim_start_seconds:trimStart,content_seconds:duration,viewport:[1280,720],events,errors,raw_file:path.basename(raw)},null,2));console.log('RECORDED',locale,duration.toFixed(2),'seconds,',events.length,'interaction checks');
}finally{await browser.close();}
viewer.js
View files on GitHub// RGB-only reconstruction viewer. MIT; upstream model/vehicle licenses separate.
import * as T from 'three';
import { mountPolicy } from './policy-view.js';
import { mountPerception } from './perception-view.js';
import { mountEnhancement } from './enhancement-view.js';
import { SparkRenderer, SplatMesh } from '@sparkjsdev/spark';
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
import { RoomEnvironment } from 'three/addons/environments/RoomEnvironment.js';
import { MeshoptDecoder } from 'three/addons/libs/meshopt_decoder.module.js';
export async function mountRgbViewer(root) {
const ko=root.dataset.locale==='ko', base=root.dataset.root.replace(/\/$/,'')+'/';
const stage=root.querySelector('[data-rgb-stage]'), status=root.querySelector('[data-rgb-status]');
const config=await fetch(base+'cameras.json').then(r=>{if(!r.ok)throw new Error('Missing camera reconstruction');return r.json();});
const guidanceFile=root.dataset.rgbGuidance??config.guidance_file;
const guidance=guidanceFile?await fetch(base+guidanceFile).then(r=>{if(!r.ok)throw new Error('Missing guidance manifest');return r.json();}):null;
const variants=guidance?.variants??[];let variant=variants.find(v=>v.id===guidance?.default)??null;
if(guidance&&!root.querySelector('[data-rgb-variant]')){
const wrapper=document.createElement('div');wrapper.className='rgb-variants';const label=document.createElement('label');label.textContent=ko?'복원 모델 비교':'Compare reconstruction models';
const select=document.createElement('select');select.dataset.rgbVariant='';select.disabled=true;label.append(select);const note=document.createElement('p');note.dataset.rgbVariantNote='';wrapper.append(label,note);(root.querySelector('.rgb-toolbar')??stage).after(wrapper);
}
root.dataset.rgbBackend=config.backend??'standalone-3dgut';if(config.reconstruction_title){const chip=root.querySelector('.rgb-chip');if(chip)chip.textContent=config.reconstruction_title;}
const renderer=new T.WebGLRenderer({antialias:false,alpha:false,powerPreference:'high-performance'});
renderer.setPixelRatio(Math.min(devicePixelRatio,1.5));renderer.setClearColor('#ccd3d9');renderer.toneMapping=T.ACESFilmicToneMapping;renderer.toneMappingExposure=1.0;renderer.shadowMap.enabled=true;renderer.shadowMap.type=T.PCFSoftShadowMap;
const canvas=renderer.domElement;canvas.tabIndex=0;canvas.setAttribute('aria-label',ko?'RGB로 복원한 도로와 Volvo의 3D 장면':'3D road reconstructed from RGB, with a Volvo reference');stage.append(canvas);
const scene=new T.Scene(),referenceScene=new T.Scene();renderer.autoClear=false;
const pmrem=new T.PMREMGenerator(renderer),room=new RoomEnvironment();const environment=pmrem.fromScene(room,.04);referenceScene.environment=environment.texture;room.dispose();pmrem.dispose();
referenceScene.add(new T.HemisphereLight(0xe4f0ff,0x66645d,2.5));
const sun=new T.DirectionalLight(0xfff7eb,3.1);sun.position.set(-3,-4,9);sun.castShadow=true;sun.shadow.mapSize.set(1024,1024);sun.shadow.camera.left=-8;sun.shadow.camera.right=8;sun.shadow.camera.top=8;sun.shadow.camera.bottom=-8;sun.shadow.normalBias=.025;referenceScene.add(sun);referenceScene.add(sun.target);
const shadow=new T.Mesh(new T.PlaneGeometry(150,150),new T.ShadowMaterial({opacity:.16,depthWrite:false}));shadow.receiveShadow=true;shadow.position.z=-.015;referenceScene.add(shadow);
const camera=new T.PerspectiveCamera(64,16/9,.025,250);camera.up.set(0,0,1);camera.layers.enable(1);
const controls=new OrbitControls(camera,canvas);controls.enableDamping=true;controls.dampingFactor=.12;controls.minDistance=1.2;controls.maxDistance=24;controls.maxPolarAngle=Math.PI*.49;controls.screenSpacePanning=true;
const spark=new SparkRenderer({renderer});scene.add(spark);
let splats=new SplatMesh({url:base+(variant?.file??'road.spz')});scene.add(splats);
const placeSplats=mesh=>new T.Matrix4().set(...config.world_to_viewer.flat()).decompose(mesh.position,mesh.quaternion,mesh.scale);
placeSplats(splats);
const gltf=await new GLTFLoader().setMeshoptDecoder(MeshoptDecoder).loadAsync(base+config.vehicle.file);
const car=new T.Group();const vehicle=gltf.scene;vehicle.rotation.x=Math.PI/2;vehicle.scale.setScalar(config.vehicle.scale);car.add(vehicle);referenceScene.add(car);
vehicle.traverse(o=>{if(o.isMesh){o.castShadow=true;o.receiveShadow=false;}});
const slider=root.querySelector('[data-rgb-frame]'), play=root.querySelector('[data-rgb-play]'), frameLabel=root.querySelector('[data-rgb-time]');
slider.max=String(config.frames.length-1);slider.value=String(config.default_frame);let index=config.default_frame,playing=false,clock=0,view='chase',visible=true,disposed=false;
const offset=new T.Vector3(-4.3,-3.1,2.8), lastGround=new T.Vector3(), carTarget=new T.Vector3();
let perception,policy,enhancement,capturePending;
const framePosition=(frame)=>new T.Vector3(...frame.ground_position);
function setFrame(value,{initial=false}={}) {
index=Math.max(0,Math.min(config.frames.length-1,Number(value)));const frame=config.frames[index];const p=framePosition(frame);const delta=p.clone().sub(lastGround);car.position.copy(p);car.rotation.z=frame.yaw_radians;carTarget.copy(p).add(new T.Vector3(0,0,.43));
if(!initial){camera.position.add(delta);controls.target.add(delta);}lastGround.copy(p);slider.value=String(index);frameLabel.textContent=`${frame.time_seconds.toFixed(1)} s · ${index+1}/${config.frames.length}`;
shadow.position.set(p.x,p.y,-.015);sun.position.copy(p).add(new T.Vector3(-3,-4,9));sun.target.position.copy(p);
if(view==='driver')setPreset('driver');perception?.setFrame(index);policy?.setFrame(index);root.dataset.frame=String(index);
}
function setPreset(name) {
view=name;car.visible=name!=='driver';const frame=config.frames[index];const yaw=frame.yaw_radians;const q=new T.Quaternion().setFromAxisAngle(new T.Vector3(0,0,1),yaw);
if(name==='driver'){
camera.position.set(...frame.camera_position);const R=frame.camera_rotation_opencv;
const forward=new T.Vector3(R[0][2],R[1][2],R[2][2]);controls.target.copy(camera.position).addScaledVector(forward,5);camera.fov=2*Math.atan(frame.image_size[1]/(2*frame.K[1][1]))*180/Math.PI;
}else {
const offsets={chase:guidance?.chase_offset??[-3.4,-2.6,2.2],rear:[-5.2,0,1.8],side:[0,-5.2,2.0],overhead:[-.4,0,6.5]};offset.set(...(offsets[name]||offsets.chase)).applyQuaternion(q);camera.position.copy(carTarget).add(offset);controls.target.copy(carTarget);camera.fov=64;
}
camera.updateProjectionMatrix();controls.update();root.dataset.view=name;
root.querySelectorAll('[data-rgb-preset]').forEach(b=>b.setAttribute('aria-pressed',String(b.dataset.rgbPreset===name)));
}
setFrame(index,{initial:true});setPreset('chase');
const onInput=()=>{playing=false;play.textContent=ko?'경로 재생':'Play path';setFrame(slider.value);};slider.addEventListener('input',onInput);
const onPlay=()=>{playing=!playing;clock=0;play.textContent=playing?(ko?'일시 정지':'Pause'):(ko?'경로 재생':'Play path');};play.addEventListener('click',onPlay);
const presetHandlers=[];root.querySelectorAll('[data-rgb-preset]').forEach(b=>{const handler=()=>setPreset(b.dataset.rgbPreset);b.addEventListener('click',handler);presetHandlers.push([b,handler]);});
// Real pointer events drive OrbitControls. A small cursor ring also makes
// recorded tutorials readable; it never changes the camera or rendered scene.
const cursor=root.querySelector('[data-rgb-cursor]');
const pointer=e=>{if(cursor){const b=stage.getBoundingClientRect();cursor.style.transform=`translate(${e.clientX-b.left}px,${e.clientY-b.top}px)`;cursor.hidden=false;}};
const leave=()=>{if(cursor)cursor.hidden=true;};canvas.addEventListener('pointermove',pointer);canvas.addEventListener('pointerleave',leave);
const orbit=()=>{if(view==='driver'){view='free';root.dataset.view='free';}};controls.addEventListener('start',orbit);
const resize=new ResizeObserver(()=>{camera.aspect=stage.clientWidth/stage.clientHeight;camera.updateProjectionMatrix();renderer.setSize(stage.clientWidth,stage.clientHeight);});resize.observe(stage);
const observer=new IntersectionObserver(([entry])=>{visible=entry.isIntersecting;});observer.observe(stage);
let last=performance.now();renderer.setAnimationLoop(()=>{const now=performance.now(),dt=Math.min((now-last)/1000,.08);last=now;if(disposed||(!visible&&!capturePending)||document.hidden)return;
if(playing){clock+=dt;const step=config.frames[Math.min(index+1,config.frames.length-1)].time_seconds-config.frames[index].time_seconds||.3;if(clock>=step){clock=0;setFrame((index+1)%config.frames.length);}}
controls.update();const captureLayers=camera.layers.mask;if(capturePending)camera.layers.disable(1);renderer.clear();renderer.render(scene,camera);renderer.clearDepth();renderer.render(referenceScene,camera);
if(capturePending){
const request=capturePending;capturePending=null;clearTimeout(request.timer);
try{
const w=canvas.width,h=canvas.height;let cw=w,ch=h;
if(w/h>16/9)cw=h*16/9;else ch=w*9/16;
const output=document.createElement('canvas');output.width=1024;output.height=576;const context=output.getContext('2d');context.drawImage(canvas,(w-cw)/2,(h-ch)/2,cw,ch,0,0,1024,576);
const direction=camera.getWorldDirection(new T.Vector3());const state=root.rgbViewerState();
const project=point=>{const v=new T.Vector3(...point).project(camera);const x=((v.x+1)*w/2-(w-cw)/2)/cw*1024,y=((1-v.y)*h/2-(h-ch)/2)/ch*576;return v.z>-1&&v.z<1&&x>=0&&x<=1024&&y>=0&&y<=576?[x,y]:null;};
const annotations=(perception?.annotations?.()??[]).slice(0,24).map(o=>({class:o.class,point:project(o.point)})).filter(o=>o.point);const path=(policy?.annotations?.()??[]).map(project);
request.resolve({image:output.toDataURL('image/png').split(',')[1],view:{camera:camera.position.toArray(),forward:direction.toArray(),frame:index,time_seconds:config.frames[index].time_seconds,preset:view,variant:state.variant,crop_xywh:[(w-cw)/2,(h-ch)/2,cw,ch],source_canvas:[w,h],output_size:[1024,576],projection:[camera.fov,camera.aspect,cw/w,ch/h],annotations,path}});
}catch(error){request.reject(error);}
finally{camera.layers.mask=captureLayers;renderer.clear();renderer.render(scene,camera);renderer.clearDepth();renderer.render(referenceScene,camera);}
}
});
await splats.initialized;perception=await mountPerception({root,stage,scene:referenceScene,base,ko,config});policy=await mountPolicy({root,scene:referenceScene,base,config,ko});root.querySelector('.rgb-poster')?.remove();root.dataset.rgbReady='true';status.textContent=ko?'드래그해서 회전하고 휠로 확대해 보세요. 입력은 RGB 사진뿐입니다.':'Drag to orbit and scroll to zoom. Reconstruction inputs are RGB images only.';
const variantSelect=root.querySelector('[data-rgb-variant]'),variantNote=root.querySelector('[data-rgb-variant-note]');
const updateVariantNote=()=>{if(variantNote)variantNote.textContent=variant?.[ko?'note_ko':'note_en']??'';root.dataset.rgbModel=variant?.id??'original';};
if(variantSelect&&variants.length){
for(const v of variants){const option=document.createElement('option');option.value=v.id;option.textContent=v[ko?'label_ko':'label_en'];variantSelect.append(option);}
variantSelect.value=variant.id;variantSelect.disabled=false;updateVariantNote();
}
const changeVariant=async()=>{
const selected=variants.find(v=>v.id===variantSelect.value);if(!selected||selected===variant)return;
variantSelect.disabled=true;status.textContent=ko?'같은 시점에서 비교할 모델을 불러오는 중…':'Loading the comparison model at the same viewpoint…';
let next;
try{
next=new SplatMesh({url:base+selected.file});placeSplats(next);await next.initialized;
if(disposed){next.dispose();return;}
scene.remove(splats);splats.dispose();splats=next;scene.add(splats);variant=selected;updateVariantNote();
status.textContent=ko?'모델을 바꿨습니다. 카메라 시점과 프레임은 유지됩니다.':'Model changed. Camera viewpoint and frame are unchanged.';
}catch(error){next?.dispose();variantSelect.value=variant.id;status.textContent=ko?'비교 모델을 열지 못했습니다. 현재 장면을 유지합니다.':'Could not load this model. The current scene is preserved.';console.error(error);}
finally{if(!disposed)variantSelect.disabled=false;}
};
variantSelect?.addEventListener('change',changeVariant);
root.querySelectorAll('[data-rgb-frame],[data-rgb-play],[data-rgb-preset]').forEach(el=>el.disabled=false);
// Read-only debug state supports automated interaction checks without replacing
// real pointer/scroll events with a pre-rendered video or camera animation.
root.rgbViewerState=()=>({frame:index,view,variant:variant?.id??'original',camera:camera.position.toArray(),target:controls.target.toArray(),gaussians:splats.packedSplats?.numSplats??null,perception:perception?.state()??null,policy:policy?.state()??null});
root.rgbViewerCapture=()=>new Promise((resolve,reject)=>{
if(disposed||capturePending){reject(new Error('A capture is already pending or the viewer is closed'));return;}
const request={resolve,reject};request.timer=setTimeout(()=>{if(capturePending===request){capturePending=null;reject(new Error('The3Dviewer is not rendering; bring it into view'));}},5000);capturePending=request;
});
enhancement=mountEnhancement({root,config,ko});
return ()=>{enhancement?.();if(capturePending){clearTimeout(capturePending.timer);capturePending.reject(new Error('Viewer closed'));capturePending=null;}delete root.rgbViewerCapture;policy?.dispose();perception?.dispose();disposed=true;variantSelect?.removeEventListener('change',changeVariant);renderer.setAnimationLoop(null);resize.disconnect();observer.disconnect();slider.removeEventListener('input',onInput);play.removeEventListener('click',onPlay);presetHandlers.forEach(([b,h])=>b.removeEventListener('click',h));canvas.removeEventListener('pointermove',pointer);canvas.removeEventListener('pointerleave',leave);controls.removeEventListener('start',orbit);controls.dispose();splats.dispose();spark.dispose();vehicle.traverse(o=>{if(o.geometry)o.geometry.dispose();if(o.material){for(const m of Array.isArray(o.material)?o.material:[o.material])m.dispose();}});environment.dispose();shadow.geometry.dispose();shadow.material.dispose();renderer.dispose();renderer.forceContextLoss();canvas.remove();delete root.dataset.rgbReady;delete root.rgbViewerState;};
}
record_tour.mjs
View files on GitHub// Record real pointer/scroll/button interactions with the RGB 3D viewer.
// Optional dependency: Playwright 1.60.0. No pre-rendered camera sweep is used.
import fs from 'node:fs';
import path from 'node:path';
import {pathToFileURL} from 'node:url';
const args=Object.fromEntries(process.argv.slice(2).reduce((pairs,s,i,all)=>{if(s.startsWith('--'))pairs.push([s.slice(2),all[i+1]]);return pairs;},[]));
const locale=args.language??'en',url=args.url??`http://127.0.0.1:8090/?lang=${locale}`,out=path.resolve(args.output??'rgb-viewer-recording');fs.mkdirSync(out,{recursive:true});
const modulePath=process.env.PLAYWRIGHT_MODULE;const {chromium}=await import(modulePath?(path.isAbsolute(modulePath)?pathToFileURL(modulePath).href:modulePath):'playwright');
const browser=await chromium.launch({headless:true,channel:'chrome',args:process.platform==='darwin'?['--use-angle=metal']:[]});
const context=await browser.newContext({viewport:{width:1280,height:720},deviceScaleFactor:1,recordVideo:{dir:out,size:{width:1280,height:720}}});const page=await context.newPage(),born=Date.now(),video=page.video(),events=[],errors=[];
page.on('pageerror',e=>errors.push(e.message));page.on('console',m=>{if(m.type()==='error')errors.push(m.text());});
try{
await page.goto(url);await page.locator('[data-rgb-load]').click();await page.waitForSelector('[data-rgb-ready=true]',{timeout:120000});await page.waitForTimeout(1000);const trimStart=(Date.now()-born)/1000;
const root=page.locator('[data-rgb-viewer]'),stage=page.locator('[data-rgb-stage]'),box=await stage.boundingBox();
const snapshot=async action=>events.push({action,time_seconds:(Date.now()-born)/1000-trimStart,...await root.evaluate(r=>r.rgbViewerState())});
const drag=async(dx,dy,button='left')=>{const x=box.x+box.width*.72,y=box.y+box.height*.48;await page.mouse.move(x,y);await page.mouse.down({button});for(let i=1;i<=50;i++){await page.mouse.move(x+dx*i/50,y+dy*i/50);await page.waitForTimeout(32);}await page.mouse.up({button});await page.waitForTimeout(400);};
await snapshot('initial');await page.screenshot({path:path.join(out,`rgb-reality-view.${locale}.jpg`),type:'jpeg',quality:90});await page.waitForTimeout(1700);
await drag(-box.height*.48,0);await snapshot('orbit_first_half');await page.waitForTimeout(1100);
await drag(-box.height*.48,0);await snapshot('orbit_second_half');await page.waitForTimeout(1100);
await drag(0,-box.height*.08);await snapshot('tilt');await page.mouse.wheel(0,-220);await page.waitForTimeout(1300);await snapshot('zoom');
await drag(75,-10,'right');await snapshot('pan');await page.waitForTimeout(800);
await page.locator('[data-rgb-preset=driver]').click();await page.waitForTimeout(2400);await snapshot('driver');
await page.locator('[data-rgb-preset=side]').click();await page.waitForTimeout(1500);await snapshot('side');
await page.locator('[data-rgb-preset=chase]').click();await page.locator('[data-rgb-play]').click();await page.waitForTimeout(3500);await page.locator('[data-rgb-play]').click();await snapshot('path_replay');await page.waitForTimeout(1600);
if(events[0].camera.every((v,i)=>Math.abs(v-events[1].camera[i])<.01))throw new Error('Drag did not change camera pose');
if(events.at(-1).frame===events[0].frame)throw new Error('Path playback did not change the estimated frame');
if(errors.length)throw new Error('Viewer errors: '+errors.join('; '));
const duration=(Date.now()-born)/1000-trimStart;await context.close();const file=await video.path();const raw=path.join(out,`raw-tour.${locale}.webm`);fs.renameSync(file,raw);
fs.writeFileSync(path.join(out,`interaction.${locale}.json`),JSON.stringify({language:locale,recording:'Actual browser viewport, driven by Playwright mouse/scroll/buttons',trim_start_seconds:trimStart,content_seconds:duration,viewport:[1280,720],events,errors,raw_file:path.basename(raw)},null,2));console.log('RECORDED',locale,duration.toFixed(2),'seconds,',events.length,'interaction checks');
}finally{await browser.close();}
check.py
View files on GitHub"""Check published RGB provenance, model geometry and actual browser interactions.
CPU only, standard library. --decode-video additionally needs FFmpeg on PATH.
This checks integrity and observed execution, not autonomous-driving accuracy.
"""
import argparse
import gzip
import hashlib
import json
import math
from pathlib import Path
import struct
import subprocess
LAB = Path(__file__).resolve().parent
REPO = LAB.parents[1]
def read(name):
return json.loads((LAB / name).read_text())
def matrix_ok(matrix):
assert len(matrix) == 3 and all(len(row) == 3 for row in matrix)
assert all(math.isfinite(x) for row in matrix for x in row)
for i in range(3):
for j in range(3):
assert abs(sum(matrix[k][i] * matrix[k][j] for k in range(3)) - (i == j)) < 1e-6
det = sum(matrix[0][i] * (matrix[1][(i+1)%3] * matrix[2][(i+2)%3] - matrix[1][(i+2)%3] * matrix[2][(i+1)%3]) for i in range(3))
assert abs(det - 1) < 1e-6
def main(decode=False):
report = read('recorded.json')
assert report['pipeline']['inputs'] == ['RGB pixels']
manifest = read('evidence/input-manifest.json')
assert len(manifest['images']) == 162
assert manifest['external_sensor_inputs'] == []
assert not any(manifest[k] for k in ['supplied_camera_poses', 'supplied_intrinsics', 'supplied_depth', 'supplied_ground_plane'])
assert hashlib.sha256((LAB / 'evidence/input-manifest.json').read_bytes()).hexdigest() == report['training']['input_manifest_sha256']
download = read('evidence/download-result.json')
assert download['downloaded_modalities'] == ['RGB JPEG'] and len(download['files']) == 162
assert all(Path(row['file']).suffix == '.jpg' for row in download['files'])
assert {row['file'] for row in download['files']} == {row['image'] for row in manifest['images']}
sfm = read('evidence/sfm-result.json')
assert sfm['registered_images'] == sfm['input_images'] == 162
assert sfm['sparse_points'] > 20000 and sfm['mean_reprojection_error_px'] < 2
assert sfm['selected_model'] == 'sfm-selected'
assert report['training']['training_steps'] == 16000
assert report['training']['training_loop_seconds'] > 0 and report['training']['gpu_count'] == 1
scene = REPO / 'site/public/showcase/rgb-reality-view'
with gzip.open(scene / 'road.spz', 'rb') as f:
header = f.read(16)
magic, version, count = struct.unpack('<III', header[:12])
assert magic == 0x5053474E and version == 3 and count == report['viewer']['gaussians'] == 400000
assert header[12] == 1 # retained spherical-harmonics degree
car = (scene / 'volvo-s90.glb').read_bytes()
assert car[:4] == b'glTF' and struct.unpack('<I', car[4:8])[0] == 2
assert struct.unpack('<I', car[8:12])[0] == len(car)
geometry = json.loads((scene / 'cameras.json').read_text())
assert len(geometry['frames']) == 27 and geometry['road_plane_inliers'] >= 25
assert 'RGB' in geometry['road_plane_source'] and 'not measured meters' in geometry['units']
T = geometry['world_to_viewer']
assert len(T) == 4 and T[3] == [0, 0, 0, 1]
scale = math.sqrt(sum(T[0][j]**2 for j in range(3)))
assert scale > 0
matrix_ok([[T[i][j] / scale for j in range(3)] for i in range(3)])
last = -1
for frame in geometry['frames']:
assert frame['time_seconds'] > last
last = frame['time_seconds']
matrix_ok(frame['camera_rotation_opencv'])
assert frame['K'][0][0] > 0 and frame['K'][1][1] > 0
assert all(math.isfinite(x) for x in frame['camera_position'] + frame['ground_position'])
for lang in ['en', 'ko']:
trace = read(f'evidence/interaction.{lang}.json')
assert trace['errors'] == [] and len(trace['events']) == 9
events = {e['action']: e for e in trace['events']}
assert all(e['gaussians'] == count for e in events.values())
assert math.dist(events['initial']['camera'], events['orbit_first_half']['camera']) > .1
assert events['path_replay']['frame'] != events['initial']['frame']
assert events['driver']['view'] == 'driver' and events['side']['view'] == 'side'
for name, expected in report['files'].items():
path = REPO / name
assert path.resolve().is_relative_to(REPO.resolve())
assert path.stat().st_size == expected['bytes'], name
assert hashlib.sha256(path.read_bytes()).hexdigest() == expected['sha256'], name
if decode and path.suffix == '.mp4':
subprocess.run(['ffmpeg', '-v', 'error', '-i', str(path), '-f', 'null', '-'], check=True)
import runpy
runpy.run_path(str(LAB/'check_perception.py'))['main'](decode=decode)
print('Verified 162 RGB-only inputs, estimated cameras, 400k Gaussians, 27 poses, bilingual mouse traces and artifact hashes.')
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--decode-video', action='store_true')
main(parser.parse_args().decode_video)
