在本指南中,我们将使用 YOLOv10 通过 Gradio 从用户的网络摄像头馈送中执行实时目标检测。我们将使用来自 gradio 团队的配套库 FastRTC 来构建低延迟流式 Web 应用程序。您可以在下面看到完成的产品演示
首先安装所有依赖项。将以下行添加到 `requirements.txt` 文件中,然后运行 `pip install -r requirements.txt`
opencv-python
fastrtc
onnxruntime-gpu我们将使用 ONNX runtime 来加速 YOLOv10 推理。本指南假设您有权访问 GPU。如果没有,请将 `onnxruntime-gpu` 更改为 `onnxruntime`。没有 GPU,模型运行速度会变慢,导致演示延迟。
我们将使用 OpenCV 进行图像处理,并使用 WebRTC 协议来实现接近零的延迟。
注意:如果您想将此应用程序部署到任何云提供商,则需要使用您的 Hugging Face 令牌连接到 TURN 服务器。在此指南中了解更多信息。如果您不熟悉 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 演示非常简单,但我们将实现一些特定功能
我们还将应用自定义 CSS 来将网络摄像头和滑块居中放置在页面上。
import gradio as gr
from fastrtc 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 或 FastRTC GitHub 存储库中提出问题。