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)