此页面由 AI 自动翻译。查看英文原版
DepthAI
  • DepthAI 组件
    • AprilTags
    • 基准测试
    • Camera
    • 校准
    • DetectionNetwork
    • Events
    • FeatureTracker
    • Gate
    • HostNodes
    • ImageAlign
    • ImageManip
    • IMU
    • 杂项
    • 模型动物园
    • NeuralDepth
    • NeuralNetwork
    • ObjectTracker
    • 点云
    • RecordReplay
    • RGBD
    • Script
    • SpatialDetectionNetwork
    • SpatialLocationCalculator
    • StereoDepth
    • Sync
    • VideoEncoder
    • Visualizer
    • Warp
    • RVC2-specific
  • 高级教程
  • API 参考
  • 工具
软件栈

本页目录

  • Pipeline
  • 源代码

脚本切换所有摄像头

Supported on:RVC2RVC4
通过按键在摄像头之间切换。此示例需要 DepthAI v3 API,请参阅 安装说明

Pipeline

源代码

Python

Python
GitHub
1import depthai as dai
2import time
3import cv2
4
5# Create pipeline
6device = dai.Device()
7pipeline = dai.Pipeline(device)
8
9cameras = [
10    pipeline.create(dai.node.Camera).build(socket)
11    for socket in device.getConnectedCameras()
12]
13inputKeys = []
14script = pipeline.create(dai.node.Script)
15
16for i, camera in enumerate(cameras):
17    inputName = str(i)
18    camera.requestFullResolutionOutput().link(script.inputs[inputName])
19    script.inputs[inputName].setBlocking(False)
20    script.inputs[inputName].setMaxSize(1)
21    inputKeys.append(inputName)
22
23controlQueue = script.inputs["control"].createInputQueue()
24preview = script.outputs["out"].createOutputQueue()
25
26inputKeysSize = len(inputKeys)
27script.setScript(
28    f"""
29    inputToStream = 0
30    maxID = {inputKeysSize} - 1
31    while True:
32        controlMessage = node.inputs["control"].tryGet()
33        if controlMessage is not None:
34            if(inputToStream < maxID):
35                inputToStream += 1
36            else:
37                inputToStream = 0
38        frame = node.inputs[str(inputToStream)].get()
39        node.outputs["out"].send(frame)
40"""
41)
42
43pipeline.start()
44print("To switch between streams, press 's'")
45with pipeline:
46    while pipeline.isRunning():
47        previewMessage = preview.get()
48        assert isinstance(previewMessage, dai.ImgFrame)
49        cv2.imshow("preview", previewMessage.getCvFrame())
50        key = cv2.waitKey(1)
51        if key == ord("s"):
52            controlQueue.send(dai.Buffer())
53        if key == ord("q"):
54            break

C++

1#include <atomic>
2#include <csignal>
3#include <iostream>
4#include <memory>
5#include <opencv2/opencv.hpp>
6#include <vector>
7
8#include "depthai/depthai.hpp"
9
10// Global flag for graceful shutdown
11std::atomic<bool> quitEvent(false);
12
13// Signal handler
14void signalHandler(int signum) {
15    quitEvent = true;
16}
17
18int main() {
19    // Set up signal handlers
20    signal(SIGTERM, signalHandler);
21    signal(SIGINT, signalHandler);
22
23    try {
24        // Create device and pipeline
25        std::shared_ptr<dai::Device> device = std::make_shared<dai::Device>();
26        dai::Pipeline pipeline(device);
27
28        // Get connected cameras and create camera nodes
29        std::vector<std::shared_ptr<dai::node::Camera>> cameras;
30        std::vector<std::string> inputKeys;
31
32        for(const auto& socket : device->getConnectedCameras()) {
33            auto camera = pipeline.create<dai::node::Camera>();
34            camera->build(socket);
35            cameras.push_back(camera);
36            inputKeys.push_back(std::to_string(cameras.size() - 1));
37        }
38
39        // Create script node
40        auto script = pipeline.create<dai::node::Script>();
41
42        // Link cameras to script inputs
43        for(size_t i = 0; i < cameras.size(); i++) {
44            std::string inputName = std::to_string(i);
45            cameras[i]->requestFullResolutionOutput()->link(script->inputs[inputName]);
46            script->inputs[inputName].setBlocking(false);
47            script->inputs[inputName].setMaxSize(1);
48        }
49
50        // Create control and preview queues
51        auto controlQueue = script->inputs["control"].createInputQueue();
52        auto preview = script->outputs["out"].createOutputQueue();
53
54        // Set the script content
55        std::string scriptContent = R"(
56            inputToStream = 0
57            maxID = )" + std::to_string(inputKeys.size() - 1)
58                                    + R"(
59            while True:
60                controlMessage = node.inputs["control"].tryGet()
61                if controlMessage is not None:
62                    if(inputToStream < maxID):
63                        inputToStream += 1
64                    else:
65                        inputToStream = 0
66                frame = node.inputs[str(inputToStream)].get()
67                node.outputs["out"].send(frame)
68        )";
69        script->setScript(scriptContent);
70
71        // Start pipeline
72        pipeline.start();
73        std::cout << "To switch between streams, press 's'" << std::endl;
74
75        // Main loop
76        while(pipeline.isRunning() && !quitEvent) {
77            auto previewMessage = preview->get<dai::ImgFrame>();
78            cv::Mat frame = previewMessage->getCvFrame();
79            cv::imshow("preview", frame);
80
81            int key = cv::waitKey(1);
82            if(key == 's') {
83                auto controlMessage = std::make_shared<dai::Buffer>();
84                controlQueue->send(controlMessage);
85            } else if(key == 'q') {
86                break;
87            }
88        }
89
90        // Cleanup
91        pipeline.stop();
92        pipeline.wait();
93
94    } catch(const std::exception& e) {
95        std::cerr << "Error: " << e.what() << std::endl;
96        return 1;
97    }
98
99    return 0;
100}

需要帮助?

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