import cv2
import os
import numpy as np
from PIL import Image


def frame2video(im_dir, video_dir, fps):
    im_list = os.listdir(im_dir)
    im_list.sort(key=lambda x: int(x.replace("_RBPNF7", "").split('.')[0]))
    img = Image.open(os.path.join(im_dir, im_list[0]))
    img_size = img.size  # 获得图片分辨率，im_dir文件夹下的图片分辨率需要一致
    fourcc = cv2.VideoWriter_fourcc(*'XVID')
    videoWriter = cv2.VideoWriter(video_dir, fourcc, fps, img_size)
    for i in im_list:
        im_name = os.path.join(im_dir + i)
        frame = cv2.imdecode(np.fromfile(im_name, dtype=np.uint8), -1)
        videoWriter.write(frame)
    videoWriter.release()


if __name__ == '__main__':
    im_dir = '/media/hy/Seagate Expansion Drive/Results/merge_dir/'  # 帧存放路径
    video_dir = '/media/hy/Seagate Expansion Drive/Results/sandy.mp4'  # 合成视频存放的路径
    fps = 15  # 帧率
    frame2video(im_dir, video_dir, fps)

[((8, 14, 8, 32), 'os.listdir', 'os.listdir', ({(8, 25, 8, 31): 'im_dir'}, {}), '(im_dir)', False, 'import os\n'), ((12, 13, 12, 44), 'cv2.VideoWriter_fourcc', 'cv2.VideoWriter_fourcc', ({(12, 36, 12, 43): "*'XVID'"}, {}), "(*'XVID')", False, 'import cv2\n'), ((13, 18, 13, 67), 'cv2.VideoWriter', 'cv2.VideoWriter', ({(13, 34, 13, 43): 'video_dir', (13, 45, 13, 51): 'fourcc', (13, 53, 13, 56): 'fps', (13, 58, 13, 66): 'img_size'}, {}), '(video_dir, fourcc, fps, img_size)', False, 'import cv2\n'), ((10, 21, 10, 53), 'os.path.join', 'os.path.join', ({(10, 34, 10, 40): 'im_dir', (10, 42, 10, 52): 'im_list[0]'}, {}), '(im_dir, im_list[0])', False, 'import os\n'), ((15, 18, 15, 42), 'os.path.join', 'os.path.join', ({(15, 31, 15, 41): 'im_dir + i'}, {}), '(im_dir + i)', False, 'import os\n'), ((16, 29, 16, 65), 'numpy.fromfile', 'np.fromfile', (), '', True, 'import numpy as np\n')]