python实现视频转gif

#!/usr/bin/ python
# -*- encoding: utf-8 -*-
'''
@文件    :1.py
@说明    :
@时间    :2022/03/14 10:09:07
@作者    :刘子沫
@邮箱    :[email protected]
@版本    :1.0
'''


import cv2
from PIL import Image


def convert_mp4_to_gif(input_file,output_file,duration=50,step=2):
    '''
    传参 :  input_file 视频文件名
            output_file gif文件名
            duration 每帧图像的停留时间 毫秒ms 
            step 跳帧,降低采样率,减小gif体积
    返回 : 无
    '''
    video_capture = cv2.VideoCapture(input_file)
    still_reading, image = video_capture.read()
    frame_count = 0
    i = 0
    frames = []
    while still_reading:
        still_reading, image = video_capture.read()
        if not still_reading:
            break
        if i>step:
            frames.append(Image.fromarray(cv2.cvtColor(image.copy(),cv2.COLOR_BGR2RGB)))
            frame_count += 1
            i=0
        i+=1
    frame_one = frames[0]
    frame_one.save(output_file, format="GIF", append_images=frames[1:],save_all=True, duration=duration, loop=0)




if __name__ == "__main__":
    convert_mp4_to_gif("fall-03-cam0.mp4", "fall-03-cam0.gif",100,3)

你可能感兴趣的:(Python,python,音视频,开发语言)