import gradio as gr from ultralytics import YOLO import cv2 import numpy as np from PIL import Image model = YOLO("best0715.pt") def detect(image, conf_threshold=0.3): results = model(image, conf=conf_threshold) if len(results) == 0 or results[0].boxes is None or len(results[0].boxes) == 0: return image, "No bear detected." # 先取得帶有標註的圖片(此時是 BGR 格式) plotted = results[0].plot() # 這是 numpy array,BGR 格式 # 手動轉成 RGB(因為 Gradio 和 PIL 顯示需要 RGB) plotted_rgb = cv2.cvtColor(plotted, cv2.COLOR_BGR2RGB) # 取得最高信心度的分數 conf = results[0].boxes.conf[0].item() return Image.fromarray(plotted_rgb), f"Detected bear with confidence {conf:.2f}" iface = gr.Interface( fn=detect, inputs=[gr.Image(type="pil"), gr.Slider(0.1, 0.9, value=0.3, label="Confidence Threshold")], outputs=[gr.Image(type="pil"), gr.Textbox(label="Detection Result")], title="Taiwanese Black Bear Detector", description="Upload an image for detection." ) iface.launch(share=True)