目標
• 學會讀取視頻文件,顯示視頻,保存視頻文件
• 學會從攝像頭獲取並顯示視頻
• 你將會學習到這些函數:cv2.VideoCapture(),cv2.VideoWrite()
用攝像頭捕獲視頻
- 使用攝像頭來捕獲一段視頻,並把它轉換成灰度視頻顯示出來。
- 首先應該創建一個VideoCapture 對象,參數可以是設備的索引號,或者是一個視頻文件。
- 設備索引號就是在指定要使用的攝像頭。一般的筆記本電腦都有內置攝像頭。所以參數就是0。你可以通過設置成1或者其他的來選擇別的攝像頭。
- 之后,你就可以一幀一幀的捕獲視頻了。但是最后,別忘了停止捕獲視頻。
上代碼:

1 # -*- coding: utf-8 -*- 2 3 import numpy as np 4 import cv2 5 6 cap = cv2.VideoCapture(0) # 創建一個VideoCapture對象 7 while(True): 8 9 ret, frame = cap.read() # 一幀一幀讀取視頻 10 gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)# 對每一幀做處理,設置為灰度圖 11 cv2.imshow('frame',gray) # 顯示結果 12 if cv2.waitKey(1) & 0xFF == ord('q'): # 按q停止 13 break 14 15 cap.release() # 釋放cap,銷毀窗口 16 cv2.destroyAllWindows()
- 運行一下可以看到攝像頭打開,並且顯示了灰度圖,按q退出
讀取視頻文件:

1 # -*- coding: utf-8 -*- 2 3 import numpy as np 4 import cv2 5 6 cap = cv2.VideoCapture(0) 7 8 # Define the codec and create VideoWriter object 9 fourcc = cv2.VideoWriter_fourcc(*'XVID') 10 out = cv2.VideoWriter('test.avi',fourcc, 20.0, (640,480)) 11 12 while(cap.isOpened()): 13 ret, frame = cap.read() 14 if ret==True: 15 frame = cv2.flip(frame,0) 16 17 # write the flipped frame 18 out.write(frame) 19 20 cv2.imshow('frame',frame) 21 if cv2.waitKey(1) & 0xFF == ord('q'): 22 break 23 else: 24 break 25 # Release everything if job is finished 26 cap.release() 27 out.release() 28 cv2.destroyAllWindows()
- 本例子中的演示會比較麻煩。需要安裝合適版本的ffmpeg 或者gstreamer,才能正確運行改程序