Gradio Agents & MCP 黑客马拉松
获奖者Gradio Agents & MCP 黑客马拉松
获奖者在本指南中,我们将使用 YOLOv10 在 Gradio 中通过用户网络摄像头实时进行目标检测。我们将利用 Gradio 5.0 中引入的最新流媒体功能。你可以在下方看到成品演示效果。
首先安装所有依赖项。将以下行添加到 requirements.txt
文件中,然后运行 pip install -r requirements.txt
opencv-python
twilio
gradio>=5.0
gradio-webrtc
onnxruntime-gpu
我们将使用 ONNX runtime 来加速 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 演示非常简单,但我们将实现一些特定功能:
WebRTC
自定义组件确保输入和输出通过 WebRTC 发送到/从服务器。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 构建实时图像应用。如果你有任何问题或遇到问题,请随时在 Spaces 或 WebRTC 组件 GitHub 仓库中提交问题。