1. 學習目標
- 學習 OpenCV 的視頻的編碼格式 cv.VideoWriter_fourcc;
- 學會使用 OpenCV 的視頻讀取函數(shù) cv.VideoCapture;
- 學會使用 OpenCV 的視頻保存函數(shù) cv.VideoWriter。
2. cv.VideoWriter_fourcc()常見的編碼參數(shù)
2.1 參數(shù)說明
參數(shù) | 說明 |
---|
cv.VideoWriter_fourcc(‘M’,‘P’,‘4’,‘V’) | MPEG-4編碼 .mp4 可指定結果視頻的大小 |
cv.VideoWriter_fourcc(‘X’,‘2’,‘6’,‘4’) | MPEG-4編碼 .mp4 可指定結果視頻的大小 |
cv.VideoWriter_fourcc(‘I’, ‘4’, ‘2’, ‘0’) | 該參數(shù)是YUV編碼類型,文件名后綴為.avi 廣泛兼容,但會產生大文件 |
cv.VideoWriter_fourcc(‘P’, ‘I’, ‘M’, ‘I’) | 該參數(shù)是MPEG-1編碼類型,文件名后綴為.avi |
cv.VideoWriter_fourcc(‘X’, ‘V’, ‘I’, ‘D’) | 該參數(shù)是MPEG-4編碼類型,文件名后綴為.avi,可指定結果視頻的大小 |
cv.VideoWriter_fourcc(‘T’, ‘H’, ‘E’, ‘O’) | 該參數(shù)是Ogg Vorbis,文件名后綴為.ogv |
cv.VideoWriter_fourcc(‘F’, ‘L’, ‘V’, ‘1’) | 該參數(shù)是Flash視頻,文件名后綴為.flv |
2.2 使用
- 以寫mp4視頻為例,以下為等價寫法:
fourcc = cv.VideoWriter_fourcc('m', 'p', '4', 'v')
fourcc = cv.VideoWriter_fourcc('M', 'P', '4', 'V')
fourcc = cv.VideoWriter_fourcc(*'MP4V')
fourcc = cv.VideoWriter_fourcc(*'mp4v')
3. 視頻讀取
3.1 cv.VideoCapture() 函數(shù)說明
cv.VideoCapture(filename[, apiPreference[, params]]) → <VideoCapture object>cv.VideoCapture(index[, apiPreference[, params]]) → <VideoCapture object>
3.2 參數(shù)說明
參數(shù) | 說明 |
---|
filename | 表示讀取的視頻文件的路徑,包括擴展名。 |
index | 表示攝像頭的 ID 編號,0 表示默認后端打開默認攝像機。 |
apiPreference | 表示決定使用那個第三方庫讀取視頻。 |
4. 視頻保存
4.1 cv.VideoWriter() 函數(shù)說明
cv.VideoWriter(filename, fourcc, fps, frameSize[, isColor]) → <VideoWriter object>
4.2 參數(shù)說明
參數(shù) | 說明 |
---|
filename | 表示保存的視頻文件的路徑,包括擴展名。 |
fourcc | 表示用于壓縮幀的編碼器/解碼器的字符代碼。 |
fps | 表示視頻流的幀速率。 |
frameSize | 表示元組 (w, h),視頻幀的寬度和高度。 |
isColor | 表示是否彩色圖像。 |
5. cv.VideoCapture 和 cv.VideoWriter 的成員函數(shù)
函數(shù)名 | 說明 |
---|
cv.VideoCapture.isOpened() | 表示檢查視頻捕獲是否初始化成功。 |
cv.VideoCapture.read() | 表示捕獲視頻文件、視頻流或捕獲的視頻設備。 |
cv.VideoCapture.get(propId) | 表示獲取 VideoCapture 類對象的屬性。 |
cv.VideoCapture.set(propId, value) | 表示設置 VideoCapture 類對象的屬性。 |
cv.VideoCapture.release() | 表示關閉視頻文件或設備,釋放對象。 |
cv.VideoWriter.fourcc(c1, c2, c3, c4[, ]) | 表示構造編碼器/解碼器的fourcc代碼。 |
cv.VideoWriter.write(image[, ]) | 表示寫入下一幀視頻。 |
cv.VideoWriter.release() | 表示關閉視頻寫入,釋放對象。 |
6. 實例將 .avi 轉 .mp4
6.1 實例代碼
import cv2 as cv
import imageio# 讀取視頻,將視頻按照幀導出圖片
def get_video_images(video_path):cap = cv.VideoCapture(video_path)images = []while cap.isOpened():ret, frame = cap.read() # 讀取下一幀視頻圖像if ret is True:cv.imshow("frame", frame)images.append(frame)key = cv.waitKey(24)if key == ord('q'):breakelse:breakcap.release()cv.destroyAllWindows()return images# 轉MP4
def create_mp4(filename, fps, images):h,w,c = images[0].shapefourcc = cv.VideoWriter_fourcc(*'mp4v')writer = cv.VideoWriter(filename, fourcc, fps, (w,h))for frame in images:writer.write(frame)writer.release()if __name__ == "__main__":imgs = get_video_images('./images/Megamind.avi')create_mp4('./images/Megamind.mp4', 24, imgs)
6.2 轉換結果使用 gif 展示

7. 總結
- 視頻寫入類VideoWriter的參數(shù)frameSize是元組 (w, h),即視頻幀的寬度和高度,而OpenCV圖像的形狀是 (h, w),注意二者的順序相反;
- write 寫入圖片的寬高必須保持一直;
- 使用攝像頭時,index=0 表示默認后端打開默認攝像機,例如筆記本內置攝像頭。