Saving key event video clips with OpenCV

import cv2
import collections
import time

# Parameters
video_source = 0 # Use 0 for webcam, or provide a video file path
output_dir = “key_event_clips”
buffer_size = 50 # Number of frames to buffer before the event
clip_duration = 2 # Duration of the clip after the event (in seconds)
fps = 30 # Frames per second (adjust if necessary)

# Create a buffer to store recent frames
frame_buffer = collections.deque(maxlen=buffer_size)

# Initialize video capture
cap = cv2.VideoCapture(video_source)

# Check if video capture is opened
if not cap.isOpened():
print(“Error: Could not open video source.”)
exit()

frame_width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
frame_height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
fourcc = cv2.VideoWriter_fourcc(*’XVID’)

# Ensure output directory exists
import os
if not os.path.exists(output_dir):
os.makedirs(output_dir)

print(“Press ‘e’ to trigger key event and save clip. Press ‘q’ to quit.”)

key_event = False
clip_writer = None
clip_start_time = None

while cap.isOpened():
ret, frame = cap.read()
if not ret:
print(“Error: Frame capture failed or video ended.”)
break

# Add the frame to the buffer
frame_buffer.append(frame)

# Display the video
cv2.imshow(“Video”, frame)

key = cv2.waitKey(1) & 0xFF
if key == ord(‘e’):
key_event = True
timestamp = time.strftime(“%Y%m%d-%H%M%S”)
clip_path = os.path.join(output_dir, f”clip_{timestamp}.avi”)
clip_writer = cv2.VideoWriter(clip_path, fourcc, fps, (frame_width, frame_height))
print(f”Key event triggered! Saving clip to {clip_path}”)

# Write buffered frames to file
for buf_frame in frame_buffer:
clip_writer.write(buf_frame)

# Record the start time for additional frames
clip_start_time = time.time()

if key_event and (time.time() – clip_start_time) <= clip_duration:
clip_writer.write(frame)
elif key_event:
key_event = False
clip_writer.release()
print(“Clip saved successfully.”)

if key == ord(‘q’):
break

# Release resources
cap.release()
if clip_writer:
clip_writer.release()
cv2.destroyAllWindows()

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top