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