使用python3+opencv3.3.1環(huán)境將視頻流保存為本地視頻文件,具體內(nèi)容如下
1、利用opencv中的VideoCapture類獲取視頻流的鏈接,通過(guò)cv2的方法得到該視頻流的幀數(shù)和每幀大小。
2、使用VideoWriter類進(jìn)行視頻編碼
3、通過(guò)VideoCapture的read()方法進(jìn)行視頻流解碼成每一幀
4、獲取到每一幀frame,我們就可以對(duì)該幀做圖像算法(例如識(shí)別、圖像加強(qiáng)、灰度變換等)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
|
import cv2 from matplotlib import pyplot as plt #通過(guò)cv2中的類獲取視頻流操作對(duì)象cap #調(diào)用cv2方法獲取cap的視頻幀(幀:每秒多少?gòu)垐D片) 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' ) #定義視頻文件輸入對(duì)象 outVideo = cv2.VideoWriter( 'saveDir.avi' ,fourcc,fps,size) #獲取視頻流打開(kāi)狀態(tài) if cap.isOpened(): rval,frame = cap.read() print ( 'ture' ) else : rval = False print ( 'False' ) tot = 1 c = 1 #循環(huán)使用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() |
結(jié)果:
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持服務(wù)器之家。
原文鏈接:https://blog.csdn.net/Int93/article/details/78805414