#!/usr/bin/env python3 from __future__ import annotations import csv import io import json import multiprocessing as mp import os import shutil import sys import tempfile import time import zipfile from pathlib import Path from typing import Mapping import numpy as np # Keep the environment's numpy/torch/cv2, then add the temporary HDF5 deps. sys.path.insert(0, "/tmp/dsec_deps") import cv2 import h5py import hdf5plugin # noqa: F401 - registers compressed HDF5 filters import torch import yaml from PIL import Image BASE = Path("/data/fcr/data/train_data/DSEC") OUT_SIZE = (512, 512) NUM_BINS = 4 DISPARITY_SCALE = 256.0 SEQUENCES = [ ("interlaken_00_e", "screen-000002-dsec"), ("zurich_city_02_b", "screen-000003-dsec"), ] PRELOAD_EVENTS = True PRECOMPUTE_COORDS = False WORKERS = 12 WORK_EVENT_SOURCE: Mapping[str, np.ndarray] | None = None WORK_RECTIFY_MAP: np.ndarray | None = None WORK_PARTIAL: Path | None = None WORK_IMAGE_ZIP: zipfile.ZipFile | None = None WORK_DISP_ZIP: zipfile.ZipFile | None = None WORK_FX = 0.0 WORK_Q32 = 0.0 WORK_EVENT_OFFSET = 0 WORK_IMAGE_TS: list[int] = [] WORK_DISPARITY_TS: list[int] = [] def read_timestamps(path: Path) -> list[int]: out: list[int] = [] with path.open("r", encoding="utf-8") as f: for line in f: line = line.strip() if not line or line.startswith("#"): continue out.append(int(line.split(",")[0])) return out def load_calibration(seq: str) -> dict: with zipfile.ZipFile(BASE / f"{seq}_calibration.zip") as zf: return yaml.safe_load(zf.read("cam_to_cam.yaml")) def write_cameras(out_dir: Path, calib: dict) -> tuple[float, float]: rect = calib["intrinsics"]["camRect1"] width, height = rect["resolution"] fx, fy, cx, cy = rect["camera_matrix"] sx = OUT_SIZE[0] / width sy = OUT_SIZE[1] / height intrinsics = [fx * sx, fy * sy, cx * sx, cy * sy] cam = { "distortion_model": "none", "distortion_coeffs": [0.0, 0.0, 0.0, 0.0], "intrinsics": intrinsics, "resolution": [OUT_SIZE[0], OUT_SIZE[1]], } cameras = { "event_cam": cam, "rgb_cam_full": cam, "rgb_cam_crop": { "distortion_model": "none", "distortion_coeffs": [0.0, 0.0, 0.0, 0.0], "intrinsics": intrinsics, "resolution": [OUT_SIZE[0], OUT_SIZE[1]], "crop_offset_xy": [0, 0], }, } with (out_dir / "cameras.yaml").open("w", encoding="utf-8") as f: yaml.safe_dump(cameras, f, sort_keys=False) q32 = float(calib["disparity_to_depth"]["cams_12"][3][2]) return float(fx), q32 def write_meta_json(out_dir: Path, seq: str, frames: int, event_offset: int) -> None: meta = { "source": "DSEC", "sequence": seq, "frames": frames, "image_size": [OUT_SIZE[0], OUT_SIZE[1]], "event_window": "between_frames", "num_bins": NUM_BINS, "disparity_scale": DISPARITY_SCALE, "depth_formula": "depth = fx / ((disp_raw / disparity_scale) * Q[3,2])", "depth_source": "dsec/disparity_image", "depth_units": "meters", "depth_invalid_value": 0.0, "depth_protocol": "sparse_metric_depth_zero_invalid", "depth_protocol_note": ( "Metric depth in the rectified RGB/event camera plane with zero as invalid. " "Semantically compatible with MVSEC depth_gt, but typically much sparser " "because the source is a disparity image." ), "event_time_offset_us": event_offset, "event_rectified": True, "event_alignment_note": ( "DSEC event x/y are mapped through events_left/rectify_map.h5 to the " "rectified event camera plane, then resized to the training image size. " "This is not a full depth-aware event-camera to frame-camera projection." ), } with (out_dir / "meta.json").open("w", encoding="utf-8") as f: json.dump(meta, f, indent=2) f.write("\n") def extract_events_zip(seq: str, temp_root: Path) -> tuple[Path, Path]: with zipfile.ZipFile(BASE / f"{seq}_events_left.zip") as zf: events_h5 = Path(zf.extract("events.h5", temp_root)) rectify_h5 = Path(zf.extract("rectify_map.h5", temp_root)) return events_h5, rectify_h5 def make_event_tensor( event_source: Mapping[str, np.ndarray], event_offset: int, rectify_map: np.ndarray, start_us: int, end_us: int, ) -> tuple[np.ndarray, int]: t_ds = event_source["t"] offset = event_offset start_rel = start_us - offset end_rel = end_us - offset lo = int(np.searchsorted(t_ds, start_rel, side="left")) hi = int(np.searchsorted(t_ds, end_rel, side="right")) num_events = hi - lo grid_size = 2 * NUM_BINS * OUT_SIZE[0] * OUT_SIZE[1] if num_events <= 0: return np.zeros((2 * NUM_BINS, OUT_SIZE[1], OUT_SIZE[0]), dtype=np.float32), 0 t_rel = t_ds[lo:hi] if "xi" in event_source: xi = event_source["xi"][lo:hi].astype(np.int64, copy=False) yi = event_source["yi"][lo:hi].astype(np.int64, copy=False) valid = event_source["valid"][lo:hi] polarity = event_source["polarity"][lo:hi].astype(np.int64, copy=False) else: x = event_source["x"][lo:hi] y = event_source["y"][lo:hi] polarity = event_source["p"][lo:hi].astype(np.int64) rect_x = rectify_map[y, x, 0].astype(np.float64) rect_y = rectify_map[y, x, 1].astype(np.float64) xi = np.floor(rect_x * (OUT_SIZE[0] / 640.0)).astype(np.int64) yi = np.floor(rect_y * (OUT_SIZE[1] / 480.0)).astype(np.int64) valid = (xi >= 0) & (xi < OUT_SIZE[0]) & (yi >= 0) & (yi < OUT_SIZE[1]) polarity = 1 - polarity if not np.any(valid): return np.zeros((2 * NUM_BINS, OUT_SIZE[1], OUT_SIZE[0]), dtype=np.float32), num_events xi = xi[valid] yi = yi[valid] t_rel = t_rel[valid] polarity = polarity[valid] duration = max(1, end_us - start_us) pos = ((t_rel.astype(np.float64) - float(start_rel)) / float(duration)) * float(NUM_BINS - 1) bin_lo = np.floor(pos).astype(np.int64) bin_hi = bin_lo + 1 w_hi = pos - bin_lo w_lo = 1.0 - w_hi flat_hw = OUT_SIZE[0] * OUT_SIZE[1] accum = np.zeros(grid_size, dtype=np.float64) mask = (bin_lo >= 0) & (bin_lo < NUM_BINS) if np.any(mask): flat = (polarity[mask] * NUM_BINS + bin_lo[mask]) * flat_hw + yi[mask] * OUT_SIZE[0] + xi[mask] accum += np.bincount(flat, weights=w_lo[mask], minlength=grid_size) mask = (bin_hi >= 0) & (bin_hi < NUM_BINS) if np.any(mask): flat = (polarity[mask] * NUM_BINS + bin_hi[mask]) * flat_hw + yi[mask] * OUT_SIZE[0] + xi[mask] accum += np.bincount(flat, weights=w_hi[mask], minlength=grid_size) grid = accum.astype(np.float32).reshape(2 * NUM_BINS, OUT_SIZE[1], OUT_SIZE[0]) active = grid != 0 if np.any(active): values = grid[active] grid[active] = (values - values.mean()) / (values.std() + 1e-12) return grid, num_events def make_depth_tensor(disp_png: bytes, fx: float, q32: float) -> np.ndarray: disp = np.array(Image.open(io.BytesIO(disp_png)), dtype=np.float32) disp = cv2.resize(disp, OUT_SIZE, interpolation=cv2.INTER_NEAREST) depth = np.zeros_like(disp, dtype=np.float32) valid = disp > 0 depth[valid] = fx / ((disp[valid] / DISPARITY_SCALE) * q32) return depth def init_worker( seq: str, partial: str, fx: float, q32: float, event_offset: int, image_ts: list[int], disparity_ts: list[int], ) -> None: global WORK_PARTIAL, WORK_IMAGE_ZIP, WORK_DISP_ZIP global WORK_FX, WORK_Q32, WORK_EVENT_OFFSET, WORK_IMAGE_TS, WORK_DISPARITY_TS WORK_PARTIAL = Path(partial) WORK_IMAGE_ZIP = zipfile.ZipFile(BASE / f"{seq}_images_rectified_left.zip") WORK_DISP_ZIP = zipfile.ZipFile(BASE / f"{seq}_disparity_image.zip") WORK_FX = fx WORK_Q32 = q32 WORK_EVENT_OFFSET = event_offset WORK_IMAGE_TS = image_ts WORK_DISPARITY_TS = disparity_ts def process_frame_worker(out_idx: int) -> dict: assert WORK_PARTIAL is not None assert WORK_IMAGE_ZIP is not None assert WORK_DISP_ZIP is not None assert WORK_EVENT_SOURCE is not None assert WORK_RECTIFY_MAP is not None source_idx = out_idx * 2 source_file = f"{source_idx:06d}.png" image_timestamp = WORK_IMAGE_TS[source_idx] if out_idx == 0: start_us = WORK_IMAGE_TS[0] end_us = WORK_IMAGE_TS[1] else: start_us = WORK_IMAGE_TS[source_idx - 1] end_us = WORK_IMAGE_TS[source_idx] image = Image.open(io.BytesIO(WORK_IMAGE_ZIP.read(source_file))).convert("RGB") image = image.resize(OUT_SIZE, Image.Resampling.BILINEAR) image.save(WORK_PARTIAL / "images" / f"{out_idx:06d}.png") depth = make_depth_tensor(WORK_DISP_ZIP.read(source_file), WORK_FX, WORK_Q32) torch.save(torch.from_numpy(depth), WORK_PARTIAL / "depth_gt" / f"{out_idx:06d}.pt") event_grid, num_events = make_event_tensor(WORK_EVENT_SOURCE, WORK_EVENT_OFFSET, WORK_RECTIFY_MAP, start_us, end_us) torch.save(torch.from_numpy(event_grid), WORK_PARTIAL / "events" / f"{out_idx:06d}.pt") center = (start_us + end_us) // 2 depth_valid = depth > 0 depth_median = float(np.median(depth[depth_valid])) if np.any(depth_valid) else 0.0 stats = { "idx": out_idx, "image_name": f"{out_idx:06d}.png", "image_width": OUT_SIZE[0], "image_height": OUT_SIZE[1], "event_shape": [2 * NUM_BINS, OUT_SIZE[1], OUT_SIZE[0]], "depth_shape": [OUT_SIZE[1], OUT_SIZE[0]], "num_events": int(num_events), "event_nonzero_ratio": float(np.count_nonzero(event_grid) / event_grid.size), "event_abs_sum": float(np.abs(event_grid).sum()), "depth_valid_ratio": float(np.count_nonzero(depth_valid) / depth.size), "depth_median": depth_median, "event_window_us": int(end_us - start_us), "event_window_ms": float((end_us - start_us) / 1000.0), } row = [ out_idx, source_idx, source_file, image_timestamp, WORK_DISPARITY_TS[out_idx], start_us, end_us, num_events, ] return { "idx": out_idx, "row": row, "rgb_ts": image_timestamp, "center": center, "window": (start_us, end_us), "stats": stats, } def write_text_meta(meta_dir: Path, rgb_ts: list[int], centers: list[int], windows: list[tuple[int, int]]) -> None: with (meta_dir / "timestamp_rgb_us.txt").open("w", encoding="utf-8") as f: for ts in rgb_ts: f.write(f"{ts}\n") with (meta_dir / "timestamp_event_center_us.txt").open("w", encoding="utf-8") as f: for ts in centers: f.write(f"{ts}\n") with (meta_dir / "event_windows_us.txt").open("w", encoding="utf-8") as f: for start, end in windows: f.write(f"{start},{end}\n") def summarize_stats(stats: list[dict]) -> dict: def triple(key: str) -> list[float]: values = np.array([s[key] for s in stats], dtype=np.float64) return [float(values.min()), float(np.median(values)), float(values.max())] return { "frames": len(stats), "image_size": [OUT_SIZE[0], OUT_SIZE[1]], "event_shape": [2 * NUM_BINS, OUT_SIZE[1], OUT_SIZE[0]], "depth_shape": [OUT_SIZE[1], OUT_SIZE[0]], "event_count_min_median_max": triple("num_events"), "event_nonzero_ratio_min_median_max": triple("event_nonzero_ratio"), "depth_valid_ratio_min_median_max": triple("depth_valid_ratio"), "depth_median_min_median_max": triple("depth_median"), "event_window_ms_min_median_max": triple("event_window_ms"), "preview_video_encoded": False, "preview_video_frames": 0, } def process_sequence(seq: str, target_name: str) -> None: target = BASE / target_name partial = BASE / f"{target_name}.partial" if target.exists(): print(f"[skip] {target} already exists", flush=True) return if partial.exists(): archived = BASE / f"{target_name}.partial.aborted-{int(time.time())}" partial.rename(archived) print(f"[archive] moved old partial output to {archived}", flush=True) print(f"[start] {seq} -> {target_name}", flush=True) partial.mkdir() for subdir in ["images", "events", "depth_gt", "meta", "visual_check"]: (partial / subdir).mkdir(parents=True, exist_ok=True) calib = load_calibration(seq) fx, q32 = write_cameras(partial, calib) image_ts = read_timestamps(BASE / f"{seq}_image_timestamps.txt") disparity_ts = read_timestamps(BASE / f"{seq}_disparity_timestamps.txt") frames = len(disparity_ts) temp_root = Path(tempfile.mkdtemp(prefix=f"dsec_{seq}_", dir="/tmp")) stats: list[dict] = [] rows: list[list[object]] = [] rgb_out_ts: list[int] = [] centers: list[int] = [] windows: list[tuple[int, int]] = [] started = time.time() try: events_h5, rectify_h5 = extract_events_zip(seq, temp_root) with h5py.File(events_h5, "r") as event_file, h5py.File(rectify_h5, "r") as rect_file: event_offset = int(event_file["t_offset"][()]) rectify_map = rect_file["rectify_map"][:] write_meta_json(partial, seq, frames, event_offset) if PRELOAD_EVENTS: events_group = event_file["events"] n_events = int(events_group["t"].shape[0]) estimated_gb = ( events_group["t"].dtype.itemsize + events_group["x"].dtype.itemsize + events_group["y"].dtype.itemsize + events_group["p"].dtype.itemsize ) * n_events / (1024**3) print(f"[preload] {target_name}: loading {n_events} events ({estimated_gb:.1f} GiB)", flush=True) t_all = events_group["t"][:] x_all = events_group["x"][:] y_all = events_group["y"][:] p_all = events_group["p"][:] print(f"[preload] {target_name}: events loaded", flush=True) if PRECOMPUTE_COORDS: print(f"[precompute] {target_name}: rectifying event coordinates", flush=True) rect_x_map = rectify_map[:, :, 0] rect_y_map = rectify_map[:, :, 1] xi_all = np.floor(rect_x_map[y_all, x_all] * (OUT_SIZE[0] / 640.0)).astype(np.int16) yi_all = np.floor(rect_y_map[y_all, x_all] * (OUT_SIZE[1] / 480.0)).astype(np.int16) valid_all = (xi_all >= 0) & (xi_all < OUT_SIZE[0]) & (yi_all >= 0) & (yi_all < OUT_SIZE[1]) polarity_all = (1 - p_all).astype(np.uint8) del x_all, y_all, p_all event_source = { "t": t_all, "xi": xi_all, "yi": yi_all, "valid": valid_all, "polarity": polarity_all, } print(f"[precompute] {target_name}: coordinates ready", flush=True) else: event_source = { "t": t_all, "x": x_all, "y": y_all, "p": p_all, } else: event_source = event_file["events"] global WORK_EVENT_SOURCE, WORK_RECTIFY_MAP WORK_EVENT_SOURCE = event_source WORK_RECTIFY_MAP = rectify_map worker_count = max(1, min(WORKERS, frames, os.cpu_count() or 1)) print(f"[workers] {target_name}: using {worker_count} workers", flush=True) results: list[dict | None] = [None] * frames completed = 0 started = time.time() ctx = mp.get_context("fork") with ctx.Pool( processes=worker_count, initializer=init_worker, initargs=(seq, str(partial), fx, q32, event_offset, image_ts, disparity_ts), ) as pool: for result in pool.imap_unordered(process_frame_worker, range(frames), chunksize=1): results[result["idx"]] = result completed += 1 if completed % 25 == 0 or completed == frames: elapsed = time.time() - started rate = completed / max(elapsed, 1e-9) remaining = (frames - completed) / max(rate, 1e-9) print( f"[progress] {target_name}: {completed}/{frames} " f"({rate:.2f} fps, eta {remaining / 60:.1f} min)", flush=True, ) for result in results: if result is None: raise RuntimeError(f"missing worker result for {target_name}") rows.append(result["row"]) rgb_out_ts.append(result["rgb_ts"]) centers.append(result["center"]) windows.append(result["window"]) stats.append(result["stats"]) write_text_meta(partial / "meta", rgb_out_ts, centers, windows) with (partial / "meta" / "frames_meta.csv").open("w", newline="", encoding="utf-8") as f: writer = csv.writer(f) writer.writerow( [ "out_idx", "source_idx", "source_file", "image_timestamp_us", "disparity_timestamp_us", "event_start_us", "event_end_us", "num_events", ] ) writer.writerows(rows) with (partial / "visual_check" / "stats_per_frame.json").open("w", encoding="utf-8") as f: json.dump(stats, f, indent=2) f.write("\n") with (partial / "visual_check" / "summary.json").open("w", encoding="utf-8") as f: json.dump(summarize_stats(stats), f, indent=2) f.write("\n") partial.rename(target) print(f"[done] {target_name}: {frames} frames", flush=True) finally: shutil.rmtree(temp_root, ignore_errors=True) def main() -> None: for seq, target_name in SEQUENCES: process_sequence(seq, target_name) if __name__ == "__main__": main()