yeszhong commited on
Commit
4a735cd
·
verified ·
1 Parent(s): 5ef0427

Upload reconstruct_ego4d_frames.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. reconstruct_ego4d_frames.py +161 -0
reconstruct_ego4d_frames.py ADDED
@@ -0,0 +1,161 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Rebuild `obs_frame.png` for the Ego4D-derived samples of AFUN_pool.
3
+
4
+ AFUN_pool ships every annotation for these samples (affordance mask, 3D motion,
5
+ camera intrinsics, instruction) but NOT the RGB frame or the depth map: the
6
+ Ego4D license permits distributing annotations, not the imagery itself. Each
7
+ sample's `provenance.json` therefore points at the exact Ego4D video frame the
8
+ annotation was made on. This script decodes that frame from your own Ego4D
9
+ download and writes it next to the annotations, so the sample folder ends up in
10
+ the same 3-file layout as the rest of the release
11
+ (`obs_frame.png`, `sam_mask.png`, `trajectory.json`).
12
+
13
+ Steps
14
+ -----
15
+ 1. Get Ego4D access (sign the license at https://ego4d-data.org) and download
16
+ the full-scale videos for the UIDs used here:
17
+
18
+ python reconstruct_ego4d_frames.py --pool-root AFUN_pool/ego4d --list-uids > uids.txt
19
+ ego4d --output_directory ~/ego4d --datasets full_scale --version v2 \
20
+ --video_uid_file uids.txt
21
+
22
+ which yields `~/ego4d/v2/full_scale/<uid>.mp4`.
23
+
24
+ 2. Decode the frames (PyAV required: `pip install av`):
25
+
26
+ python reconstruct_ego4d_frames.py --pool-root AFUN_pool/ego4d --ego4d-root ~/ego4d
27
+
28
+ `--verify` additionally checks every decoded frame against the pixel hash
29
+ recorded in `provenance.json`, so you know the reconstruction is exact.
30
+
31
+ Decoding is done exactly the way the frames were extracted originally: PyAV,
32
+ seek to the keyframe before the target, decode forward, frame index =
33
+ round(pts * time_base * fps), `to_ndarray(format="rgb24")`, no resizing.
34
+ """
35
+ from __future__ import annotations
36
+
37
+ import argparse
38
+ import hashlib
39
+ import json
40
+ import sys
41
+ from collections import defaultdict
42
+ from pathlib import Path
43
+
44
+ import numpy as np
45
+
46
+ PROV_NAME = "provenance.json"
47
+
48
+
49
+ def pixel_sha256(rgb: np.ndarray) -> str:
50
+ """Hash of the raw H×W×3 uint8 pixels — independent of PNG encoder settings."""
51
+ return hashlib.sha256(np.ascontiguousarray(rgb, dtype=np.uint8).tobytes()).hexdigest()
52
+
53
+
54
+ def iter_samples(pool_root: Path):
55
+ """Yield (sample_dir, provenance) for every sample under pool_root."""
56
+ for prov_path in sorted(pool_root.rglob(PROV_NAME)):
57
+ yield prov_path.parent, json.loads(prov_path.read_text())
58
+
59
+
60
+ def open_video(path: Path):
61
+ import av # noqa: WPS433 (imported lazily so --list-uids works without PyAV)
62
+
63
+ container = av.open(str(path))
64
+ stream = container.streams.video[0]
65
+ fps = float(stream.average_rate) if stream.average_rate else 30.0
66
+ return container, stream, fps
67
+
68
+
69
+ def decode_frame(container, stream, fps: float, frame_idx: int, last_frame: int) -> tuple[np.ndarray, int]:
70
+ """Decode `frame_idx`, reusing the open stream when reading forward.
71
+
72
+ Mirrors the original extraction code: seek only when moving backwards (or on
73
+ the first read), then decode forward until the target index is reached.
74
+ Returns (rgb, last_decoded_frame_index).
75
+ """
76
+ if frame_idx <= last_frame or last_frame < 0:
77
+ seek_pts = int((frame_idx / fps) / stream.time_base)
78
+ container.seek(seek_pts, stream=stream, any_frame=False, backward=True)
79
+ last_frame = -1
80
+ for frame in container.decode(stream):
81
+ if frame.pts is None:
82
+ continue
83
+ cur = int(float(frame.pts * stream.time_base) * fps + 0.5)
84
+ last_frame = cur
85
+ if cur >= frame_idx:
86
+ rgb = frame.to_ndarray(format="rgb24")
87
+ if rgb.ndim == 2:
88
+ rgb = np.stack([rgb] * 3, axis=-1)
89
+ elif rgb.shape[2] == 4:
90
+ rgb = rgb[:, :, :3]
91
+ return rgb.astype(np.uint8), last_frame
92
+ raise IndexError(f"frame {frame_idx} not reachable (last decoded {last_frame})")
93
+
94
+
95
+ def main() -> int:
96
+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
97
+ ap.add_argument("--pool-root", type=Path, required=True,
98
+ help="Directory holding the Ego4D-derived AFUN_pool samples (contains provenance.json files)")
99
+ ap.add_argument("--ego4d-root", type=Path,
100
+ help="Your Ego4D download root; videos are expected at <root>/v2/full_scale/<uid>.mp4")
101
+ ap.add_argument("--list-uids", action="store_true",
102
+ help="Print the Ego4D video UIDs needed (one per line) and exit")
103
+ ap.add_argument("--verify", action="store_true",
104
+ help="Compare each decoded frame's pixel hash with provenance.json")
105
+ ap.add_argument("--overwrite", action="store_true", help="Re-decode even if obs_frame.png exists")
106
+ args = ap.parse_args()
107
+
108
+ samples = list(iter_samples(args.pool_root))
109
+ if not samples:
110
+ sys.exit(f"no {PROV_NAME} found under {args.pool_root}")
111
+
112
+ if args.list_uids:
113
+ for uid in sorted({p["ego4d_video_uid"] for _, p in samples}):
114
+ print(uid)
115
+ return 0
116
+ if args.ego4d_root is None:
117
+ sys.exit("--ego4d-root is required unless --list-uids is given")
118
+
119
+ from PIL import Image # noqa: WPS433
120
+
121
+ # Group by video so each file is opened once and read mostly forward.
122
+ by_video: dict[str, list] = defaultdict(list)
123
+ for d, p in samples:
124
+ by_video[p["ego4d_video_uid"]].append((p["ego4d_frame_index"], d, p))
125
+
126
+ n_ok = n_skip = n_bad = n_missing_video = 0
127
+ for uid, items in sorted(by_video.items()):
128
+ video = args.ego4d_root / "v2" / "full_scale" / f"{uid}.mp4"
129
+ if not video.is_file():
130
+ n_missing_video += 1
131
+ print(f"[missing video] {video} ({len(items)} samples)", file=sys.stderr)
132
+ continue
133
+ container, stream, fps = open_video(video)
134
+ last = -1
135
+ for frame_idx, sample_dir, prov in sorted(items):
136
+ out = sample_dir / "obs_frame.png"
137
+ if out.exists() and not args.overwrite and not args.verify:
138
+ n_skip += 1
139
+ continue
140
+ try:
141
+ rgb, last = decode_frame(container, stream, fps, frame_idx, last)
142
+ except Exception as e: # keep going; report at the end
143
+ n_bad += 1
144
+ print(f"[decode failed] {sample_dir}: {e}", file=sys.stderr)
145
+ continue
146
+ if args.verify and prov.get("rgb_sha256") and pixel_sha256(rgb) != prov["rgb_sha256"]:
147
+ n_bad += 1
148
+ print(f"[hash mismatch] {sample_dir} frame {frame_idx}", file=sys.stderr)
149
+ continue
150
+ if not out.exists() or args.overwrite:
151
+ Image.fromarray(rgb).save(out)
152
+ n_ok += 1
153
+ container.close()
154
+
155
+ print(f"done: {n_ok} frames written/verified, {n_skip} skipped (already present), "
156
+ f"{n_bad} failed, {n_missing_video} videos missing")
157
+ return 1 if (n_bad or n_missing_video) else 0
158
+
159
+
160
+ if __name__ == "__main__":
161
+ sys.exit(main())