2017-07-23 71 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() 
相关问题