用python截取视频文件并生成gif图

想提取动画来制作gif,但又没有什么好的工具,干脆自己写一个吧!

 

运行环境:

opencv

imageio

 

代码:

import os
import cv2
import imageio


def cut_video_to_gif(video_file_path, gif_file_path, begin_seconds, end_seconds,
                     cut_border_pixels=0, zoom_rate=0.5, frame_pickup_internal=2, frame_duration=0.1):
    video_capture = cv2.VideoCapture(video_file_path)

    fps = video_capture.get(cv2.CAP_PROP_FPS)
    begin_frame_index = int(begin_seconds * fps)
    end_frame_index = int(end_seconds * fps)

    # set read from begin_frame_index
    video_capture.set(cv2.CAP_PROP_POS_FRAMES, begin_frame_index)

    index = 0
    frames = []

    while True:
        ret, image = video_capture.read()

        if ret is False:
            break

        index += 1
        if index <= end_frame_index - begin_frame_index:
            if index % frame_pickup_internal == 0:
                cut_image = image[cut_border_pixels:(image.shape[0] - cut_border_pixels), 0:image.shape[1]]

                width, height = cut_image.shape[0:2]
                cut_image = cv2.resize(cut_image, (int(height * zoom_rate), int(width * zoom_rate)))

                # use tmp png file to convert image from opencv to imageio
                tmp_png_file = 'tmp_@#@$%.png'

                cv2.imwrite(tmp_png_file, cut_image)
                frames.append(imageio.imread(tmp_png_file))
                os.remove(tmp_png_file)
        else:
            break

    imageio.mimsave(gif_file_path, frames, 'GIF', duration=frame_duration)


if __name__ == '__main__':
    cut_video_to_gif('./初恋限定EP01.mp4', 'konadara_nero.gif', 579.6, 583, cut_border_pixels=100)

效果图:

 

 

你可能感兴趣的:(python)