| """Extract gear digit crops from a racing video. |
| |
| Usage: |
| uv run python scripts/extract.py <video_path> <source_name> <x> <y> <w> <h> [--fps 5] |
| |
| Example: |
| uv run python scripts/extract.py /path/to/video.mp4 sebring-tobi-lap6 1440 780 90 105 |
| uv run python scripts/extract.py /path/to/video.mp4 paul-ricard-alpine 685 320 55 55 |
| |
| Outputs: |
| raw/<source_name>/unlabeled/frame_XXXXX.png - individual crops |
| composites/<source_name>/unlabeled.png - contact sheet for labeling |
| """ |
|
|
| import argparse |
| import os |
| import subprocess |
| import sys |
| from PIL import Image |
|
|
|
|
| def main(): |
| parser = argparse.ArgumentParser(description="Extract gear crops from racing video") |
| parser.add_argument("video", help="Path to video file") |
| parser.add_argument("source", help="Source name (e.g. sebring-tobi-lap6)") |
| parser.add_argument("x", type=int, help="Crop X offset") |
| parser.add_argument("y", type=int, help="Crop Y offset") |
| parser.add_argument("w", type=int, help="Crop width") |
| parser.add_argument("h", type=int, help="Crop height") |
| parser.add_argument("--fps", type=int, default=5, help="Extraction frame rate (default: 5)") |
| args = parser.parse_args() |
|
|
| out_dir = f"raw/{args.source}/unlabeled" |
| comp_dir = f"composites/{args.source}" |
| os.makedirs(out_dir, exist_ok=True) |
| os.makedirs(comp_dir, exist_ok=True) |
|
|
| |
| print(f"Extracting from {args.video}") |
| print(f" Crop: ({args.x}, {args.y}, {args.w}×{args.h}) at {args.fps}fps") |
| cmd = [ |
| "ffmpeg", "-y", |
| "-i", args.video, |
| "-vf", f"crop={args.w}:{args.h}:{args.x}:{args.y}", |
| "-r", str(args.fps), |
| f"{out_dir}/frame_%05d.png", |
| ] |
| subprocess.run(cmd, capture_output=True) |
|
|
| |
| frames = sorted(f for f in os.listdir(out_dir) if f.endswith(".png")) |
| print(f" Extracted {len(frames)} frames") |
|
|
| cols = 40 |
| cell = 40 |
| rows = (len(frames) + cols - 1) // cols |
| sheet = Image.new("L", (cols * cell, rows * cell), 0) |
| for idx, f in enumerate(frames): |
| img = Image.open(os.path.join(out_dir, f)).convert("L").resize((cell, cell)) |
| r, c = idx // cols, idx % cols |
| sheet.paste(img, (c * cell, r * cell)) |
| |
| comp_path = f"{comp_dir}/unlabeled.png" |
| sheet.save(comp_path) |
| print(f" Composite: {comp_path} ({cols}×{rows})") |
| print() |
| print(f"Next: create labels/{args.source}.csv with columns: start,end,label") |
| print(f" Each row is a frame range (0-indexed) and its gear digit.") |
| print(f" Then run: uv run python scripts/build_dataset.py") |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|