使用工具Python3.5,
使用庫numpy;opencv
1.用攝像頭捕獲視頻
cv2.VideoCapture() :0為默認計算機默認攝像頭,1可以更換來源;
~~~
import numpy as np
import cv2
cap = cv2.VideoCapture(0)
while(True):
#capture frame-by-frame
ret , frame = cap.read()
#our operation on the frame come here
gray = cv2.cvtColor(frame , cv2.COLOR_BGR2GRAY)
#display the resulting frame
cv2.imshow('frame',gray)
if cv2.waitKey(1) &0xFF ==ord('q'): #按q鍵退出
break
#when everything done , release the capture
cap.release()
cv2.destroyAllWindows()
~~~
當代碼報錯時,可以使用cap.isOpened()來檢查是否成功初始化了,返回值是True,就沒有問題,否則就要使用cap.open()。
可以使用cap.get(propId)來獲取視頻的一些參數信息。propId可以是0到18之間的任何數,每一個數代表一個屬性,自己可以嘗試一下。
其中一些值可以使用cap.set(propId,value)來修改,例如cap.get(3)和cap.get(4)來查看每一幀的寬和高,默認是640x480。我們可以使用ret=cap.set(3,320)和ret = cap.set(4,240)來把寬和高改成320x240。
2.從文件中播放視頻
把設備索引號改成文件名即可。在播放每一幀時,使用cv2.waitKey()適當持續時間,一般可以設置25ms。
~~~
import numpy as np
import cv2
cap=cv2.VideoCapture('filename.avi')#文件名及格式
while(True):
#capture frame-by-frame
ret , frame = cap.read()
#our operation on the frame come here
gray = cv2.cvtColor(frame , cv2.COLOR_BGR2GRAY)
#display the resulting frame
cv2.imshow('frame',gray)
if cv2.waitKey(1) &0xFF ==ord('q'): #按q鍵退出
break
#when everything done , release the capture
cap.release()
cv2.destroyAllWindows()
~~~
代碼中嘗試修改視頻流的一些屬性;


3.保存視頻
創建一個VideoWrite的對象,確定輸出文件名,指定FourCC編碼,播放頻率和幀的大小,最后是isColor標簽True為彩色。
FourCC是一個4字節碼,用來確定視頻的編碼格式。
1.In Fedora : DIVX , XVID , MJPG , X264 , WMV1 , WMV2
XVID是最好的,MJPG是高尺寸視頻,X264得到小尺寸視頻
2.In Windows : DIVX
3.In OSX :不知道用什么好
設置FourCC格式時,原文里采用了cv2.VideoWriter_fourcc()這個函數,若運行程序的時候顯示這個函數不存在,可以改用了cv2.cv.CV_FOURCC這個函數。
~~~
import numpy as np
import cv2
cap = cv2.VideoCapture(0)
# Define the codec and create VideoWriter object
fourcc = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter('output.avi',fourcc, 20.0, (640,480))
while(cap.isOpened()):
ret, frame = cap.read()
if ret==True:
frame = cv2.flip(frame,0)
# write the flipped frame
out.write(frame)
cv2.imshow('frame',frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
else:
break
# Release everything if job is finished
cap.release()
out.release()
cv2.destroyAllWindows()
~~~