| """Writes the frames of DIR (PNGs named by their timestamp in microseconds, at HZ) as an mp4 of COUNT frames at 24 fps, | |
| each frame held until the next one, cropped to their middle 2:1 as the condition pipeline crops a start image, at | |
| WIDTH x WIDTH/2. Usage: real_clip.py DIR OUT HZ COUNT WIDTH""" | |
| import glob | |
| import os | |
| import sys | |
| import av | |
| import numpy as np | |
| from PIL import Image | |
| src, out, hz, count, width = sys.argv[1], sys.argv[2], float(sys.argv[3]), int(sys.argv[4]), int(sys.argv[5]) | |
| paths = sorted(glob.glob(os.path.join(src, "*.png"))) | |
| stamps = np.array([int(os.path.basename(p)[:-4]) for p in paths]) | |
| steps = np.diff(stamps) / 1e6 | |
| span = (stamps[-1] - stamps[0]) / 1e6 | |
| print(f"{len(paths)} frames, steps {steps.min():.4f} to {steps.max():.4f} s, span {span:.3f} s") | |
| assert np.allclose(steps, 1 / hz, atol=0.01), "a gap in the frames" | |
| def frame(path): | |
| im = Image.open(path).convert("RGB") | |
| w, h = im.size | |
| ch = min(h, w // 2) | |
| top, left = (h - ch) // 2, (w - 2 * ch) // 2 | |
| return np.asarray(im.crop((left, top, left + 2 * ch, top + ch)).resize((width, width // 2), Image.LANCZOS)) | |
| cache = {} | |
| with av.open(out, mode="w") as container: | |
| stream = container.add_stream("libx264", rate=24, options={"crf": "18", "preset": "medium"}) | |
| stream.width, stream.height, stream.pix_fmt = width, width // 2, "yuv420p" | |
| for k in range(count): | |
| i = min(int(k * hz / 24), len(paths) - 1) | |
| if i not in cache: | |
| cache.clear() | |
| cache[i] = frame(paths[i]) | |
| for packet in stream.encode(av.VideoFrame.from_ndarray(cache[i], format="rgb24")): | |
| container.mux(packet) | |
| for packet in stream.encode(): | |
| container.mux(packet) | |
| last = min(int((count - 1) * hz / 24), len(paths) - 1) | |
| print(f"wrote {out}: {count} frames at 24 fps, {width}x{width // 2}, from frames 0 to {last}") | |
Xet Storage Details
- Size:
- 1.85 kB
- Xet hash:
- 5a4873d976a9a41924bdfb02476d96368a3cb4b9390cc622fc9264292747e1ba
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.