Spaces:
Build error
Build error
Delete app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111import gradio as grimport cv2import numpy as npfrom ultralytics import YOLOimport tempfile
# 載入模型model = YOLO("best.pt")
def predict(input_data, input_type): """根據輸入類型進行預測""" if input_data is None: return None # 如果是檔案路徑(影片或圖片) if isinstance(input_data, str): if input_type == "video": # 處理影片 cap = cv2.VideoCapture(input_data) 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() # 儲存處理後的影片 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 else: # 處理圖片 image = cv2.imread(input_data) image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) else: # 處理 numpy 陣列(來自攝影機或上傳) image = input_data # 圖片偵測 results = model(image) for result in results: for box in result.boxes: x1, y1, x2, y2 = map(int, box.xyxy[0]) conf = float(box.conf[0]) label = f"Jellyfish {conf:.2f}" cv2.rectangle(image, (x1, y1), (x2, y2), (0, 255, 0), 3) cv2.putText(image, label, (x1, y1-10), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2) return image
# 創建 Gradio 介面with gr.Blocks() as demo: gr.Markdown("# 🪼 水母偵測系統 (YOLOv8)") gr.Markdown("使用 YOLOv8 模型偵測水母,支援攝影機、圖片和影片") with gr.Tab("📷 即時攝影機"): gr.Markdown("### 點擊下方按鈕啟用攝影機") with gr.Row(): webcam = gr.Webcam(label="網路攝影機", source="webcam") webcam_output = gr.Image(label="偵測結果") def process_webcam(img): return predict(img, "image") webcam.change(process_webcam, webcam, webcam_output) with gr.Tab("📁 上傳圖片"): gr.Markdown("### 上傳包含水母的圖片") with gr.Row(): img_input = gr.Image(label="選擇圖片", type="filepath") img_output = gr.Image(label="偵測結果") def process_image(img): return predict(img, "image") img_input.change(process_image, img_input, img_output) with gr.Tab("📹 上傳影片"): gr.Markdown("### 上傳水母影片檔案 (MP4, AVI等)") with gr.Row(): video_input = gr.Video(label="選擇影片") video_output = gr.Video(label="處理結果") def process_video(video): return predict(video, "video") video_input.change(process_video, video_input, video_output)
# 啟動應用if __name__ == "__main__": demo.launch(debug=True)app.pyDeleted-111