DepthAI v2 has been superseded by DepthAI v3. You are viewing legacy documentation.
DepthAI 教程
DepthAI API 参考

本页目录

  • 设置
  • 用于测试的代码
  • 源代码
  • 管线

UVC 与彩色相机

本示例演示如何将 OAK 设备上的 RGB 相机用作 UVC 网络摄像头。UVC 节点允许你在诸如 OpenCV 的 cv2.VideoCapture()、原生相机应用等场景中将 OAK 设备用作普通网络摄像头。

类似示例:

设置

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

用于测试的代码

Python
1import cv2
2
3# 初始化 VideoCapture 对象以使用默认相机(相机索引 0 为网络摄像头)
4cap = cv2.VideoCapture(1)
5
6# 检查相机是否成功打开
7if not cap.isOpened():
8    print("错误:无法打开相机。")
9    exit()
10
11# 循环持续获取相机帧
12while True:
13    ret, frame = cap.read()
14
15    if not ret:
16        print("错误:无法读取帧。")
17        break
18
19    cv2.imshow('视频流', frame)
20
21    if cv2.waitKey(1) & 0xFF == ord('q'):
22        break
23
24cap.release()
25cv2.destroyAllWindows()

源代码

Python

Python
GitHub
1#!/usr/bin/env python3
2
3import time
4import argparse
5
6parser = argparse.ArgumentParser()
7parser.add_argument('-fb', '--flash-bootloader', default=False, action="store_true")
8parser.add_argument('-f',  '--flash-app',        default=False, action="store_true")
9parser.add_argument('-l',  '--load-and-exit',    default=False, action="store_true")
10args = parser.parse_args()
11
12if args.load_and_exit:
13    import os
14    # Disabling device watchdog, so it doesn't need the host to ping periodically.
15    # Note: this is done before importing `depthai`
16    os.environ["DEPTHAI_WATCHDOG"] = "0"
17
18import depthai as dai
19
20def getPipeline():
21    enable_4k = False  # Will downscale 4K -> 1080p
22
23    pipeline = dai.Pipeline()
24
25    # Define a source - color camera
26    cam_rgb = pipeline.createColorCamera()
27    cam_rgb.setBoardSocket(dai.CameraBoardSocket.CAM_A)
28    cam_rgb.setInterleaved(False)
29    #cam_rgb.initialControl.setManualFocus(130)
30
31    if enable_4k:
32        cam_rgb.setResolution(dai.ColorCameraProperties.SensorResolution.THE_4_K)
33        cam_rgb.setIspScale(1, 2)
34    else:
35        cam_rgb.setResolution(dai.ColorCameraProperties.SensorResolution.THE_1080_P)
36
37    # Create an UVC (USB Video Class) output node
38    uvc = pipeline.createUVC()
39    cam_rgb.video.link(uvc.input)
40
41    # Note: if the pipeline is sent later to device (using startPipeline()),
42    # it is important to pass the device config separately when creating the device
43    config = dai.Device.Config()
44    # config.board.uvc = dai.BoardConfig.UVC()  # enable default 1920x1080 NV12
45    config.board.uvc = dai.BoardConfig.UVC(1920, 1080)
46    config.board.uvc.frameType = dai.ImgFrame.Type.NV12
47    # config.board.uvc.cameraName = "My Custom Cam"
48    pipeline.setBoardConfig(config.board)
49
50    return pipeline
51
52# Will flash the bootloader if no pipeline is provided as argument
53def flash(pipeline=None):
54    (f, bl) = dai.DeviceBootloader.getFirstAvailableDevice()
55    bootloader = dai.DeviceBootloader(bl, True)
56
57    # Create a progress callback lambda
58    progress = lambda p : print(f'Flashing progress: {p*100:.1f}%')
59
60    startTime = time.monotonic()
61    if pipeline is None:
62        print("Flashing bootloader...")
63        bootloader.flashBootloader(progress)
64    else:
65        print("Flashing application pipeline...")
66        bootloader.flash(progress, pipeline)
67
68    elapsedTime = round(time.monotonic() - startTime, 2)
69    print("Done in", elapsedTime, "seconds")
70
71if args.flash_bootloader or args.flash_app:
72    if args.flash_bootloader: flash()
73    if args.flash_app: flash(getPipeline())
74    print("Flashing successful. Please power-cycle the device")
75    quit()
76
77if args.load_and_exit:
78    device = dai.Device(getPipeline())
79    print("\nDevice started. Attempting to force-terminate this process...")
80    print("Open an UVC viewer to check the camera stream.")
81    print("To reconnect with depthai, a device power-cycle may be required in some cases")
82    # We do not want the device to be closed, so terminate the process uncleanly.
83    # (TODO add depthai API to be able to cleanly exit without closing device)
84    import signal
85    os.kill(os.getpid(), signal.SIGTERM)
86
87# Standard UVC load with depthai
88with dai.Device(getPipeline()) as device:
89    print("\nDevice started, please keep this process running")
90    print("and open an UVC viewer to check the camera stream.")
91    print("\nTo close: Ctrl+C")
92
93    # Doing nothing here, just keeping the host feeding the watchdog
94    while True:
95        try:
96            time.sleep(0.1)
97        except KeyboardInterrupt:
98            break

管线

需要帮助?

请前往 OAKChina 官网 获取技术支持或解答您的任何疑问。