Download code/agt/dataset/waymo.py from MRBSTUDIO/AGT: direct link, hf CLI and curl.
- Browser
- Download file 17.2 kB
-
https://huggingface.co/MRBSTUDIO/AGT/resolve/main/code/agt/dataset/waymo.py
- Command line
-
hf download hf://MRBSTUDIO/AGT/code/agt/dataset/waymo.py
-
curl -L -o waymo.py https://huggingface.co/MRBSTUDIO/AGT/resolve/main/code/agt/dataset/waymo.py
17.2 kB
| from __future__ import annotations | |
| import io | |
| import json | |
| from dataclasses import dataclass, field | |
| from pathlib import Path | |
| from typing import Any, Iterable, Iterator | |
| import numpy as np | |
| from . import scene_store as store | |
| SOURCE_ID = "waymo" | |
| DATASET_ID = "waymo_front_crop169_v1" | |
| CAMERA_ID = "front_crop169_v1" | |
| SOURCE_CAMERA = "FRONT" | |
| FRONT = 1 | |
| OFFICIAL_SPLITS = ("validation", "testing", "testing_location") | |
| NATIVE_SIZE = (1920, 1280) | |
| CROP_TOP, CROP_BOTTOM = 100, 100 | |
| CROPPED_SIZE = (NATIVE_SIZE[0], NATIVE_SIZE[1] - CROP_TOP - CROP_BOTTOM) | |
| SIZE = store.resize_size(*CROPPED_SIZE) | |
| NOMINAL_FPS = 10 | |
| TIME_OF_DAY = {"Day": "day", "Dawn/Dusk": "dawn", "Night": "night"} | |
| ROLLING_SHUTTER = {1: "top_to_bottom", 2: "left_to_right", 3: "bottom_to_top", 4: "right_to_left", 5: "global"} | |
| PRINCIPAL_POINT_OFFSET = -0.5 | |
| AXES_WAYMO_FROM_OPENCV = np.array([[0.0, 0.0, 1.0, 0.0], | |
| [-1.0, 0.0, 0.0, 0.0], | |
| [0.0, -1.0, 0.0, 0.0], | |
| [0.0, 0.0, 0.0, 1.0]]) | |
| COMPONENTS = ("camera_image", "camera_calibration", "stats") | |
| CI, CC, SC = "[CameraImageComponent].", "[CameraCalibrationComponent].", "[StatsComponent]." | |
| COLUMNS = { | |
| "camera_image": { | |
| "segment": "key.segment_context_name", "timestamp": "key.frame_timestamp_micros", "camera": "key.camera_name", | |
| "image": CI + "image", "pose": CI + "pose.transform", | |
| "v_x": CI + "velocity.linear_velocity.x", "v_y": CI + "velocity.linear_velocity.y", | |
| "v_z": CI + "velocity.linear_velocity.z", "w_x": CI + "velocity.angular_velocity.x", | |
| "w_y": CI + "velocity.angular_velocity.y", "w_z": CI + "velocity.angular_velocity.z", | |
| "pose_timestamp": CI + "pose_timestamp", "shutter": CI + "rolling_shutter_params.shutter", | |
| "trigger": CI + "rolling_shutter_params.camera_trigger_time", | |
| "readout_done": CI + "rolling_shutter_params.camera_readout_done_time"}, | |
| "camera_calibration": { | |
| "segment": "key.segment_context_name", "camera": "key.camera_name", | |
| **{k: CC + "intrinsic." + k for k in ("f_u", "f_v", "c_u", "c_v", "k1", "k2", "p1", "p2", "k3")}, | |
| "extrinsic": CC + "extrinsic.transform", "width": CC + "width", "height": CC + "height", | |
| "rolling_shutter_direction": CC + "rolling_shutter_direction"}, | |
| "stats": {"segment": "key.segment_context_name", "time_of_day": SC + "time_of_day", "location": SC + "location", | |
| "weather": SC + "weather"}, | |
| } | |
| CAMERA_JSON_CONVERSION = { | |
| "version": "waymo_front_metadata_v1", | |
| "principal_point": "integer pixel centres: c - 0.5 (Waymo corner origin), v - 100 (crop), u' = (u + 0.5) * s - 0.5", | |
| "distortion": "recorded (k1, k2, p1, p2, k3), not applied", | |
| "axes": "OpenCV camera axes: camera_to_vehicle = extrinsic @ [[0,0,1],[-1,0,0],[0,-1,0]]", | |
| "pose": "world_from_vehicle = [CameraImageComponent].pose at pose_timestamp, extrapolated with its velocity", | |
| "world": "local = vehicle frame of frame 0 at its pose_timestamp", | |
| "time": "exposure centre of the first / last visible readout line; line k at trigger + shutter/2 + readout*k/(L-1)", | |
| "timestamps": "integer microseconds, round(seconds * 1e6)", | |
| "frames": "every FRONT row of camera_image, sorted by key.frame_timestamp_micros; gaps kept (no fill)", | |
| "scene_stats": "scene_store.scene_statistics_from_video on the written rgb.mp4", | |
| } | |
| def component_path(raw: Path, split: str, component: str, segment: str) -> Path: | |
| return Path(raw) / split / component / f"{segment}.parquet" | |
| def find_split(raw: Path, segment: str) -> str: | |
| found = [s for s in OFFICIAL_SPLITS if component_path(raw, s, "camera_image", segment).is_file()] | |
| if len(found) != 1: | |
| raise FileNotFoundError(f"{segment}: camera_image parquet found in {found or 'no'} split of {raw}") | |
| return found[0] | |
| def read_columns(path: Path, columns: Iterable[str]) -> dict[str, list]: | |
| import pyarrow.parquet as pq | |
| handle = pq.ParquetFile(str(path)) | |
| names = {f.name for f in handle.schema_arrow} | |
| columns = list(columns) | |
| missing = [c for c in columns if c not in names] | |
| if missing: | |
| raise KeyError(f"{path}: missing columns {missing}") | |
| return handle.read(columns=columns).to_pydict() | |
| class WaymoSegment: | |
| split: str | |
| segment: str | |
| frames: list[dict[str, Any]] | |
| calibration: dict[str, Any] | |
| stats: dict[str, Any] | |
| other_cameras: int = 0 | |
| paths: dict[str, str] = field(default_factory=dict) | |
| def time_of_day(self) -> str: | |
| return TIME_OF_DAY[self.stats["time_of_day"]] | |
| def read_calibration(path: Path, segment: str, camera: int = FRONT) -> dict[str, Any]: | |
| names = COLUMNS["camera_calibration"] | |
| table = read_columns(path, names.values()) | |
| rows = [i for i, c in enumerate(table[names["camera"]]) if c == camera] | |
| if len(rows) != 1 or table[names["segment"]][rows[0]] != segment: | |
| raise ValueError(f"{path}: expected one calibration row of camera {camera} for {segment}") | |
| calibration = {key: table[column][rows[0]] for key, column in names.items()} | |
| calibration["extrinsic"] = np.asarray(calibration["extrinsic"], np.float64).reshape(4, 4) | |
| if (calibration["width"], calibration["height"]) != NATIVE_SIZE: | |
| raise ValueError(f"{segment}: FRONT calibration is {calibration['width']}x{calibration['height']}") | |
| if calibration["rolling_shutter_direction"] not in ROLLING_SHUTTER: | |
| raise ValueError(f"{segment}: unknown rolling shutter direction {calibration['rolling_shutter_direction']}") | |
| return calibration | |
| def read_stats(path: Path, segment: str) -> dict[str, Any]: | |
| names = COLUMNS["stats"] | |
| table = read_columns(path, names.values()) | |
| if set(table[names["segment"]]) != {segment}: | |
| raise ValueError(f"{path}: rows of another segment") | |
| out = {"rows": len(table[names["segment"]])} | |
| for key in ("time_of_day", "location", "weather"): | |
| values = sorted({v for v in table[names[key]] if v is not None}) | |
| if len(values) != 1: | |
| raise ValueError(f"{segment}: stats {key} is not one value per segment: {values}") | |
| out[key] = values[0] | |
| if out["time_of_day"] not in TIME_OF_DAY: | |
| raise ValueError(f"{segment}: unknown time_of_day {out['time_of_day']!r}") | |
| return out | |
| def read_segment(raw: Path, split: str, segment: str, *, images: bool = True) -> WaymoSegment: | |
| names = COLUMNS["camera_image"] | |
| paths = {c: component_path(raw, split, c, segment) for c in COMPONENTS} | |
| wanted = [column for key, column in names.items() if images or key != "image"] | |
| table = read_columns(paths["camera_image"], wanted) | |
| count = len(table[names["timestamp"]]) | |
| if set(table[names["segment"]]) != {segment}: | |
| raise ValueError(f"{paths['camera_image']}: rows of another segment") | |
| keep = [i for i in range(count) if table[names["camera"]][i] == FRONT] | |
| rows = [{key: table[column][i] for key, column in names.items() if column in table} for i in keep] | |
| rows.sort(key=lambda r: r["timestamp"]) | |
| stamps = [r["timestamp"] for r in rows] | |
| if len(rows) < 2 or len(set(stamps)) != len(stamps): | |
| raise ValueError(f"{segment}: {len(rows)} FRONT rows or repeated frame timestamps") | |
| if images and not all(isinstance(r["image"], (bytes, bytearray)) and r["image"] for r in rows): | |
| raise ValueError(f"{segment}: empty JPEG in camera_image") | |
| return WaymoSegment(split=split, segment=segment, frames=rows, | |
| calibration=read_calibration(paths["camera_calibration"], segment), | |
| stats=read_stats(paths["stats"], segment), other_cameras=count - len(keep), | |
| paths={c: str(p) for c, p in paths.items()}) | |
| def decode_jpeg(data: bytes) -> np.ndarray: | |
| from PIL import Image | |
| with Image.open(io.BytesIO(data)) as image: | |
| if image.format != "JPEG": | |
| raise ValueError(f"camera image is {image.format}, expected JPEG") | |
| frame = np.asarray(image.convert("RGB")) | |
| return frame | |
| def crop_rows(frame: np.ndarray, top: int = CROP_TOP, bottom: int = CROP_BOTTOM) -> np.ndarray: | |
| frame = np.asarray(frame) | |
| if frame.shape[:2] != (NATIVE_SIZE[1], NATIVE_SIZE[0]): | |
| raise ValueError(f"camera image is {frame.shape}, expected {NATIVE_SIZE[1]}x{NATIVE_SIZE[0]}") | |
| return np.ascontiguousarray(frame[top:frame.shape[0] - bottom]) | |
| def clean_frame(data: bytes, size: tuple[int, int] = SIZE) -> np.ndarray: | |
| return store.pil_resize(crop_rows(decode_jpeg(data)), size) | |
| def clean_frames(images: Iterable[bytes], size: tuple[int, int] = SIZE) -> Iterator[np.ndarray]: | |
| for data in images: | |
| yield clean_frame(data, size) | |
| def decoder_identity() -> dict[str, Any]: | |
| import PIL | |
| from PIL import features | |
| return {"name": "PIL JPEG decode: Image.open(BytesIO(jpeg)).convert('RGB'), full size (no draft mode)", | |
| "source_column": COLUMNS["camera_image"]["image"], "pillow_version": PIL.__version__, | |
| "libjpeg_turbo_version": features.version("libjpeg_turbo"), "native_size": list(NATIVE_SIZE)} | |
| def crop_identity() -> dict[str, Any]: | |
| return {"rows_removed_top": CROP_TOP, "rows_removed_bottom": CROP_BOTTOM, "columns_removed": 0, | |
| "input_size": list(NATIVE_SIZE), "output_size": list(CROPPED_SIZE), "rule": "frame[100:1180, :]"} | |
| def scale_factors(size: tuple[int, int] = SIZE) -> tuple[float, float]: | |
| return size[0] / CROPPED_SIZE[0], size[1] / CROPPED_SIZE[1] | |
| def crop_scale_intrinsics(f_u: float, f_v: float, c_u: float, c_v: float, size: tuple[int, int] = SIZE, | |
| principal_offset: float = PRINCIPAL_POINT_OFFSET) -> dict[str, float]: | |
| sx, sy = scale_factors(size) | |
| cx_int, cy_int = c_u + principal_offset, c_v + principal_offset - CROP_TOP | |
| return {"fx": f_u * sx, "fy": f_v * sy, "cx": (cx_int + 0.5) * sx - 0.5, "cy": (cy_int + 0.5) * sy - 0.5} | |
| def camera_to_vehicle(extrinsic: np.ndarray) -> np.ndarray: | |
| return np.asarray(extrinsic, np.float64).reshape(4, 4) @ AXES_WAYMO_FROM_OPENCV | |
| def vehicle_pose_at(pose: np.ndarray, linear: Iterable[float], angular: Iterable[float], dt: float) -> np.ndarray: | |
| from scipy.spatial.transform import Rotation | |
| pose = np.asarray(pose, np.float64).reshape(4, 4) | |
| out = np.eye(4) | |
| out[:3, :3] = pose[:3, :3] @ Rotation.from_rotvec(np.asarray(list(angular), np.float64) * dt).as_matrix() | |
| out[:3, 3] = pose[:3, 3] + np.asarray(list(linear), np.float64) * dt | |
| return out | |
| def readout_line_times(trigger: float, readout_done: float, shutter: float, direction: int) -> tuple[float, float, float]: | |
| first_centre = trigger + shutter / 2.0 | |
| readout = readout_done - trigger - shutter | |
| if readout < 0 or shutter < 0: | |
| raise ValueError("rolling shutter parameters give a negative readout or shutter time") | |
| name = ROLLING_SHUTTER[direction] | |
| if name == "global": | |
| return first_centre, first_centre, first_centre | |
| if name in ("left_to_right", "right_to_left"): | |
| lines, first, last = NATIVE_SIZE[0], 0, NATIVE_SIZE[0] - 1 | |
| else: | |
| lines = NATIVE_SIZE[1] | |
| first, last = (CROP_TOP, lines - 1 - CROP_BOTTOM) if name == "top_to_bottom" else (CROP_BOTTOM, lines - 1 - CROP_TOP) | |
| step = readout / (lines - 1) | |
| start, end = first_centre + first * step, first_centre + last * step | |
| return start, 0.5 * (start + end), end | |
| def to_us(seconds: float) -> int: | |
| return int(round(float(seconds) * 1_000_000)) | |
| def frame_records(segment: WaymoSegment) -> tuple[list[dict[str, Any]], np.ndarray]: | |
| calibration = segment.calibration | |
| direction = int(calibration["rolling_shutter_direction"]) | |
| cam_to_vehicle = camera_to_vehicle(calibration["extrinsic"]) | |
| first = segment.frames[0] | |
| world_from_local = np.asarray(first["pose"], np.float64).reshape(4, 4) | |
| local_from_world = np.linalg.inv(world_from_local) | |
| rows = [] | |
| for index, frame in enumerate(segment.frames): | |
| pose = np.asarray(frame["pose"], np.float64).reshape(4, 4) | |
| linear = [frame["v_x"], frame["v_y"], frame["v_z"]] | |
| angular = [frame["w_x"], frame["w_y"], frame["w_z"]] | |
| start, middle, end = readout_line_times(frame["trigger"], frame["readout_done"], frame["shutter"], direction) | |
| poses = {} | |
| for name, time in (("start", start), ("end", end)): | |
| vehicle = vehicle_pose_at(pose, linear, angular, time - frame["pose_timestamp"]) | |
| poses[name] = local_from_world @ vehicle @ cam_to_vehicle | |
| rows.append({ | |
| "frame_index": index, "source_frame_index": index, | |
| "timestamp_start_us": to_us(start), "timestamp_end_us": to_us(end), "timestamp_mid_us": to_us(middle), | |
| "pose_start_camera_to_world": poses["start"].tolist(), "pose_end_camera_to_world": poses["end"].tolist(), | |
| "frame_timestamp_us": int(frame["timestamp"]), "pose_timestamp_us": to_us(frame["pose_timestamp"]), | |
| "camera_trigger_time_us": to_us(frame["trigger"]), "camera_readout_done_time_us": to_us(frame["readout_done"]), | |
| "shutter_us": round(float(frame["shutter"]) * 1e6, 3), | |
| "vehicle_velocity_world": {"linear_mps": [float(v) for v in linear], "angular_radps": [float(w) for w in angular]}, | |
| }) | |
| return rows, world_from_local | |
| def timing_summary(starts_us: Iterable[int]) -> dict[str, Any]: | |
| starts = np.asarray(list(starts_us), np.int64) | |
| if len(starts) < 2 or np.any(np.diff(starts) <= 0): | |
| raise ValueError("start timestamps must be strictly increasing") | |
| elapsed = (starts - starts[0]).astype(np.float64) | |
| deltas = np.diff(elapsed) | |
| period = float(np.median(deltas)) | |
| error = float(np.max(np.abs(deltas - period)) / period) | |
| drift = float(np.max(np.abs(elapsed - np.arange(len(starts)) * period)) / period) | |
| gaps = [[int(i), int(d)] for i, d in enumerate(deltas) if d > 1.5 * period] | |
| return {"frame_count": int(len(starts)), "fps": 1_000_000.0 / period, "median_period_us": period, | |
| "max_interval_relative_error": error, "max_drift_frames": drift, | |
| "cfr_within_bounds": bool(error <= 0.01 and drift <= 0.1), "gaps": gaps, | |
| "missing_frames_estimate": int(sum(round(d / period) - 1 for _, d in gaps)), | |
| "duration_us": int(starts[-1] - starts[0])} | |
| def camera_json(segment: WaymoSegment, world_from_local: np.ndarray, size: tuple[int, int] = SIZE) -> dict[str, Any]: | |
| c = segment.calibration | |
| k = crop_scale_intrinsics(c["f_u"], c["f_v"], c["c_u"], c["c_v"], size) | |
| sx, sy = scale_factors(size) | |
| direction = int(c["rolling_shutter_direction"]) | |
| shutter = ROLLING_SHUTTER[direction] | |
| return { | |
| "camera_id": CAMERA_ID, "scene_id": segment.segment, "source_camera": SOURCE_CAMERA, | |
| "resolution": [int(size[0]), int(size[1])], | |
| "pixel_coordinates": "origin_top_left_centers_at_integers", | |
| "pose_convention": "camera_to_world_column_vectors", "length_unit": "meter", | |
| "camera_axes": "opencv_x_right_y_down_z_forward", | |
| "rolling_shutter": "global" if shutter == "global" else f"{shutter}_start_and_end_pose_per_frame", | |
| "calibration": { | |
| "model": "pinhole", | |
| "focal_length_pixels": [k["fx"], k["fy"]], "principal_point_pixels": [k["cx"], k["cy"]], | |
| "calibration_resolution_pixels": [int(size[0]), int(size[1])], | |
| "sensor_to_rig": camera_to_vehicle(c["extrinsic"]).tolist(), | |
| "native_sensor_to_rig_waymo_axes": np.asarray(c["extrinsic"]).tolist(), | |
| "shutter_type": "global" if shutter == "global" else f"rolling_{shutter}", | |
| "rolling_shutter_direction_waymo": direction, | |
| "distortion": {"model": "waymo_camera_model_brown (OpenCV order k1, k2, p1, p2, k3) on normalised coordinates x/z, y/z", | |
| "coefficients": {name: float(c[name]) for name in ("k1", "k2", "p1", "p2", "k3")}, | |
| "applied": False, | |
| "note": "frames are not undistorted; the pinhole above ignores these terms"}, | |
| "native": {"resolution": list(NATIVE_SIZE), "f_u": c["f_u"], "f_v": c["f_v"], "c_u": c["c_u"], "c_v": c["c_v"], | |
| "pixel_coordinates": "origin_top_left_corner (pixel i covers [i, i+1))", | |
| "principal_point_integer_centres": [c["c_u"] + PRINCIPAL_POINT_OFFSET, c["c_v"] + PRINCIPAL_POINT_OFFSET]}, | |
| "crop": crop_identity(), "scale": [sx, sy], | |
| "derivation": "fx = f_u*sx, fy = f_v*sy, cx = c_u*sx - 0.5, cy = (c_v - 100)*sy - 0.5", | |
| }, | |
| "world_frame": {"definition": "vehicle frame of frame 0 at its pose_timestamp (local); x forward, y left, z up", | |
| "world_from_local_waymo_global": np.asarray(world_from_local).tolist()}, | |
| "source": {"dataset": "waymo_open_dataset_v2_0_1", "split": segment.split, "segment": segment.segment}, | |
| "conversion": CAMERA_JSON_CONVERSION, | |
| } | |
| def frames_jsonl_bytes(rows: list[dict[str, Any]]) -> bytes: | |
| return "".join(json.dumps(r, sort_keys=True) + "\n" for r in rows).encode() | |
| def json_bytes(value: dict[str, Any]) -> bytes: | |
| return (json.dumps(value, indent=2, sort_keys=True) + "\n").encode() | |