2017-07-23 74 views
0

我想使用OpenCV和網絡攝像頭連續錄製視頻15分鐘,然後再次啓動該過程,以便獲得15分鐘的視頻。 我已經寫了一個腳本,但遇到意想不到的行爲。錄製工作一段時間,然後該程序只會創建5kb大小的文件,無法播放。Python OpcenCV將錄製文件分割爲多個文件

有人會知道爲什麼會發生這種情況嗎?

這是代碼:

import numpy as np 
import cv2 
import time 


cap = cv2.VideoCapture(0) 

#Record the current time 
current_time = time.time() 

#Specify the path and name of the video file as well as the encoding, fps and resolution 
out = cv2.VideoWriter('/mnt/NAS326/cctv/' + str(time.strftime('%d %m %Y - %H %M %S')) + '.avi', cv2.cv.CV_FOURCC('X','V','I','D'), 15, (640,480)) 




while(True): 



    # Capture frame-by-frame 
    ret, frame = cap.read() 
    out.write(frame) 

    #If the current time is greater than 'current_time' + seconds specified then release the video, record the time again and start a new recording 
    if time.time() >= current_time + 900: 
     out.release() 
     current_time = time.time() 
     out = cv2.VideoWriter('/mnt/NAS326/cctv/' + str(time.strftime('%d %m %Y - %H %M %S')) + '.avi', cv2.cv.CV_FOURCC('X','V','I','D'), 15, (640,480)) 



out.release() 

cap.release() 




cv2.destroyAllWindows() 

回答

0

如上所述,您應該測試cap.read()是sucessfull,且僅當它是有效的編寫框架。這可能導致輸出文件出現問題。在需要時提前next_time以避免輕微的時間延遲也更好。

import numpy as np 
import cv2 
import time 


def get_output(out=None): 
    #Specify the path and name of the video file as well as the encoding, fps and resolution 
    if out: 
     out.release() 
    return cv2.VideoWriter('/mnt/NAS326/cctv/' + str(time.strftime('%d %m %Y - %H %M %S')) + '.avi', cv2.cv.CV_FOURCC('X','V','I','D'), 15, (640,480)) 

cap = cv2.VideoCapture(0) 
next_time = time.time() + 900 
out = get_output() 

while True: 
    if time.time() > next_time: 
     next_time += 900 
     out = get_output(out) 

    # Capture frame-by-frame 
    ret, frame = cap.read() 

    if ret: 
     out.write(frame) 

cap.release() 
cv2.destroyAllWindows() 
相關問題