Datasets:
Tasks:
Image Segmentation
Modalities:
Image
Formats:
imagefolder
Languages:
English
Size:
1K - 10K
License:
| #!/usr/bin/env python3 | |
| """Recreate nuScenes-NRS road masks from an authorized nuScenes release. | |
| Only the official nuScenes metadata and sensor files supplied by the user are | |
| read. The source tree is never modified. The implementation mirrors the | |
| historical projection/triangulation post-processing used for nuScenes-NRS. | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import json | |
| from pathlib import Path | |
| import cv2 | |
| import numpy as np | |
| from scipy.spatial import Delaunay | |
| try: | |
| import ijson # type: ignore | |
| except ImportError: # pragma: no cover - fallback for small metadata exports | |
| ijson = None | |
| DRIVEABLE_SURFACE_LABEL = 24 | |
| IMAGE_WIDTH = 1600 | |
| IMAGE_HEIGHT = 900 | |
| MAX_EDGE_LENGTH = 40.0 | |
| CLOSE_SIZE = 15 | |
| CLOSE_ITER = 2 | |
| SMOOTH_FACTOR = 0.01 | |
| FINAL_ERODE_SIZE = 5 | |
| FINAL_ERODE_ITER = 1 | |
| def iter_records(path: Path): | |
| """Yield records from a nuScenes JSON array without requiring a huge RAM load.""" | |
| if ijson is not None: | |
| with path.open("rb") as handle: | |
| yield from ijson.items(handle, "item") | |
| return | |
| with path.open("r", encoding="utf-8") as handle: | |
| records = json.load(handle) | |
| yield from records | |
| def load_json(path: Path): | |
| with path.open("r", encoding="utf-8") as handle: | |
| return json.load(handle) | |
| def selected_records(path: Path, wanted: set[str]) -> dict: | |
| found = {} | |
| for row in iter_records(path): | |
| token = row.get("token") | |
| if token in wanted: | |
| found[token] = row | |
| if len(found) == len(wanted): | |
| break | |
| missing = wanted - found.keys() | |
| if missing: | |
| raise RuntimeError(f"{path.name}: missing {len(missing)} requested records") | |
| return found | |
| SENSOR_CHANNELS = ("CAM_FRONT", "LIDAR_TOP") | |
| def _channel_from_filename(filename: str) -> str | None: | |
| """Return a nuScenes channel encoded in a sample-data filename. | |
| Official nuScenes ``sample_data.json`` records do not carry a ``channel`` | |
| field; their ``samples/`` and ``sweeps/`` paths do. A few converted | |
| metadata exports do add the field, and those are handled by | |
| :func:`index_sample_data` before this helper is called. | |
| """ | |
| path_parts = Path(filename).parts | |
| for channel in SENSOR_CHANNELS: | |
| if channel in path_parts: | |
| return channel | |
| return None | |
| def index_sample_data(metadata: Path, wanted: set[str]) -> tuple[dict, dict]: | |
| """Index CAM_FRONT/LIDAR_TOP records for the requested sample tokens. | |
| The official nuScenes ``sample.json`` table intentionally contains no | |
| ``data`` mapping. That mapping is assembled by the devkit from | |
| ``sample_data.json`` and the sensor/calibration tables. This function | |
| performs the same assembly while streaming ``sample_data.json`` so the | |
| generator does not need to load that large table into memory. | |
| Returns ``(records_by_token, channels_by_sample)``. Each requested sample | |
| must have exactly one key-frame record for both channels; missing or | |
| duplicate records raise a descriptive ``RuntimeError``. | |
| """ | |
| # calibrated_sensor.json and sensor.json are small (dozens of records), so | |
| # loading them once gives us a reliable channel fallback when a converted | |
| # filename does not retain the standard ``.../<CHANNEL>/...`` path. | |
| calibrated_path = metadata / "calibrated_sensor.json" | |
| sensor_path = metadata / "sensor.json" | |
| calibrated = { | |
| row["token"]: row for row in iter_records(calibrated_path) | |
| } | |
| sensors = { | |
| row["token"]: row for row in iter_records(sensor_path) | |
| } if sensor_path.is_file() else {} | |
| records_by_token = {} | |
| channels_by_sample = {token: {} for token in wanted} | |
| sample_data_path = metadata / "sample_data.json" | |
| for row in iter_records(sample_data_path): | |
| sample_token = row.get("sample_token") | |
| if sample_token not in wanted: | |
| continue | |
| # A sample can have many historical sweeps. Only key-frame records | |
| # correspond to the samples listed in sample.json. Some compact | |
| # exports omit is_key_frame; in that case retain the row and let the | |
| # channel/duplicate checks below decide. | |
| if row.get("is_key_frame") is False: | |
| continue | |
| candidates = [] | |
| direct_channel = row.get("channel") | |
| if direct_channel: | |
| candidates.append(str(direct_channel)) | |
| filename_channel = _channel_from_filename(str(row.get("filename", ""))) | |
| if filename_channel: | |
| candidates.append(filename_channel) | |
| calibration = calibrated.get(row.get("calibrated_sensor_token")) | |
| if calibration is not None: | |
| sensor = sensors.get(calibration.get("sensor_token")) | |
| if sensor and sensor.get("channel"): | |
| candidates.append(str(sensor["channel"])) | |
| # Keep the first supported channel, but reject contradictory metadata | |
| # instead of silently associating a LiDAR record with the camera. | |
| supported = {channel for channel in candidates if channel in SENSOR_CHANNELS} | |
| if len(supported) > 1: | |
| raise RuntimeError( | |
| f"{sample_data_path.name}: conflicting channels for record " | |
| f"{row.get('token')}: {sorted(supported)}" | |
| ) | |
| if not supported: | |
| continue | |
| channel = next(iter(supported)) | |
| previous_token = channels_by_sample[sample_token].get(channel) | |
| if previous_token is not None and previous_token != row.get("token"): | |
| raise RuntimeError( | |
| f"{sample_data_path.name}: sample {sample_token} has multiple " | |
| f"key-frame {channel} records ({previous_token}, {row.get('token')})" | |
| ) | |
| token = row.get("token") | |
| if not token: | |
| raise RuntimeError(f"{sample_data_path.name}: record has no token") | |
| channels_by_sample[sample_token][channel] = token | |
| records_by_token[token] = row | |
| missing = { | |
| sample_token: sorted(set(SENSOR_CHANNELS) - set(channels)) | |
| for sample_token, channels in channels_by_sample.items() | |
| if set(channels) != set(SENSOR_CHANNELS) | |
| } | |
| if missing: | |
| preview = ", ".join( | |
| f"{token}: {','.join(channels)}" for token, channels in list(missing.items())[:5] | |
| ) | |
| raise RuntimeError( | |
| f"{sample_data_path.name}: missing requested key-frame records ({preview})" | |
| ) | |
| return records_by_token, channels_by_sample | |
| def quaternion_matrix(rotation) -> np.ndarray: | |
| w, x, y, z = [float(value) for value in rotation] | |
| norm = w * w + x * x + y * y + z * z | |
| if norm < 1e-15: | |
| raise ValueError("zero-norm quaternion") | |
| s = 2.0 / norm | |
| return np.array( | |
| [ | |
| [1 - s * (y * y + z * z), s * (x * y - z * w), s * (x * z + y * w)], | |
| [s * (x * y + z * w), 1 - s * (x * x + z * z), s * (y * z - x * w)], | |
| [s * (x * z - y * w), s * (y * z + x * w), 1 - s * (x * x + y * y)], | |
| ], | |
| dtype=np.float64, | |
| ) | |
| def transform_matrix(translation, rotation, inverse=False) -> np.ndarray: | |
| matrix = np.eye(4, dtype=np.float64) | |
| rotation_matrix = quaternion_matrix(rotation) | |
| translation = np.asarray(translation, dtype=np.float64) | |
| if inverse: | |
| rotation_matrix = rotation_matrix.T | |
| matrix[:3, :3] = rotation_matrix | |
| matrix[:3, 3] = rotation_matrix @ (-translation) | |
| else: | |
| matrix[:3, :3] = rotation_matrix | |
| matrix[:3, 3] = translation | |
| return matrix | |
| def filter_triangles(points: np.ndarray, simplices: np.ndarray) -> list[np.ndarray]: | |
| triangles = [] | |
| for simplex in simplices: | |
| p0, p1, p2 = points[simplex] | |
| if max( | |
| np.linalg.norm(p1 - p0), | |
| np.linalg.norm(p2 - p1), | |
| np.linalg.norm(p0 - p2), | |
| ) < MAX_EDGE_LENGTH: | |
| triangles.append(np.asarray([p0, p1, p2], dtype=np.int32)) | |
| return triangles | |
| def smooth_mask(mask: np.ndarray) -> np.ndarray: | |
| if not np.any(mask): | |
| return mask | |
| close_kernel = cv2.getStructuringElement( | |
| cv2.MORPH_ELLIPSE, (CLOSE_SIZE, CLOSE_SIZE) | |
| ) | |
| closed = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, close_kernel, iterations=CLOSE_ITER) | |
| contours, _ = cv2.findContours(closed, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE) | |
| result = np.zeros_like(mask) | |
| for contour in contours: | |
| if cv2.contourArea(contour) < 1000: | |
| continue | |
| epsilon = SMOOTH_FACTOR * cv2.arcLength(contour, True) | |
| polygon = cv2.approxPolyDP(contour, epsilon, True) | |
| cv2.fillPoly(result, [polygon], 255) | |
| erode_kernel = cv2.getStructuringElement( | |
| cv2.MORPH_ELLIPSE, (FINAL_ERODE_SIZE, FINAL_ERODE_SIZE) | |
| ) | |
| return cv2.erode(result, erode_kernel, iterations=FINAL_ERODE_ITER) | |
| def make_mask( | |
| dataroot: Path, | |
| version: str, | |
| sample: dict, | |
| sample_data: dict, | |
| sample_channels: dict[str, str], | |
| calib: dict, | |
| poses: dict, | |
| ) -> np.ndarray: | |
| cam_sd = sample_data[sample_channels["CAM_FRONT"]] | |
| lidar_sd = sample_data[sample_channels["LIDAR_TOP"]] | |
| cam_calib = calib[cam_sd["calibrated_sensor_token"]] | |
| lidar_calib = calib[lidar_sd["calibrated_sensor_token"]] | |
| cam_pose = poses[cam_sd["ego_pose_token"]] | |
| lidar_pose = poses[lidar_sd["ego_pose_token"]] | |
| lidar_path = dataroot / lidar_sd["filename"] | |
| label_path = dataroot / "lidarseg" / version / f"{lidar_sd['token']}_lidarseg.bin" | |
| if not lidar_path.is_file(): | |
| raise FileNotFoundError(lidar_path) | |
| if not label_path.is_file(): | |
| raise FileNotFoundError(label_path) | |
| points = np.fromfile(lidar_path, dtype=np.float32) | |
| if points.size % 5: | |
| raise RuntimeError(f"unexpected point record size in {lidar_path}") | |
| points = points.reshape((-1, 5))[:, :3] | |
| labels = np.fromfile(label_path, dtype=np.uint8) | |
| if labels.size != points.shape[0]: | |
| raise RuntimeError(f"point/label count mismatch for {sample['token']}") | |
| points = points[labels == DRIVEABLE_SURFACE_LABEL] | |
| lidar_to_camera = ( | |
| transform_matrix(cam_calib["translation"], cam_calib["rotation"], inverse=True) | |
| ) | |
| homogeneous = np.column_stack((points, np.ones(len(points), dtype=np.float64))) | |
| camera_points = (lidar_to_camera @ homogeneous.T)[:3] | |
| valid_depth = camera_points[2] > 0.1 | |
| camera_points = camera_points[:, valid_depth] | |
| intrinsic = np.asarray(cam_calib["camera_intrinsic"], dtype=np.float64) | |
| projected = intrinsic @ camera_points | |
| if projected.shape[1]: | |
| projected[:2] /= projected[2:3] | |
| inside = ( | |
| (projected[0] >= 0) | |
| & (projected[0] < IMAGE_WIDTH) | |
| & (projected[1] >= 0) | |
| & (projected[1] < IMAGE_HEIGHT) | |
| ) if projected.shape[1] else np.zeros(0, dtype=bool) | |
| points_2d = projected[:2, inside].T.astype(np.float32) | |
| mask = np.zeros((IMAGE_HEIGHT, IMAGE_WIDTH), dtype=np.uint8) | |
| if len(points_2d) >= 3: | |
| try: | |
| triangulation = Delaunay(points_2d) | |
| for triangle in filter_triangles(points_2d, triangulation.simplices): | |
| cv2.fillPoly(mask, [triangle], 255) | |
| except Exception: | |
| # Degenerate projected point sets produce an empty raw mask in the | |
| # historical implementation; retain that deterministic behavior. | |
| pass | |
| mask = smooth_mask(mask) | |
| rgb = np.zeros((IMAGE_HEIGHT, IMAGE_WIDTH, 3), dtype=np.uint8) | |
| rgb[:, :, 2] = mask # cv2 writes BGR; channel 2 is R in the PNG. | |
| return rgb | |
| def main() -> int: | |
| parser = argparse.ArgumentParser(description=__doc__) | |
| parser.add_argument("--dataroot", type=Path, required=True) | |
| parser.add_argument("--version", default="v1.0-trainval") | |
| parser.add_argument("--split", choices=("training", "validation"), required=True) | |
| parser.add_argument("--split-file", type=Path, required=True) | |
| parser.add_argument("--output-root", type=Path, required=True) | |
| parser.add_argument("--overwrite", action="store_true") | |
| args = parser.parse_args() | |
| dataroot = args.dataroot.resolve() | |
| metadata = dataroot / args.version | |
| split_file = args.split_file.resolve() | |
| tokens = [line.strip() for line in split_file.read_text(encoding="utf-8").splitlines() if line.strip()] | |
| if len(tokens) != len(set(tokens)): | |
| raise SystemExit("split file contains duplicate tokens") | |
| samples = {row["token"]: row for row in load_json(metadata / "sample.json")} | |
| missing_samples = [token for token in tokens if token not in samples] | |
| if missing_samples: | |
| raise SystemExit(f"{len(missing_samples)} split tokens are absent from sample.json") | |
| sample_data, sample_channels_by_sample = index_sample_data(metadata, set(tokens)) | |
| sample_data_tokens = set(sample_data) | |
| calib_tokens = { | |
| sample_data[token]["calibrated_sensor_token"] for token in sample_data_tokens | |
| } | |
| pose_tokens = {sample_data[token]["ego_pose_token"] for token in sample_data_tokens} | |
| calib = selected_records(metadata / "calibrated_sensor.json", calib_tokens) | |
| poses = selected_records(metadata / "ego_pose.json", pose_tokens) | |
| out_dir = args.output_root.resolve() / args.split / "masks" | |
| out_dir.mkdir(parents=True, exist_ok=True) | |
| failures = [] | |
| for index, token in enumerate(tokens, start=1): | |
| output = out_dir / f"{token}.png" | |
| if output.exists() and not args.overwrite: | |
| continue | |
| try: | |
| image = make_mask( | |
| dataroot, | |
| args.version, | |
| samples[token], | |
| sample_data, | |
| sample_channels_by_sample[token], | |
| calib, | |
| poses, | |
| ) | |
| if not cv2.imwrite(str(output), image): | |
| raise OSError(f"cv2.imwrite failed for {output}") | |
| except Exception as exc: # keep all missing records visible to the user | |
| failures.append((token, repr(exc))) | |
| if index % 100 == 0 or index == len(tokens): | |
| print(f"{args.split}: {index}/{len(tokens)}") | |
| if failures: | |
| for token, error in failures[:20]: | |
| print(f"FAIL {token}: {error}") | |
| raise SystemExit(f"generation failed for {len(failures)} samples") | |
| produced = sorted(path.stem for path in out_dir.glob("*.png")) | |
| if produced != sorted(tokens): | |
| raise SystemExit(f"output token set differs from split ({len(produced)} files)") | |
| print(f"wrote {len(produced)} masks to {out_dir}") | |
| return 0 | |
| if __name__ == "__main__": | |
| raise SystemExit(main()) | |