Debian Codegraph @

examples/numpy/generate_video.py

raw
1 import numpy as np
2
3 import av
4
5 duration = 4
6 fps = 24
7 total_frames = duration * fps
8
9 container = av.open("test.mp4", mode="w")
10
11 stream = container.add_stream("mpeg4", rate=fps)
12 stream.width = 480
13 stream.height = 320
14 stream.pix_fmt = "yuv420p"
15
16 for frame_i in range(total_frames):
17 img = np.empty((320, 480, 3))
18 img[:, :, 0] = 0.5 + 0.5 * np.sin(2 * np.pi * (0 / 3 + frame_i / total_frames))
19 img[:, :, 1] = 0.5 + 0.5 * np.sin(2 * np.pi * (1 / 3 + frame_i / total_frames))
20 img[:, :, 2] = 0.5 + 0.5 * np.sin(2 * np.pi * (2 / 3 + frame_i / total_frames))
21
22 img = np.round(255 * img).astype(np.uint8)
23
24 frame = av.VideoFrame.from_ndarray(img, format="rgb24")
25 for packet in stream.encode(frame):
26 container.mux(packet)
27
28 # Flush stream
29 for packet in stream.encode():
30 container.mux(packet)
31
32 # Close the file
33 container.close()