要捕獲視頻,您需要創建一個VideoCapture對象。它的參數可以是該設備的索引或視頻文件的名稱。在此之後,可以捕獲幀接一幀。但最後,不要忘了釋放捕獲。
import numpy as np
import cv2
cap = cv2.VideoCapture(0)
while(True):
# Capture frame-by-frame
ret, frame = cap.read()
# Our operations 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'):
break
# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()
從文件播放頻
只需更改視頻文件名 稱相機索引。使用適當的時間cv2.waitKey() 。如果過少,視頻會非常快,如果它是太高,視頻將是緩慢的。
import numpy as np
import cv2
cap = cv2 . VideoCapture ( 'vtest.avi' )
while ( cap . isOpened ()):
ret , frame = cap . read ()
gray = cv2 . cvtColor ( frame , cv2 . COLOR_BGR2GRAY )
cv2 . imshow ( 'frame' , gray )
if cv2 . waitKey ( 1 ) & 0xFF == ord ( 'q' ):
break
cap . release ()
cv2 . destroyAllWindows ()
保存視頻
因此,我們捕捉視頻,過程中,我們要保存的視頻。這是非常簡單,只需使用cv2.imwrite() 。在這裡,更多一點的工作是必需的。 這一次,我們創建了一個VideoWriter對象。我們應當指定輸出文件名 (如:output.avi)。那麼我們就應該指定的FourCC代碼,然後每秒(fps)的和幀大小幀的數量應傳遞。而最後一個是isColor標誌。如果這是真的,編碼器期望彩色幀,否則它與灰度框架。
FourCC是用於指定視頻編解碼器4字節代碼。
import numpy as np
import cv2
cap = cv2.VideoCapture(0)
# Define the codec and create VideoWriter object
fourcc = cv2.cv.CV_FOURCC('m', 'p', '4', 'v')
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()
參考資料:
https://opencv-python-tutroals.readthedocs.org/en/latest/py_tutorials/py_gui/py_video_display/py_video_display.html http://stackoverflow.com/questions/26452909/opencv-write-frame-to-file-python
No comments:
Post a Comment