我想使用OpenCV和网络摄像头连续录制来自网络摄像头的视频15分钟,然后再次启动该过程,以便我有15分钟的视频块。 我已经写了一个脚本,但遇到了意想不到的行为。录制工作正常一段时间,然后程序只会创建5kb大小不可播放的文件。
有人会知道为什么会这样吗?
这是代码:
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 :(得分:1)
如前所述,您应该测试cap.read()
是否成功,并且只有在有效时才写入帧。这可能导致输出文件出现问题。最好只在需要时提前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()