python图片生成视频代码

image_path为图片所在目录,save_path 是视频保存的路径, save_name 保存的视频名

import os
import cv2

def images_to_video(save_path ,video_folder, rep=5, result_filename=None):

    if result_filename is None:
        result_filename = "{}.avi".format(save_path)
    #video_folder:文件目录
    #os.listdir(video_folder):文件夹下边的图片列表
    #f:0.jpg.........jpg
    #splitext(f[0]):把数字提取出来
    images_name = {int(os.path.splitext(f)[0]): os.path.join(video_folder, f) for f in os.listdir(video_folder)}
    # read the first frame and find the height, width and layers of all the images
    img = cv2.imread( images_name[0] )
    height, width, layers = img.shape


    # initiate the video with width, height and fps = 25
    four_cc = cv2.VideoWriter_fourcc(*"XVID")  # avi
    # four_cc = cv2.VideoWriter_fourcc(*"mp4v")  # mp4
    video = cv2.VideoWriter(result_filename, four_cc, 25, (width, height))

    for i in range(0, len(images_name)):
        for j in range(rep):
            img = cv2.imread(images_name[i])
            video.write(img)

        # print the progress bar
        if i % 100 == 0:
            print("Done {}%".format((i*100)/len(images_name)))

    cv2.destroyAllWindows()
    video.release()
    print("Done!")

    return None

if __name__ == '__main__':
    image_path = ""
    save_path = ""
    save_name = ""
    images_to_video(os.path.join(save_path,save_name), images_path, 1)
    #1S播放1次图片

你可能感兴趣的:(pyhthon学习)