根据以下代码写一段代码按s键保存视频,视频名称含有时间戳,按q键退出 SENSOR_ID=0 # 0 for CAM0 and 1 for CAM1 ports FRAMERATE=30 # Framerate can go from 2 to 30 for 4032x3040 mode gst-launch-1.0 -e nvarguscamerasrc sensor-id=$SENSOR_ID ! "video/x-raw(memory:NVMM),width=4032,height=3040,framerate=$FRAMERATE/1" ! nvv4l2h264enc ! h264parse ! mp4mux ! filesink location=rpi_v3_imx477_cam$SENSOR_ID.mp4
要实现按 s
键保存视频并在文件名中包含时间戳,按 q
键退出的功能,可以使用 Python 的 cv2
库来捕获视频流,并结合 keyboard
库来监听键盘事件。以下是一个示例代码:
import cv2
import time
import keyboard
SENSOR_ID = 0 # 0 for CAM0 and 1 for CAM1 ports
FRAMERATE = 30 # Framerate can go from 2 to 30 for 4032x3040 mode
# 创建视频捕获对象
cap = cv2.VideoCapture(f'nvarguscamerasrc sensor-id={SENSOR_ID} ! video/x-raw(memory:NVMM),width=4032,height=3040,framerate={FRAMERATE}/1 ! nvvidconv ! video/x-raw,format=BGR ! appsink', cv2.CAP_GSTREAMER)
if not cap.isOpened():
print("无法打开摄像头")
exit()
recording = False
out = None
while True:
ret, frame = cap.read()
if not ret:
print("无法读取帧")
break
cv2.imshow('Camera', frame)
# 检测按键
if keyboard.is_pressed('s') and not recording:
timestamp = time.strftime("%Y%m%d_%H%M%S")
filename = f'rpi_v3_imx477_cam{SENSOR_ID}_{timestamp}.mp4'
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
out = cv2.VideoWriter(filename, fourcc, FRAMERATE, (4032, 3040))
recording = True
print(f"开始录制: {filename}")
if recording:
out.write(frame)
if keyboard.is_pressed('q'):
print("退出程序")
break
# 释放资源
cap.release()
if out is not None:
out.release()
cv2.destroyAllWindows()
cv2.VideoCapture
从 GStreamer 管道中捕获视频流。keyboard
库监听 s
和 q
键。
s
键时,开始录制视频,并生成带有时间戳的文件名。q
键时,退出程序。cv2.VideoWriter
将捕获的帧写入视频文件。opencv-python
和 keyboard
库,可以使用以下命令安装:
pip install opencv-python keyboard
keyboard
库需要全局键盘监听权限。