I need to buffer some frames from a VideoCapture and then save the latest n frames
This works:
from cv2 import cv2
cap = cv2.VideoCapture(0)
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
fps = int(cap.get(cv2.CAP_PROP_FPS))
buffered_frames = []
frame = 0
frames_to_record = 180
while True:
success, img = cap.read()
if not success:
break
cv2.imshow("Stream", img)
if cv2.waitKey(fps) == ord('q'):
break
frame += 1
buffered_frames.append(img)
if frame % 500 == 0:
result = cv2.VideoWriter("./buffer.mp4", cv2.VideoWriter_fourcc(*'mp4v'), fps, (width, height))
for f in buffered_frames[ frame-frames_to_record: ]:
result.write(f)
result.release()
buffered_frames = []
frame = 0
cap.release()
However, I'm looking for some way to optimize this, saving the frames as a batch, so, instead of:
for f in buffered_frames[ frame-frames_to_record: ]:
result.write(f)
I'm looking for a way to save all the list at once, something like:
result.write(buffered_frames[ frame-frames_to_record: ])
But, the example above doesn't work, is there a way to save a batch of frames at once using OpenCV? (So it have some low-level optimization under the hood)