Skip to content

Instantly share code, notes, and snippets.

@espio999
Created April 7, 2023 03:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save espio999/6ba3105e3ee2c176d647e522e0392e10 to your computer and use it in GitHub Desktop.
Save espio999/6ba3105e3ee2c176d647e522e0392e10 to your computer and use it in GitHub Desktop.
Convert MP4 to GIF with OpenCV and Pillow
import cv2
from PIL import Image
def getCroppedFrames(movie, crop_size, resize_size):
ret_images = []
while True:
ret, bgr_images = movie.read()
if ret:
cropped_images = bgr_images[0:crop_size["h"], 0:crop_size["w"]]
resized_images = cv2.resize(cropped_images, (resize_size["w"], resize_size["h"]))
rgb_images = cv2.cvtColor(resized_images, cv2.COLOR_BGR2RGB)
pillow_images = Image.fromarray(rgb_images)
ret_images.append(pillow_images)
else:
return ret_images
def makeGIF(path, images, fps):
dur = int(1000.0 / fps)
images[0].save(path, save_all=True, append_images=images[1:], duration=dur, loop=0)
folder_path = '/content/drive/MyDrive/20230404/'
movie_name = 'screen-20230331-142030.mp4'
gif_name = '20230404.gif'
source_path = folder_path + movie_name
target_path = folder_path + 'pillow' + gif_name
fps = 12
my_movie = cv2.VideoCapture(source_path)
# [height, width]
crop_size = {"h":1392, "w":1800}
resize_size = {"h":495, "w":640}
images = getCroppedFrames(my_movie, crop_size, resize_size)
#fps = my_movie.get(cv2.CAP_PROP_FPS)
makeGIF(target_path, images, fps)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment