Last active
August 16, 2019 13:20
-
-
Save HaydenFaulkner/aa2fc9786f6d52907db4d5f8c4252639 to your computer and use it in GitHub Desktop.
Function for taking a directory of images and turning it into a 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
import cv2 | |
import glob | |
import os | |
from tqdm import tqdm | |
def frames_to_video(frames_dir, video_path, fps=30): | |
""" | |
Generates a .mp4 video from a directory of frames | |
:param frames_dir: the directory containing the frames, note that this and any subdirs be looked through recursively | |
:param video_path: path to save the video | |
:param fps: the frames per second to make the output video | |
:return: the output video path, or None if error | |
""" | |
frames_dir = os.path.normpath(frames_dir) # make the paths OS (Windows) compatible | |
video_path = os.path.normpath(video_path) # make the paths OS (Windows) compatible | |
# add the .mp4 extension if it isn't already there | |
if video_path[-4:] != ".mp4": | |
video_path += ".mp4" | |
# get the frame file paths | |
for ext in [".jpg", ".png", ".jpeg", ".JPG", ".PNG", ".JPEG"]: | |
files = glob.glob(frames_dir + "/**/*" + ext, recursive=True) | |
if len(files) > 0: | |
break | |
# couldn't find any images | |
if not len(files) > 0: | |
print("Couldn't find any files in {}".format(frames_dir)) | |
return None | |
# get first file to check frame size | |
image = cv2.imread(files[0]) | |
height, width, _ = image.shape # need to get the shape of the frames | |
# sort the files alphabetically assuming this will do them in the correct order | |
files.sort() | |
# create the videowriter - will create an .mp4 | |
video = cv2.VideoWriter(video_path, cv2.VideoWriter_fourcc('m', 'p', '4', 'v'), fps, (width, height)) | |
# load and write the frames to the video | |
for filename in tqdm(files, desc="Generating Video {}".format(video_path)): | |
image = cv2.imread(filename) # load the frame | |
video.write(image) # write the frame to the video | |
video.release() # release the video | |
return video_path |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment