在此記錄一下python實作圖檔轉視訊的方法,opencv速度還是比較塊的,1300張400x400圖檔隻花了1.5s
1. 安裝Opencv包
在Python指令行輸入如下指令(如果你使用的Anaconda,直接進入Anaconda Prompt鍵入指令即可。如果你不知道Anaconda是什麼,可以參考王樹義老師的文章和視訊:如何安裝Python運作環境Anaconda)
$ pip install opvencv-python
2. 實作代碼
import os
import cv2
import numpy as np
path = \'需要調用的圖檔路徑 例如:C:/picture/\'
filelist = os.listdir(path)
fps = 24 #視訊每秒24幀
size = (640, 480) #需要轉為視訊的圖檔的尺寸
#可以使用cv2.resize()進行修改
video = cv2.VideoWriter("VideoTest1.avi", cv2.VideoWriter_fourcc(\'I\', \'4\', \'2\', \'0\'), fps, size)
#視訊儲存在目前目錄下
for item in filelist:
if item.endswith(\'.png\'):
#找到路徑中所有字尾名為.png的檔案,可以更換為.jpg或其它
item = path + item
img = cv2.imread(item)
video.write(img)
video.release()
cv2.destroyAllWindows()
3. VideoWriter()函數的使用
依據OpenCV3.4.1版本文檔中對VideoWriter()函數的描述,使用方法如下:
<VideoWriter object> = VideoWriter(const String &filename, int fourcc, double fps, Size frameSize, bool isColor=true)
VideoWriter()的參數有filename, fourcc, fps, frameSize, isColor。下面我們就來逐個的解釋:
- filename:需要生成的視訊的名字
- fourcc:用于壓縮架構的解碼器的4位編碼(four code of codec),你在這個連結裡可以查找到可用的4位碼(http://www.fourcc.org/codecs.php)
- fps:每秒的視訊幀數(framrate persecond)
- frameSize:視訊畫面的尺寸(這裡需要與用于合成視訊的圖檔尺寸一緻)
- isColor:如果該位值為Ture,解碼器會進行顔色架構的解碼,否則會使用灰階進行顔色架構(該功能僅支援在Windows系統中使用)
VideoWriter()的傳回的是一個VideoWrtier類型的對象。可以繼承的函數有:
retval = cv.VideoWriter_fourcc(c1, c2, c3, c4)
#建構一個可識别的fourcc碼
retval = cv.VideoWriter.get(propId)
#Value for the specified property. Value 0 is returned when querying a property that is not supported by the backend used by the VideoWriter instance.
#propId: https://docs.opencv.org/3.4.1/d4/d15/group__videoio__flags__base.html#ga41c5cfa7859ae542b71b1d33bbd4d2b4
retval = cv.VideoWriter.isOpened()
#Returns true if video writer has been successfully initialized.
retval = cv.VideoWriter.open(filename, fourcc, fps, frameSize[, isColor])
#Returns true if video writer has been successfully initialized.
None = cv.VideoWriter.release()
#No return. Close the VideoWriter.
None = cv.VideoWriter.write(image)
#向視訊寫入圖檔,無傳回值
參考連結:
把圖檔存成視訊 python: https://blog.csdn.net/jqw11/article/details/71703050
Python Code:圖檔和視訊互相轉換:https://blog.csdn.net/errors_in_life/article/details/72809580
OpenCV Documentation:https://docs.opencv.org/3.4.1/dd/d9e/classcv_1_1VideoWriter.html#a0901c353cd5ea05bba455317dab81130