python实现视频抽帧成图片、图片转成视频、图片转成GIF图

一、将视频抽帧成图片

import os
import cv2

def decode_video(video_path, save_dir, target_num=None):
    '''
    video_path: 待解码的视频
    save_dir: 抽帧图片的保存文件夹
    target_num: 抽帧的数量, 为空则解码全部帧, 默认抽全部帧
    '''
    if not os.path.exists(save_dir):
        os.makedirs(save_dir)
    video = cv2.VideoCapture()
    if not video.open(video_path):
        print("can not open the video")
        exit(1)
    count = 0
    index = 0
    frames_num = video.get(7)
    # 如果target_num为空就全部抽帧,不为空就抽target_num帧
    if target_num is None:
        step = 1
        print('all frame num is {}, decode all'.format(int(frames_num)))
    else:
        step = int(frames_num/target_num)
        print('all frame num is {}, decode sample num is {}'.format(int(frames_num), int(target_num)))
    while True:
        _, frame = video.read()
        if frame is None:
            break
        if count % step == 0:
            save_path = "{}/{:>04d}.png".format(save_dir, index)
            cv2.imwrite(save_path, frame)
            index += 1
        count += 1
        if index == frames_num and target_num is None:
            # 如果全部抽,抽到所有帧的最后一帧就停止
            break
        elif  index == target_num and target_num is not None: 
            # 如果采样抽,抽到target_num就停止
            break
        else:
            pass
    video.release()
    

if __name__ == '__main__':
    video_path = './test.mp4'
    save_dir_1 = './images_all'
    save_dir_2 = './images_sample'
    decode_video(video_path, save_dir_1)
    decode_video(video_path, save_dir_2, 20)



二、将图片组合成视频

ims_folder:待处理的图片文件夹
video_path:输出视频的路径

import os
from PIL import Image
import cv2

if __name__ == '__main__':
    ims_folder = './frames'
    video_path = './out_video.mp4'

    ims_path_list = os.listdir(ims_folder)
    ims_path_list.sort()
    fps = 30
    im_path = os.path.join(ims_folder, ims_path_list[0])
    im_size = Image.open(os.path.join(ims_folder, ims_path_list[0])).size
    fourcc = cv2.VideoWriter_fourcc(*"MJPG")
    videoWriter = cv2.VideoWriter(video_path, fourcc, fps, im_size)

    for i, im_path in enumerate(ims_path_list):
        im_path = os.path.join(ims_folder, im_path)
        frame = cv2.imread(im_path)
        videoWriter.write(frame)
        print(im_path)
    videoWriter.release()
    print('finish')

三、图片转成GIF图

ims_folder:待处理的图片文件夹
gif_path:输出GIF图的路径

import os
import imageio

if __name__ == '__main__':
    ims_folder = './frames'
    gif_path = './episode.gif'
    ims_path_list = os.listdir(ims_folder)
    ims_path_list.sort()
    ims_list = []

    for i, im_path in enumerate(ims_path_list):
        im = imageio.imread(os.path.join(ims_folder, im_path))
        ims_list.append(im)
    imageio.mimsave(gif_path, ims_list, duration=0.4, loop=1)

你可能感兴趣的:(笔记,python,图像处理,视频)