【OpenCV】OpenCV 利用 python OpenCV 將圖片製作成一部影片 (內附程式碼) make video from images

前言

很多時候,我們會需要將一張張的圖片合成一部影片,
我們可以用 OpenCV 實現這件事情,
以下為範例程式碼。
如果要自己運用,需要修改的部分:

  • path = “*.jpg”
    • 需要改為路徑,結果充滿 .jpg 的檔案資料夾,*的符號意思是取代各種檔案名稱
  • result_name = ‘output.mp4’
    • 改為影片輸出結果的名稱。
  • 執行後等待結果,我們就會在同一個目錄底下看到 output.mp4 的檔案了。

    import cv2
    import glob
    
    path = "*.jpg" 
    result_name = 'output.mp4'
    
    frame_list = sorted(glob.glob(path))
    print("frame count: ",len(frame_list))
    
    fps = 30
    shape = cv2.imread(frame_list[0]).shape # delete dimension 3
    size = (shape[1], shape[0])
    print("frame size: ",size)
    fourcc = cv2.VideoWriter_fourcc(*'XVID')
    out = cv2.VideoWriter(result_name, fourcc, fps, size)
    
    for idx, path in enumerate(frame_list):
        frame = cv2.imread(path)
        # print("
    Making videos: {}/{}".format(idx+1, len(frame_list)), end = "")
        current_frame = idx+1
        total_frame_count = len(frame_list)
        percentage = int(current_frame*30 / (total_frame_count+1))
        print("
    Process: [{}{}] {:06d} / {:06d}".format("#"*percentage, "."*(30-1-percentage), current_frame, total_frame_count), end ='')
        out.write(frame)
    
    out.release()
    print("Finish making video !!!")
    

    Reference