使用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:passwd@10.130.10.111: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()
結果:
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林站長站。
新聞熱點
疑難解答