Spaces:
Sleeping
Sleeping
import gradio as gr | |
import cv2 | |
import numpy as np | |
from ultralytics import YOLO | |
from importlib.metadata import version | |
# 动态组件选择 | |
GRADIO_VERSION = version("gradio") | |
if int(GRADIO_VERSION.split('.')[0]) >= 4 and int(GRADIO_VERSION.split('.')[1]) >= 12: | |
Webcam = gr.Webcam | |
else: | |
class Webcam(gr.Image): | |
def __init__(self, **kwargs): | |
kwargs.update(source="webcam", streaming=True) | |
super().__init__(**kwargs) | |
# YOLO模型初始化 | |
model = None | |
def load_model(model_file): | |
global model | |
model = YOLO(model_file.name) | |
return "✅ 模型加载成功" | |
with gr.Blocks() as demo: | |
with gr.Tab("📷 实时检测"): | |
webcam = Webcam(label="摄像头") | |
output = gr.Image() | |
webcam.stream( | |
fn=lambda x: model.predict(x)[0].plot(), | |
inputs=webcam, | |
outputs=output | |
) | |
if __name__ == "__main__": | |
demo.launch() |