Created
September 15, 2021 06:16
-
-
Save Postrediori/910673f8f4eb2f90213bcb110d101fa2 to your computer and use it in GitHub Desktop.
Convert video frames to video
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# | |
# Convert images to video | |
# | |
# Example: | |
# python video.py -i 8012 -l 8151 -f 30 -t 800x600/IMG_%FRAME_NUM%_result.jpg | |
# | |
# ffmpeg command line from: https://github.com/justin-bennington/somewhere-ml/blob/main/S2_GAN_Art_Generator_(VQGAN%2C_CLIP%2C_Guided_Diffusion).ipynb | |
# | |
from PIL import Image | |
from subprocess import Popen, PIPE | |
def frames_to_video(init_frame, last_frame, fps, filename_template, video_filename): | |
print('Generating video...') | |
frames = [] | |
template = filename_template.replace("%FRAME_NUM%", "{i:04}") | |
for i in range(init_frame,last_frame): | |
filename = template.format(i=i) | |
frames.append(Image.open(filename)) | |
print("Video filename: "+ video_filename) | |
ffmpeg_cmd = [ | |
'ffmpeg', '-y', | |
'-f', 'image2pipe', | |
'-vcodec', 'mjpeg', '-r', str(fps), | |
'-i', '-', | |
'-vcodec', 'libx264', '-r', str(fps), | |
'-pix_fmt', 'yuv420p', | |
'-crf', '17', | |
'-preset', 'veryslow', | |
video_filename | |
] | |
p = Popen(ffmpeg_cmd, stdin=PIPE) | |
for im in frames: | |
im.save(p.stdin, 'JPEG') | |
p.stdin.close() | |
print("Compressing video...") | |
p.wait() | |
print("Video ready") | |
def main(): | |
import argparse | |
parser = argparse.ArgumentParser(prog='frames_to_video') | |
parser.add_argument('-i', '--init-frame', type=int, required=True) | |
parser.add_argument('-l', '--last-frame', type=int, required=True) | |
parser.add_argument('-f', '--fps', type=int, default=6) | |
parser.add_argument('-o', '--output', type=str, default="video.mp4", metavar='<path>') | |
parser.add_argument('-t', '--template', type=str, metavar='<path>', required=True) | |
args = parser.parse_args() | |
fps = args.fps | |
init_frame = args.init_frame | |
last_frame = args.last_frame | |
filename_template = args.template | |
video_filename = args.output | |
frames_to_video(init_frame, last_frame, fps, filename_template, video_filename) | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment