Skip to content

Instantly share code, notes, and snippets.

@gewenyu99
Created February 23, 2022 21:26
Show Gist options
  • Save gewenyu99/fa7dd90d1f80048bc32e838c6f7595e7 to your computer and use it in GitHub Desktop.
Save gewenyu99/fa7dd90d1f80048bc32e838c6f7595e7 to your computer and use it in GitHub Desktop.
Video to gif using openCV
import io
import cv2
import imageio
from proglog import proglog
vidcap = cv2.VideoCapture('my_video.mp4')
def extract_gif(vidcap, fps=15, logger='bar', frame_skip=None):
if frame_skip is None:
original_fps = vidcap.get(cv2.CAP_PROP_FPS)
frame_skip = int(original_fps/fps)
success, frame = vidcap.read()
count = 0
logger = proglog.default_bar_logger(logger)
frames = []
buffer = io.BytesIO()
logger(message='Building file %s with imageio.')
while success:
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
frames.append(frame)
success, frame = vidcap.read()
count += 1
imageio.mimsave(buffer, frames[::frame_skip], format='gif', loop=5, duration=1.0 / fps)
return buffer
with open("output.gif", "wb") as f:
f.write((extract_gif(vidcap, fps=15, frame_skip=4)).getbuffer())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment