from datetime import datetime, date, time, timedelta import cv2 def five_minute_segment_from(the_time): return the_time.replace(minute=(the_time.minute // 1)*1, second=0, microsecond=0) def video_address_for(time_stamp): return 'videos/' + str(time_stamp) + '.mkv' queue = [(False, None)] * 100 #queue of recent frames last_time_stamp = five_minute_segment_from(datetime.now()) # live webcam feed camera = cv2.VideoCapture(0) camera.set(cv2.CAP_PROP_FPS, 30.0) if not camera.isOpened(): print("Cannot open camera") exit() # video writer fourcc = cv2.VideoWriter_fourcc(*'H264') out = cv2.VideoWriter(video_address_for(last_time_stamp), fourcc, camera.get(cv2.CAP_PROP_FPS), (int(camera.get(3)),int(camera.get(4)))) # video feed from previously captured video old_time = cv2.VideoCapture(video_address_for(last_time_stamp)) idx = 0 offset = 0 longterm = False while(True): if last_time_stamp != five_minute_segment_from(datetime.now()): out.release() out = cv2.VideoWriter(video_address_for(last_time_stamp), fourcc, camera.get(cv2.CAP_PROP_FPS), (int(camera.get(3)), int(camera.get(4))) ) if old_time.isOpened(): old_time.release() old_time = cv2.VideoCapture(video_address_for(five_minute_segment_from(datetime.now() - timedelta(minutes=10)))) last_time_stamp = five_minute_segment_from(datetime.now()) ret, frame = camera.read() frame = cv2.flip(frame, 1) #recod the frame out.write(frame) queue[idx] = ret, frame showo, fr = queue[(idx - offset) % len(queue)] if longterm: ret2, frame2 = old_time.read() if ret2: cv2.imshow('vid', frame2) elif showo: cv2.imshow('vid', fr) # the 'q' button is set as the quitting button you may use any desired button of your choice key = cv2.waitKey(1) & 0xFF if key == ord('q'): break if key == ord('a'): offset += 1 if key == ord('d'): offset -= 1 if key == ord('z'): longterm = not longterm idx = (idx + 1) % len(queue) # After the loop release the cap object camera.release() out.release() # Destroy all the windows cv2.destroyAllWindows()