import gradio as gr import cv2 import numpy as np from ultralytics import YOLO import tempfile import os # 載入模型 model = YOLO("best.pt") def predict_image(image): """處理圖片""" if image is None: return None # 轉換格式 if isinstance(image, np.ndarray): img = image else: img = cv2.imread(image) img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) # YOLO偵測 results = model(img) # 畫框 for result in results: for box in result.boxes: x1, y1, x2, y2 = map(int, box.xyxy[0]) conf = float(box.conf[0]) # 畫框 cv2.rectangle(img, (x1, y1), (x2, y2), (0, 255, 0), 3) # 標籤 label = f"Jellyfish {conf:.2f}" cv2.putText(img, label, (x1, y1-10), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2) return img def process_video(video_file): """處理影片""" if video_file is None: return None # 讀取影片 cap = cv2.VideoCapture(video_file) frames = [] # 讀取所有幀 while True: ret, frame = cap.read() if not ret: break # 偵測 results = model(frame) for result in results: for box in result.boxes: x1, y1, x2, y2 = map(int, box.xyxy[0]) conf = float(box.conf[0]) cv2.rectangle(frame, (x1, y1), (x2, y2), (0, 255, 0), 3) cv2.putText(frame, f"Jellyfish {conf:.2f}", (x1, y1-10), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2) frames.append(frame) cap.release() if not frames: return None # 儲存處理後的影片 output_path = tempfile.NamedTemporaryFile(suffix=".mp4", delete=False).name height, width = frames[0].shape[:2] fourcc = cv2.VideoWriter_fourcc(*'mp4v') out = cv2.VideoWriter(output_path, fourcc, 30, (width, height)) for frame in frames: out.write(frame) out.release() return output_path # 更簡單的版本:只做圖片上傳和攝影機輸入 with gr.Blocks() as demo: gr.Markdown("# 🪼 水母偵測系統 (YOLOv8)") gr.Markdown("使用 YOLOv8 模型偵測水母") with gr.Tab("📷 即時攝影機"): gr.Markdown("### 使用電腦攝影機") with gr.Row(): camera_input = gr.Image(source="webcam", streaming=True, label="攝影機畫面") camera_output = gr.Image(label="偵測結果") camera_input.change(predict_image, camera_input, camera_output) with gr.Tab("📁 上傳圖片"): gr.Markdown("### 上傳水母圖片") with gr.Row(): upload_input = gr.Image(label="選擇圖片", type="filepath") upload_output = gr.Image(label="偵測結果") upload_input.change(predict_image, upload_input, upload_output) with gr.Tab("📹 上傳影片"): gr.Markdown("### 上傳水母影片") gr.Markdown("處理需要一些時間,請稍候...") with gr.Row(): video_input = gr.Video(label="選擇影片") video_output = gr.Video(label="處理結果") video_input.change(process_video, video_input, video_output) # 添加說明 gr.Markdown(""" ## 使用說明 1. **攝影機模式**:允許瀏覽器使用攝影機,即可看到即時偵測 2. **圖片模式**:上傳圖片檔案 (JPG/PNG) 3. **影片模式**:上傳影片檔案 (MP4/AVI) ## 模型資訊 - 使用 YOLOv8 自訂訓練模型 - 專門偵測水母 - 教學用途 """) # 啟動 if __name__ == "__main__": demo.launch(debug=True, share=False)