Gradio 月活用户突破 100 万!

阅读更多
Gradio logo
  1. 流媒体
  2. 使用 WebRTC 从网络摄像头进行对象检测

使用 WebRTC 从网络摄像头流进行实时对象检测

在本指南中,我们将使用 YOLOv10 在 Gradio 中从用户的网络摄像头feed进行实时对象检测。我们将使用 Gradio 5.0 中引入的最新流媒体功能。你可以在下面看到最终产品的实际效果

设置

首先安装所有依赖项。将以下行添加到 requirements.txt 文件并运行 pip install -r requirements.txt

opencv-python
twilio
gradio>=5.0
gradio-webrtc
onnxruntime-gpu

我们将使用 ONNX 运行时来加速 YOLOv10 推理。本指南假设你可以访问 GPU。如果没有,请将 onnxruntime-gpu 更改为 onnxruntime。没有 GPU,模型运行速度会较慢,导致演示出现延迟。

我们将使用 OpenCV 进行图像处理,并使用 Gradio WebRTC 自定义组件在底层使用 WebRTC,实现近乎零延迟。

注意:如果你想在任何云提供商上部署此应用,你需要使用 Twilio API 的免费 TURN 服务器。在 Twilio 上创建一个免费帐户。如果你不熟悉 TURN 服务器,请查阅此指南

推理函数

我们将从 Hugging Face Hub 下载 YOLOv10 模型,并实例化一个自定义推理类来使用此模型。

本指南未涵盖推理类的实现,但如果你有兴趣,可以在此处找到源代码。此实现大量借鉴了这个github 仓库

我们使用 yolov10-n 变体是因为它具有最低的延迟。请参阅 YOLOv10 GitHub 仓库中 README 的性能部分。

from huggingface_hub import hf_hub_download
from inference import YOLOv10

model_file = hf_hub_download(
    repo_id="onnx-community/yolov10n", filename="onnx/model.onnx"
)

model = YOLOv10(model_file)

def detection(image, conf_threshold=0.3):
    image = cv2.resize(image, (model.input_width, model.input_height))
    new_image = model.detect_objects(image, conf_threshold)
    return new_image

我们的推理函数 detection 接受来自网络摄像头的 numpy 数组和所需的置信度阈值。像 YOLO 这样的对象检测模型识别许多对象,并为每个对象分配一个置信度分数。置信度越低,误报的可能性就越高。我们将允许用户调整置信度阈值。

该函数返回一个 numpy 数组,对应于相同的输入图像,其中所有检测到的对象都带有边界框。

Gradio 演示

Gradio 演示非常简单,但我们将实现一些特定功能

  1. 使用 WebRTC 自定义组件以确保输入和输出通过 WebRTC 发送到/从服务器发送。
  2. WebRTC 组件将同时作为输入和输出组件。
  3. 利用 stream 事件的 time_limit 参数。此参数设置每个用户流的处理时间。在多用户设置中(例如在 Spaces 上),在此时间段后,我们将停止处理当前用户的流,然后继续处理下一个用户。

我们还将应用自定义 CSS 将网络摄像头和滑块居中放置在页面上。

import gradio as gr
from gradio_webrtc import WebRTC

css = """.my-group {max-width: 600px !important; max-height: 600px !important;}
         .my-column {display: flex !important; justify-content: center !important; align-items: center !important;}"""

with gr.Blocks(css=css) as demo:
    gr.HTML(
        """
        <h1 style='text-align: center'>
        YOLOv10 Webcam Stream (Powered by WebRTC ⚡️)
        </h1>
        """
    )
    with gr.Column(elem_classes=["my-column"]):
        with gr.Group(elem_classes=["my-group"]):
            image = WebRTC(label="Stream", rtc_configuration=rtc_configuration)
            conf_threshold = gr.Slider(
                label="Confidence Threshold",
                minimum=0.0,
                maximum=1.0,
                step=0.05,
                value=0.30,
            )

        image.stream(
            fn=detection, inputs=[image, conf_threshold], outputs=[image], time_limit=10
        )

if __name__ == "__main__":
    demo.launch()

结论

我们的应用托管在 Hugging Face Spaces 上,点击此处查看。

你可以使用此应用作为起点,使用 Gradio 构建实时图像应用。如果你有任何问题或遇到问题,请随时在 space 或 WebRTC 组件 GitHub 仓库中提出 issue。