File size: 2,391 Bytes
8d9f842
 
 
 
 
 
 
 
ec8af24
8d9f842
 
 
 
 
 
 
 
0f3261d
62dca66
0f3261d
62dca66
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8d9f842
e9671ed
 
 
 
 
 
 
 
 
 
 
0f3261d
e9671ed
 
 
 
 
 
0f3261d
8d9f842
 
 
 
 
 
 
 
 
 
 
 
 
0f3261d
 
 
8d9f842
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
import gradio as gr
from ultralytics import YOLO
import torch
import cv2
import numpy as np
from fastapi import FastAPI, File, UploadFile
from PIL import Image
import io
import os

# 初始化 FastAPI
app = FastAPI()

# 加载模型
model = YOLO("NailongKiller.yolo11n.pt")

def detect_objects(image):
    if image is None:
        return None, "No image provided"
    
    try:
        # 运行推理
        results = model(image)
        result = results[0]
        
        # 在图像上绘制检测框
        annotated_image = result.plot()
        annotated_image = cv2.cvtColor(annotated_image, cv2.COLOR_BGR2RGB)
        
        # 获取检测结果统计
        num_detections = len(result.boxes)
        detection_info = f"检测到 {num_detections} 个目标"
        
        return annotated_image, detection_info
    except Exception as e:
        return None, f"Error: {str(e)}"

# 创建Gradio界面
demo = gr.Interface(
    fn=detect_objects,
    inputs=gr.Image(type="numpy", label="输入图片 | Input Image"),
    outputs=[
        gr.Image(type="numpy", label="检测结果 | Detection Result"),
        gr.Textbox(label="检测信息 | Detection Info")
    ],
    title="🐉 奶龙杀手 (NailongKiller)",
    description="""
    这是一个基于 YOLO 的奶龙检测系统。上传图片即可自动检测图中的奶龙。
    
    This is a YOLO-based Nailong detection system. Upload an image to detect Nailong automatically.
    """,
    theme=gr.themes.Default(),
    allow_flagging="never",
    examples=["example1.jpg", "example2.jpg"] if all(os.path.exists(f) for f in ["example1.jpg", "example2.jpg"]) else None
)

# API端点
@app.post("/detect/")
async def detect_api(file: UploadFile = File(...)):
    contents = await file.read()
    image = Image.open(io.BytesIO(contents))
    image_np = np.array(image)
    
    results = model(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)