在opencv中,攝像頭和視頻文件並沒有很大不同,都是一個可以read的數據源,使用cv2.VideoCapture(path).read()可以獲取(flag,當前幀),對於每一幀,使用圖片處理函數即可。
調用攝像頭並記錄為文件:
# 攝像頭讀取並寫入文件
cameraCapture = cv2.VideoCapture(0) # 獲取攝像頭對象
fps = 30
size = (int(cameraCapture.get(cv2.CAP_PROP_FRAME_WIDTH)),
int(cameraCapture.get(cv2.CAP_PROP_FRAME_HEIGHT)))
print(size)
videoWriter = cv2.VideoWriter('OutputVid.flv', cv2.VideoWriter_fourcc('F', 'L', 'V', '1'), fps, size) # 生成書寫器對象
# 成功與否flag, 下一幀圖像
success, frame = cameraCapture.read() # 攝像頭對象讀取數據
# 10s * 30fps
numFrameRamaining = 10 * fps - 1
print(success)
while success and numFrameRamaining > 0:
videoWriter.write(frame) # 書寫器對象記錄幀
success, frame = cameraCapture.read() # 攝像頭對象
numFrameRamaining -= 1 # 利用幀數計時:10s * 30fps
cameraCapture.release()
讀取本地視頻文件並另存為:
和上面的流程幾乎完全一樣,只是對象由攝像頭設備代號0改為視頻文件路徑
import cv2
# 讀取本地視頻並另存為
videoCapture = cv2.VideoCapture('OutputVid.flv')
fps = videoCapture.get(cv2.CAP_PROP_FPS)
size = (int(videoCapture.get(cv2.CAP_PROP_FRAME_WIDTH)),
int(videoCapture.get(cv2.CAP_PROP_FRAME_HEIGHT)))
videoWriter = cv2.VideoWriter('OutputVid2.flv', cv2.VideoWriter_fourcc('F', 'L', 'V', '1'), fps, size)
success, frame = videoCapture.read()
while success:
videoWriter.write(frame)
success, frame = videoCapture.read()
videoCapture.release()
print('finalish')
顯示圖片:
import cv2
img = cv2.imread('img2.jpg')
cv2.namedWindow("Image") # 可加可不加,加上的話一般和imshow之間會定義一些窗口事件處理用函數
cv2.imshow('Image', img) # 顯示圖片
cv2.waitKey()
cv2.destroyAllWindows() # 釋放所有窗口

窗口事件相應函數&視頻播放:
0表示主攝像頭,1表示前置攝像頭。
本程序調用攝像頭,並實時輸出,鍵盤輸入ESC或點擊窗口時會退出窗口。
import cv2
clicked = False
def onMouse(event, x, y, flags, param):
global clicked
if event == cv2.EVENT_LBUTTONUP: # 更多鼠標事件詳見書26頁
clicked = True
cv2.namedWindow('video')
cv2.setMouseCallback('video', onMouse) # 設置鼠標事件,對應窗口檢測到的數據會傳入接收函數中
print('攝像頭已啟動,鍵盤輸入ESC或者鼠標左擊窗口關閉攝像頭')
cameraCapture = cv2.VideoCapture(0)
if cameraCapture.isOpened():
while True:
success, frame = cameraCapture.read()
if success:
cv2.imshow('video', frame)
else:
break
if cv2.waitKey(20) == 27 or clicked: # cv2.waitKey()中20表示每次等待20毫秒,默認返回-1,接收ESC時返回27(就是返回ASCII實際)
break
cv2.destroyAllWindows()
。
