Spaces:
Sleeping
Sleeping
import gradio as gr | |
from ultralytics import YOLO | |
from fastapi import FastAPI, File, UploadFile | |
from PIL import Image | |
import numpy as np | |
import io | |
# 初始化 FastAPI 和模型 | |
app = FastAPI() | |
model = YOLO('NailongKiller.yolo11n.pt') | |
def predict(img): | |
results = model.predict(img) | |
return results[0].plot() | |
# Gradio 界面 | |
demo = gr.Interface( | |
predict, | |
inputs=[ | |
gr.Image(label="输入图片") | |
], | |
outputs=[ | |
gr.Image(label="检测结果", type="numpy") | |
], | |
title="🐉 奶龙杀手 (NailongKiller)", | |
description="上传图片来检测奶龙 | Upload an image to detect Nailong", | |
examples=[ | |
["example1.jpg"] | |
], | |
cache_examples=True | |
) | |
# API 端点 | |
async def detect_api(file: UploadFile = File(...)): | |
# 读取上传的图片 | |
contents = await file.read() | |
image = Image.open(io.BytesIO(contents)) | |
image_np = np.array(image) | |
# 运行推理 | |
results = model.predict(image_np) | |
result = results[0] | |
# 返回检测结果 | |
detections = [] | |
for box in result.boxes: | |
detection = { | |
"bbox": box.xyxy[0].tolist(), | |
"confidence": float(box.conf[0]), | |
"class": int(box.cls[0]) | |
} | |
detections.append(detection) | |
return {"detections": detections} | |
# 挂载 Gradio 到 FastAPI | |
app = gr.mount_gradio_app(app, demo, path="/") | |
# 启动应用 | |
if __name__ == "__main__": | |
import uvicorn | |
uvicorn.run(app, host="0.0.0.0", port=7860) |