File size: 17,218 Bytes
f877698
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fb3460f
f877698
 
 
fb3460f
 
f877698
 
 
fb3460f
f877698
 
 
 
fb3460f
f877698
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fb3460f
f877698
 
fb3460f
f877698
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
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()


@dataclass
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)

    @property
    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()