Datasets:
File size: 6,188 Bytes
df3939b | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 | import argparse
import concurrent.futures
import json
from pathlib import Path
import sys
import numpy as np
from scipy import sparse
import torch
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / 'stb_minimal_20261017/trnerf'))
from loaders.loader_captured_ours import _apply_shift
from evaluation.io import sha256, write_json
from evaluation import PROTOCOL
def scene_bounds(scene):
with (ROOT / 'Reconstruction' / scene / 'sp_merged_map.ply').open('rb') as source:
header = []
while True:
line = source.readline().decode('ascii').strip()
header.append(line)
if line == 'end_header':
break
count = int(next(line.split()[-1] for line in header if line.startswith('element vertex')))
points = np.fromfile(source, dtype=[('x', '<f8'), ('y', '<f8'), ('z', '<f8'),
('red', 'u1'), ('green', 'u1'), ('blue', 'u1')], count=count)
coordinates = np.column_stack([points[axis] for axis in ('x', 'y', 'z')])
low, high = coordinates.min(0), coordinates.max(0)
margin = np.maximum((high - low) * 0.05, 0.5)
return np.concatenate([low - margin, high + margin]).tolist()
def prepare_scene(scene):
torch.set_num_threads(2)
source_root = ROOT / 'Reconstruction' / scene
split_root = ROOT / 'Reconstruction/SP-TransientBench_9scenes_train_test' / scene / 'json'
cache = ROOT / 'experiments/data' / scene
reference = ROOT / 'experiments/references' / scene
cache.mkdir(parents=True, exist_ok=True)
reference.mkdir(parents=True, exist_ok=True)
intrinsics = ROOT / 'config/intrinsics.npy'
calibration = np.load(intrinsics, allow_pickle=True).item()
shift = calibration['shift']
if isinstance(shift, torch.Tensor):
shift = shift.cpu().numpy()
valid = np.loadtxt(ROOT / 'config/offset.txt').reshape(192, 256) <= 10
metas = {}
for views in ('three_views', 'five_views', 'ten_views'):
target = cache / views
target.mkdir(exist_ok=True)
for split in ('train', 'test'):
meta = json.loads((split_root / views / f'{split}.json').read_text())
metas[views, split] = meta
converted = dict(meta, frames=[dict(frame, file_path=Path(frame['file_path']).with_suffix('.npz').name)
for frame in meta['frames']])
write_json(target / f'transforms_{split}.json', converted)
train = metas['ten_views', 'train']['frames']
test = metas['ten_views', 'test']['frames']
canonical = {Path(frame['file_path']).stem: frame for frame in test}
for views in ('three_views', 'five_views'):
assert metas[views, 'test']['frames'] == test, f'Canonical tests differ: {scene}/{views}'
training_ids = {Path(frame['file_path']).stem for frame in train}
assert not training_ids.intersection(canonical), f'Train/test overlap: {scene}'
for views in ('three_views', 'five_views'):
subset = {Path(frame['file_path']).stem for frame in metas[views, 'train']['frames']}
assert subset <= training_ids, f'Training subset outside ten-view pool: {scene}/{views}'
peak = display = 0.0
records = {}
frames = {frame['file_path']: frame for frame in train + test}
for filename, frame in frames.items():
stem = Path(filename).stem
cached = cache / f'{stem}.npz'
if cached.exists():
array = sparse.load_npz(cached).toarray()
else:
array = np.loadtxt(source_root / filename, dtype=np.float32)
assert array.shape == (192 * 256, 672), (filename, array.shape)
sparse.save_npz(cached, sparse.csr_matrix(array))
counts = _apply_shift(torch.from_numpy(array.reshape(192, 256, 672)), shift, 7.5e-10).numpy()
if stem in training_ids:
peak = max(peak, float(counts[valid].max()))
display = max(display, float(counts.sum(-1)[valid].max()))
if stem in canonical:
histogram_path = reference / f'{stem}.npy'
mask_path = reference / f'{stem}_mask.npy'
np.save(histogram_path, counts[..., None])
mask = valid & (counts.max(-1) >= 100) & (counts.sum(-1) > 0)
assert mask.any(), f'Empty test mask: {scene}/{stem}'
np.save(mask_path, mask)
records[stem] = dict(frame, file_path=f'{stem}.npz', histogram_path=histogram_path.name,
histogram_sha256=sha256(histogram_path), mask_path=mask_path.name,
mask_sha256=sha256(mask_path), reference_scale=1.0)
contract = dict(protocol=PROTOCOL, scene_id=scene, measurement_root=str(cache),
intrinsics_sha256=sha256(intrinsics), height=192, width=256, n_bins=672,
bin_width_s=7.5e-10, time_start=0, histogram_peak=peak, display_scale=display,
training_frames=train, scale_policy='Maximum calibrated bin count and maximum integrated count over hardware-valid pixels of the ten supplied training frames; shared by 3/5/10 views.',
mask_policy='offset <= 10 AND calibrated GT peak >= 100 AND positive signal',
frames=[records[Path(frame['file_path']).stem] for frame in test])
write_json(reference / 'contract.json', contract)
write_json(cache / 'scene.json', dict(scene=scene, aabb=scene_bounds(scene),
aabb_source='Supplied sp_merged_map.ply extrema, expanded by 5% or 0.5m per axis',
test_frames=len(test), train_frames=10))
print(f'Prepared {scene}: {len(frames)} captures, {len(test)} tests, peak={peak}, display={display}', flush=True)
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--workers', type=int, default=3)
args = parser.parse_args()
scenes = sorted(path.name for path in (ROOT / 'Reconstruction/SP-TransientBench_9scenes_train_test').iterdir())
with concurrent.futures.ProcessPoolExecutor(max_workers=args.workers) as executor:
list(executor.map(prepare_scene, scenes))
|