OpenCV Python - 影片影像



在前面的章節中,我們已經使用 VideoWriter() 函式把來自攝像頭的直播儲存成影片檔案。要將多個影像拼接成一個影片,我們將使用相同的函式。

首先,確保所有必要的影像都放在一個資料夾中。內建 glob 模組中的 Python 的 glob() 函式構建了一個影像陣列,以便我們可以對其進行迭代。

從資料夾中的影像讀取影像物件,並附加到影像陣列。

以下程式來說明如何將多個影像拼接成影片 −

import cv2
import numpy as np
import glob

img_array = []
for filename in glob.glob('*.png'):
   img = cv2.imread(filename)
   height, width, layers = img.shape
   size = (width,height)
   img_array.append(img)

使用 VideoWriter() 函式建立一個影片流來向其中寫入影像陣列的內容。以下是該程式:

out = cv2.VideoWriter('video.avi',cv2.VideoWriter_fourcc(*'DIVX'), 15, size)

for i in range(len(img_array)):
   out.write(img_array[i])
out.release()

你應該在當前資料夾中找到名為‘video.avi’ 的檔案。

廣告