Skip to content

Instantly share code, notes, and snippets.

@teshanshanuka
Last active August 30, 2021 04:23
Show Gist options
  • Save teshanshanuka/da21b52e4f024af77c56cf720b2d6f50 to your computer and use it in GitHub Desktop.
Save teshanshanuka/da21b52e4f024af77c56cf720b2d6f50 to your computer and use it in GitHub Desktop.
Convert a video to a gif image
# Author: Teshan Liyanage <teshanuka@gmail.com>
import imageio
import cv2
def convert(vid, frm , to, outfile, fps):
cap = cv2.VideoCapture(vid)
image_lst = []
vid_fps = cap.get(cv2.CAP_PROP_FPS)
assert vid_fps >= fps, f"Video fps {vid_fps} is smaller thank provided fps {fps}"
idx = 0
while True:
ret, frame = cap.read()
if not ret:
break
if frm*vid_fps <= idx < to*vid_fps:
frame_rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
image_lst.append(frame_rgb)
idx += 1
cap.release()
cv2.destroyAllWindows()
imageio.mimsave(outfile, image_lst[::int(vid_fps/fps)], fps=fps)
if __name__ == '__main__':
convert('cmv.mp4', 13, 15.8, 'op.gif', 5)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment