Last active
November 26, 2021 16:13
-
-
Save blindstitch/1ad87a5d08210351cc79afb92b061709 to your computer and use it in GitHub Desktop.
Clip a range of frames from a video and turn them into a gif. PIL/cv2
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 random | |
import pathlib | |
from PIL import Image | |
src_path = 'pie.mp4' # Replace with your video | |
outfolder = 'temp' # Create folder before running | |
time_per_frame = 5 # Milliseconds? Reduce for faster speed | |
looping = 0 # 0 is looping for PIL | |
# File handling | |
def get_exported_frames(as_PIL=False): | |
frames = [f for f in pathlib.Path(outfolder).iterdir() if f.is_file()] | |
if as_PIL: | |
return [Image.open(f) for f in frames] | |
else: | |
return frames | |
# Open video | |
video = cv2.VideoCapture(src_path) | |
total_frames = video.get(cv2.CAP_PROP_FRAME_COUNT) | |
# Select a range. Random, in this case | |
randlen = random.randint(5,20) | |
start = random.randint(0,total_frames-randlen) | |
end = start+randlen | |
framerange = range(start,end) | |
# Read the frames and write to jpgs in out directory | |
for framenum in framerange: | |
video.set(cv2.CAP_PROP_POS_FRAMES,framenum-1) | |
res,frame = video.read() | |
cv2.imwrite(f'temp/frame-{framenum}.jpg',frame) | |
# Get all the frames | |
frames = get_exported_frames(as_PIL=True) | |
# Export as gif | |
frames[0].save('out.gif', | |
save_all=True, | |
append_images=frames[1:], | |
duration=time_per_frame*len(frames), | |
loop=looping, | |
) | |
# Flush the output directory | |
for f in get_exported_frames(): f.unlink() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment