Problem statement: Essentially i am trying to make a raspberry pi zero based dashcam. I need a clip of 10s with the filename as current date and time. This loop should continue as long as the pi has power supply. i've written the script as shown but it doesn't create separate files of 10s clips but one big file. Any clues on what i'm doing wrong ?
import cv2
import time
cv2.namedWindow("dashcam")
video = cv2.VideoCapture(1)
if video.isOpened(): # try to get the first frame
rval, frame = video.read()
else:
rval = False
frame_width = int(video.get(3))
frame_height = int(video.get(4))
timestr = time.strftime("%Y_%m_%d__%H_%M_%S")
out = cv2.VideoWriter(timestr+'.avi', cv2.VideoWriter_fourcc('M', 'J', 'P', 'G'), 10, (frame_width, frame_height))
now = time.time()
while rval:
rval, frame = video.read()
if time.time() - now < 5:
cv2.imshow('dashcam', frame)
out.write(frame)
elif time.time() - now > 5:
now = time.time()
key = cv2.waitKey(1)
if key == 27: # exit on ESC
break
video.release()
out.release()
cv2.destroyAllWindows()
Because you only create "out" once time, your code will save only 1 video. You maybe try my code below. Report to me if you have any error with my code.
import cv2
import time
cv2.namedWindow("dashcam")
video = cv2.VideoCapture(1)
last_save_time = -10
while video.isOpened():
rval, frame = video.read()
if not rval:
break
frame_width = int(video.get(3))
frame_height = int(video.get(4))
current_time = time.time()
if current_time - last_save_time > 10:
last_save_time = current_time
timestr = time.strftime("%Y_%m_%d__%H_%M_%S")
out = cv2.VideoWriter(timestr+'.avi', cv2.VideoWriter_fourcc('M', 'J', 'P', 'G'), 25, (frame_width, frame_height))
cv2.imshow('dashcam', frame)
out.write(frame)
key = cv2.waitKey(1)
if key == 27: # exit on ESC
break
video.release()
cv2.destroyAllWindows()