这是读取摄像头显示的代码 gst-launch-1.0 nvarguscamerasrc sensor-id=0 ! "video/x-raw(memory:NVMM),width=4032,height=3040,framerate=30/1" ! nvvidconv ! "video/x-raw(memory:NVMM),width=1920,height=1080,framerate=30/1" ! nvoverlaysink 这是读取摄像头保存图片的代码 gst-launch-1.0 -e nvarguscamerasrc num-buffers=20 sensor-id=0 ! "video/x-raw(memory:NVMM),width=4032,height=3040,framerate=30 读取摄像头保存视频的代码 gst-launch-1.0 -e nvarguscamerasrc sensor-id=0 ! "video/x-raw(memory:NVMM),width=4032,height=3040,framerate=30/1" ! nvv4l2h264enc ! h264parse ! mp4mux ! filesink location=rpi_v3_imx477_cam0.mp4 根据以上代码,写一段代码显示摄像头画面,并按s键保存图片和视频,名称加上时间戳,按q键退出
要实现一个程序,能够显示摄像头画面,并在按下 s
键时保存图片和视频,按下 q
键退出,我们可以使用 Python 和 GStreamer 的绑定库 gi
。以下是一个示例代码,展示了如何实现这个功能:
import gi
import time
import datetime
import os
import sys
from gi.repository import GObject, Gst, GLib
# 初始化GStreamer
Gst.init(None)
# 创建GStreamer管道
pipeline = Gst.parse_launch(
'nvarguscamerasrc sensor-id=0 ! '
'video/x-raw(memory:NVMM),width=4032,height=3040,framerate=30/1 ! '
'nvvidconv ! '
'video/x-raw, width=1920, height=1080 ! '
'nvoverlaysink name=overlay'
)
# 创建保存图片和视频的函数
def save_image_and_video():
timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
image_filename = f"image_{timestamp}.jpg"
video_filename = f"video_{timestamp}.mp4"
# 保存图片
os.system(f"gst-launch-1.0 -e nvarguscamerasrc num-buffers=1 sensor-id=0 ! "
f"video/x-raw(memory:NVMM),width=4032,height=3040,framerate=30/1 ! "
f"nvjpegenc ! filesink location={image_filename}")
# 保存视频
os.system(f"gst-launch-1.0 -e nvarguscamerasrc sensor-id=0 ! "
f"video/x-raw(memory:NVMM),width=4032,height=3040,framerate=30/1 ! "
f"nvv4l2h264enc ! h264parse ! mp4mux ! filesink location={video_filename}")
print(f"Saved image as {image_filename} and video as {video_filename}")
# 处理键盘输入
def handle_keypress():
while True:
key = input("Press 's' to save image and video, 'q' to quit: ")
if key.lower() == 's':
save_image_and_video()
elif key.lower() == 'q':
break
# 启动GStreamer管道
pipeline.set_state(Gst.State.PLAYING)
# 启动键盘输入处理
handle_keypress()
# 停止GStreamer管道
pipeline.set_state(Gst.State.NULL)
nvarguscamerasrc
来获取摄像头视频流,并通过 nvoverlaysink
显示在屏幕上。save_image_and_video
函数中,我们使用 os.system
来调用 GStreamer 命令行工具保存图片和视频。文件名中包含时间戳。input
函数来处理用户输入,按下 s
键时保存图片和视频,按下 q
键时退出程序。