python3將視頻流保存爲本地視頻文件

使用python3+opencv3.3.1環境


1、利用opencv中的VideoCapture類獲取視頻流的鏈接,通過cv2的方法得到該視頻流的幀數和每幀大小。

2、使用VideoWriter類進行視頻編碼

3、通過VideoCapture的read()方法進行視頻流解碼成每一幀

4、獲取到每一幀frame,我們就可以對該幀做圖像算法(例如識別、圖像加強、灰度變換等)

import cv2
from matplotlib import pyplot as plt

#通過cv2中的類獲取視頻流操作對象cap
cap = cv2.VideoCapture('rtsp://admin:[email protected]:554/MPEG-4/ch1/main/av_stream')
#調用cv2方法獲取cap的視頻幀(幀:每秒多少張圖片)
fps = cap.get(cv2.CAP_PROP_FPS)
print(fps)
#獲取cap視頻流的每幀大小
size = (int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)),
        int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)))
print(size)

#定義編碼格式mpge-4
fourcc = cv2.VideoWriter_fourcc('M', 'P', '4', '2')
#定義視頻文件輸入對象
outVideo = cv2.VideoWriter('saveDir.avi',fourcc,fps,size)

#獲取視頻流打開狀態
if cap.isOpened():
    rval,frame = cap.read()
    print('ture')
else:
    rval = False
    print('False')

tot=1
c=1
#循環使用cv2的read()方法讀取視頻幀
while rval:
    rval,frame = cap.read()
    cv2.imshow('test',frame)
    #每間隔20幀保存一張圖像幀
    # if tot % 20 ==0 :
    #     cv2.imwrite('cut/'+'cut_'+str(c)+'.jpg',frame)
    #     c+=1
    tot+=1
    print('tot=',tot)
    #使用VideoWriter類中的write(frame)方法,將圖像幀寫入視頻文件
    outVideo.write(frame)
    cv2.waitKey(1)
cap.release()
outVideo.release()
cv2.destroyAllWindows()

結果:


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章