DepthAI v2 has been superseded by DepthAI v3. You are viewing legacy documentation.
此页面由 AI 自动翻译。查看英文原版
DepthAI 教程
DepthAI API 参考

本页目录

  • 演示
  • 设置
  • 源代码
  • 管道

Script MJPEG 服务器

此演示在设备本身上运行一个 HTTP 服务器。连接到服务器后,它将为您提供 MJPEG 流。

演示

运行演示时,它将打印类似以下内容:
Command Line
1Serving at 192.168.1.193:8080
如果您在浏览器(例如 Chrome)中打开此 IP,您将看到:
software/depthai/example/http_server.webp
如果您点击 here 链接,您将获得 MJPEG 视频流。要查看静态图像,您可以参考 Script HTTP server

设置

请运行 安装脚本 以下载所有必需的依赖项。请注意,此脚本必须在 git 上下文中运行,因此您必须先下载 depthai-python 存储库,然后运行脚本
Command Line
1git clone https://github.com/luxonis/depthai-python.git
2cd depthai-python/examples
3python3 install_requirements.py
有关更多信息,请遵循 安装指南

源代码

Python

Python
GitHub
1#!/usr/bin/env python3
2
3import depthai as dai
4import time
5
6# Start defining a pipeline
7pipeline = dai.Pipeline()
8
9# Define a source - color camera
10cam = pipeline.create(dai.node.ColorCamera)
11# VideoEncoder
12jpeg = pipeline.create(dai.node.VideoEncoder)
13jpeg.setDefaultProfilePreset(cam.getFps(), dai.VideoEncoderProperties.Profile.MJPEG)
14
15# Script node
16script = pipeline.create(dai.node.Script)
17script.setProcessor(dai.ProcessorType.LEON_CSS)
18script.setScript("""
19    import time
20    import socket
21    import fcntl
22    import struct
23    from socketserver import ThreadingMixIn
24    from http.server import BaseHTTPRequestHandler, HTTPServer
25
26    PORT = 8080
27
28    def get_ip_address(ifname):
29        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
30        return socket.inet_ntoa(fcntl.ioctl(
31            s.fileno(),
32            -1071617759,  # SIOCGIFADDR
33            struct.pack('256s', ifname[:15].encode())
34        )[20:24])
35
36    class ThreadingSimpleServer(ThreadingMixIn, HTTPServer):
37        pass
38
39    class HTTPHandler(BaseHTTPRequestHandler):
40        def do_GET(self):
41            if self.path == '/':
42                self.send_response(200)
43                self.end_headers()
44                self.wfile.write(b'<h1>[DepthAI] Hello, world!</h1><p>Click <a href="img">here</a> for an image</p>')
45            elif self.path == '/img':
46                try:
47                    self.send_response(200)
48                    self.send_header('Content-type', 'multipart/x-mixed-replace; boundary=--jpgboundary')
49                    self.end_headers()
50                    fpsCounter = 0
51                    timeCounter = time.time()
52                    while True:
53                        jpegImage = node.io['jpeg'].get()
54                        self.wfile.write("--jpgboundary".encode())
55                        self.wfile.write(bytes([13, 10]))
56                        self.send_header('Content-type', 'image/jpeg')
57                        self.send_header('Content-length', str(len(jpegImage.getData())))
58                        self.end_headers()
59                        self.wfile.write(jpegImage.getData())
60                        self.end_headers()
61
62                        fpsCounter = fpsCounter + 1
63                        if time.time() - timeCounter > 1:
64                            node.warn(f'FPS: {fpsCounter}')
65                            fpsCounter = 0
66                            timeCounter = time.time()
67                except Exception as ex:
68                    node.warn(str(ex))
69
70    with ThreadingSimpleServer(("", PORT), HTTPHandler) as httpd:
71        node.warn(f"Serving at {get_ip_address('re0')}:{PORT}")
72        httpd.serve_forever()
73""")
74
75# Connections
76cam.video.link(jpeg.input)
77jpeg.bitstream.link(script.inputs['jpeg'])
78
79# Connect to device with pipeline
80with dai.Device(pipeline) as device:
81    while not device.isClosed():
82        time.sleep(1)

C++

1#include <chrono>
2#include <iostream>
3#include <thread>
4
5// Includes common necessary includes for development using depthai library
6#include "depthai/depthai.hpp"
7
8int main() {
9    using namespace std;
10
11    // Start defining a pipeline
12    dai::Pipeline pipeline;
13
14    auto cam = pipeline.create<dai::node::ColorCamera>();
15
16    auto jpeg = pipeline.create<dai::node::VideoEncoder>();
17    jpeg->setDefaultProfilePreset(cam->getFps(), dai::VideoEncoderProperties::Profile::MJPEG);
18    cam->video.link(jpeg->input);
19
20    // Script node
21    auto script = pipeline.create<dai::node::Script>();
22    script->setProcessor(dai::ProcessorType::LEON_CSS);
23    jpeg->bitstream.link(script->inputs["jpeg"]);
24    script->setScript(R"(
25    import time
26    import socket
27    import fcntl
28    import struct
29    from socketserver import ThreadingMixIn
30    from http.server import BaseHTTPRequestHandler, HTTPServer
31
32    PORT = 8080
33
34    def get_ip_address(ifname):
35        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
36        return socket.inet_ntoa(fcntl.ioctl(
37            s.fileno(),
38            -1071617759,  # SIOCGIFADDR
39            struct.pack('256s', ifname[:15].encode())
40        )[20:24])
41
42    class ThreadingSimpleServer(ThreadingMixIn, HTTPServer):
43        pass
44
45    class HTTPHandler(BaseHTTPRequestHandler):
46        def do_GET(self):
47            if self.path == '/':
48                self.send_response(200)
49                self.end_headers()
50                self.wfile.write(b'<h1>[DepthAI] Hello, world!</h1><p>Click <a href="img">here</a> for an image</p>')
51            elif self.path == '/img':
52                try:
53                    self.send_response(200)
54                    self.send_header('Content-type', 'multipart/x-mixed-replace; boundary=--jpgboundary')
55                    self.end_headers()
56                    fpsCounter = 0
57                    timeCounter = time.time()
58                    while True:
59                        jpegImage = node.io['jpeg'].get()
60                        self.wfile.write("--jpgboundary".encode())
61                        self.wfile.write(bytes([13, 10]))
62                        self.send_header('Content-type', 'image/jpeg')
63                        self.send_header('Content-length', str(len(jpegImage.getData())))
64                        self.end_headers()
65                        self.wfile.write(jpegImage.getData())
66                        self.end_headers()
67
68                        fpsCounter = fpsCounter + 1
69                        if time.time() - timeCounter > 1:
70                            node.warn(f'FPS: {fpsCounter}')
71                            fpsCounter = 0
72                            timeCounter = time.time()
73                except Exception as ex:
74                    node.warn(str(ex))
75
76    with ThreadingSimpleServer(("", PORT), HTTPHandler) as httpd:
77        node.warn(f"Serving at {get_ip_address('re0')}:{PORT}")
78        httpd.serve_forever()
79    )");
80
81    // Connect to device with pipeline
82    dai::Device device(pipeline);
83    while(!device.isClosed()) {
84        this_thread::sleep_for(chrono::milliseconds(1000));
85    }
86    return 0;
87}

管道

需要帮助?

请前往 Discussion Forum 获取技术支持或提出您可能有的任何其他问题。