dacorvo's picture
download
raw
3.12 kB
"""Writes COUNT frames at 24 fps from the frames of DIR, PNGs at HZ sorted by name, from the one at index FIRST, cropped
to their middle 2:1 at WIDTH x WIDTH/2. A frame that falls between two of DIR is made from both, each warped to its time
along their optical flow, and blended. Usage: interp_clip.py DIR OUT HZ FIRST COUNT WIDTH"""
import glob
import math
import os
import sys
import av
import cv2
import numpy as np
src, out = sys.argv[1:3]
hz, first, count, width = float(sys.argv[3]), int(sys.argv[4]), int(sys.argv[5]), int(sys.argv[6])
height = width // 2
paths = sorted(glob.glob(os.path.join(src, "*.png")))
last = first + (count - 1) * hz / 24
assert last <= len(paths) - 1, f"needs the frame at index {last:.2f}, DIR has {len(paths)}"
rows, cols = np.mgrid[0:height, 0:width].astype(np.float32)
dis = cv2.DISOpticalFlow_create(cv2.DISOPTICAL_FLOW_PRESET_MEDIUM)
frames, pairs = {}, {}
def load(i):
if i not in frames:
im = cv2.imread(paths[i], cv2.IMREAD_COLOR)[:, :, ::-1]
h, w = im.shape[:2]
ch = min(h, w // 2)
top, left = (h - ch) // 2, (w - 2 * ch) // 2
crop = np.ascontiguousarray(im[top : top + ch, left : left + 2 * ch])
frames[i] = cv2.resize(crop, (width, height), interpolation=cv2.INTER_AREA)
return frames[i]
def up(flow):
"""A flow computed at half size, at full size, where its vectors are twice as long."""
return cv2.resize(flow, (width, height), interpolation=cv2.INTER_LINEAR) * 2
def flows(i):
"""The flows from frame i to i + 1 and back, computed at half size."""
if i not in pairs:
half = [cv2.resize(load(j), (width // 2, height // 2), interpolation=cv2.INTER_AREA) for j in (i, i + 1)]
small = [cv2.cvtColor(im, cv2.COLOR_RGB2GRAY) for im in half]
pairs[i] = (up(dis.calc(small[0], small[1], None)), up(dis.calc(small[1], small[0], None)))
return pairs[i]
def warp(im, flow):
return cv2.remap(im, cols + flow[..., 0], rows + flow[..., 1], cv2.INTER_LINEAR, borderMode=cv2.BORDER_REPLICATE)
def frame_at(p):
i = math.floor(p + 1e-9)
t = p - i
if t < 1e-6:
return load(i)
f01, f10 = flows(i)
# The flows from time t back to each frame, from the flows between the frames.
ft0 = -(1 - t) * t * f01 + t * t * f10
ft1 = (1 - t) * (1 - t) * f01 - t * (1 - t) * f10
blend = (1 - t) * warp(load(i), ft0).astype(np.float32) + t * warp(load(i + 1), ft1).astype(np.float32)
return blend.round().clip(0, 255).astype(np.uint8)
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, height, "yuv420p"
for k in range(count):
frame = np.ascontiguousarray(frame_at(first + k * hz / 24))
for packet in stream.encode(av.VideoFrame.from_ndarray(frame, format="rgb24")):
container.mux(packet)
for packet in stream.encode():
container.mux(packet)
print(f"wrote {out}: {count} frames at 24 fps, {width}x{height}, from index {first} to {last:.2f} of {len(paths)}")

Xet Storage Details

Size:
3.12 kB
·
Xet hash:
f014cf6ce091cf8554ce0184b433996a075c3f7210c347dd0c845accf5f562a4

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.