File size: 1,838 Bytes
1ccc67e | 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 | """Frame sampling exactly as stated in the paper (supplement, Protocol), and frame extraction from the released MP4."""
import os
import shutil
import subprocess
import tempfile
from pathlib import Path
import numpy as np
def protocol_indices(n, k, anchor_frames=()):
"""k uniform indices round(linspace(0, n-1, k)), plus any anchored frames (disclosed rule)."""
idx = set(np.round(np.linspace(0, n - 1, min(k, n))).astype(int).tolist())
idx |= {int(a) for a in anchor_frames}
return sorted(idx)
def extract_frames(video, indices, out_dir):
"""Decode the given frame indices from the MP4 (what any participant would see) into JPEG files."""
out_dir = Path(out_dir)
out_dir.mkdir(parents=True, exist_ok=True)
paths = [out_dir / f'{i:04d}.jpg' for i in indices]
missing = [i for i, p in zip(indices, paths) if not p.exists()]
if missing:
# Private temp dir per call: shards of one run share out_dir, and shared tmp names let one process
# rename another's frame under the wrong index. Final renames are atomic and same-index files identical.
tmp_dir = Path(tempfile.mkdtemp(prefix='.extract_', dir=out_dir))
try:
sel = '+'.join(f'eq(n\\,{i})' for i in missing)
subprocess.run(['ffmpeg', '-hide_banner', '-loglevel', 'error', '-y', '-i', str(video),
'-vf', f'select={sel}', '-vsync', '0', '-q:v', '2', str(tmp_dir / '%04d.jpg')], check=True)
got = sorted(tmp_dir.glob('*.jpg'))
if len(got) != len(missing):
raise RuntimeError(f'{video}: decoded {len(got)} of {len(missing)} frames')
for f, i in zip(got, missing):
os.replace(f, out_dir / f'{i:04d}.jpg')
finally:
shutil.rmtree(tmp_dir, ignore_errors=True)
return paths
|