VideoSaver 的自定义 Host Node,该节点接收来自 Video Encoder 节点的编码视频帧,并将它们保存到主机计算机上的文件中。录制结束后,用户需要使用 ffmpeg 将原始编码流转换为可播放的视频文件。可以将 VideoSaver 节点扩展为直接保存到容器中,如 将编码视频流保存到 mp4 容器 实验所示。演示输出
Command Line
1python3 video_encode.py
2Started to save video to video.encoded
3Press Ctrl+C to stop
4To view the encoded data, convert the stream file (.encoded) into a video file (.mp4) using a command below:
5ffmpeg -framerate 30 -i video.encoded -c copy video.mp4ffmpeg 命令后,您应该使用 VLC 播放器来查看视频文件,特别是对于 H265 格式,因为它并非所有视频播放器都支持(例如 MacOS 上的 QuickTime)。此示例需要 DepthAI v3 API,请参阅 安装说明。Pipeline
源代码
Python
PythonGitHub
1import depthai as dai
2
3# Capture Ctrl+C and set a flag to stop the loop
4import time
5import cv2
6import threading
7import signal
8
9PROFILE = dai.VideoEncoderProperties.Profile.MJPEG # or H265_MAIN, H264_MAIN
10
11quitEvent = threading.Event()
12signal.signal(signal.SIGTERM, lambda *_args: quitEvent.set())
13signal.signal(signal.SIGINT, lambda *_args: quitEvent.set())
14
15class VideoSaver(dai.node.HostNode):
16 def __init__(self, *args, **kwargs):
17 dai.node.HostNode.__init__(self, *args, **kwargs)
18 self.file_handle = open('video.encoded', 'wb')
19
20 def build(self, *args):
21 self.link_args(*args)
22 return self
23
24 def process(self, frame):
25 frame.getData().tofile(self.file_handle)
26
27with dai.Pipeline() as pipeline:
28 camRgb = pipeline.create(dai.node.Camera).build(dai.CameraBoardSocket.CAM_A)
29 output = camRgb.requestOutput((1920, 1440), type=dai.ImgFrame.Type.NV12)
30 outputQueue = output.createOutputQueue()
31 encoded = pipeline.create(dai.node.VideoEncoder).build(output,
32 frameRate = 30,
33 profile = PROFILE)
34 saver = pipeline.create(VideoSaver).build(encoded.out)
35
36 pipeline.start()
37 print("Started to save video to video.encoded")
38 print("Press Ctrl+C to stop")
39 timeStart = time.monotonic()
40 while pipeline.isRunning() and not quitEvent.is_set():
41 frame = outputQueue.get()
42 assert isinstance(frame, dai.ImgFrame)
43 cv2.imshow("video", frame.getCvFrame())
44 key = cv2.waitKey(1)
45 if key == ord('q'):
46 break
47 pipeline.stop()
48 pipeline.wait()
49 saver.file_handle.close()
50
51print("To view the encoded data, convert the stream file (.encoded) into a video file (.mp4) using a command below:")
52print("ffmpeg -framerate 30 -i video.encoded -c copy video.mp4")需要帮助?
请前往 Discussion Forum 获取技术支持或提出您可能有的任何其他问题。