import cv2
# Open the video capture (0 for the default camera or a video file path)
cap = cv2.VideoCapture(0)
# Check if the camera is opened successfully
if not cap.isOpened():
print(“Error: Could not open camera.”)
exit()
# Get the frame width and height to define the video codec
frame_width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
frame_height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
# Define the codec and create a VideoWriter object to save the video
fourcc = cv2.VideoWriter_fourcc(*’XVID’)
out = None
is_recording = False
while True:
ret, frame = cap.read()
if not ret:
print(“Error: Failed to grab frame.”)
break
# Display the frame in a window
cv2.imshow(‘Video Feed’, frame)
# Wait for key event
key = cv2.waitKey(1) & 0xFF
# If ‘q’ is pressed, exit the loop
if key == ord(‘q’):
break
# If ‘s’ is pressed, start recording
if key == ord(‘s’) and not is_recording:
# Initialize the VideoWriter to save the clip
out = cv2.VideoWriter(‘video_clip.avi’, fourcc, 20.0, (frame_width, frame_height))
is_recording = True
print(“Recording started…”)
# If ‘e’ is pressed, stop recording
if key == ord(‘e’) and is_recording:
is_recording = False
out.release()
print(“Recording stopped.”)
# Write the frame to the video file if recording
if is_recording and out is not None:
out.write(frame)
# Release everything once done
cap.release()
if out is not None:
out.release()
cv2.destroyAllWindows()