Update app.py
Browse files1 unmodified line23455677891011121314915161718192021222312242526272829303132333416173536373839404142202122232425262728294344454647484950515253545556575859603132333435363738394041424344456162636465666768697071727374757677787980818283848586878889474849909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761 unmodified lineimport cv2import numpy as npfrom PIL import Imagefrom ultralytics import YOLOimport tempfileimport os
st.title("🪼 水母偵測器")# 頁面設定st.set_page_config( page_title="水母偵測系統", page_icon="🪼", layout="centered")
# 載入模型# 標題st.title("🪼 水母偵測系統")st.markdown("使用 YOLOv8 模型偵測水母")
# 嘗試載入模型(使用延遲載入)@st.cache_resourcedef load_model(): try: from ultralytics import YOLO return YOLO("best.pt") return YOLO("best.pt") except Exception as e: st.error(f"載入模型失敗: {e}") return None
model = load_model()
if model is None: st.warning("無法載入模型,請確認 best.pt 檔案存在") st.stop()
# 上傳圖片uploaded_file = st.file_uploader("上傳水母圖片", type=['jpg', 'png', 'jpeg'])# 上傳檔案uploaded_file = st.file_uploader( "上傳水母圖片或影片", type=['jpg', 'jpeg', 'png', 'mp4', 'avi', 'mov'], help="支援 JPG, PNG, MP4 格式")
if uploaded_file is not None: # 顯示原始圖片 image = Image.open(uploaded_file) st.image(image, caption="原始圖片", use_column_width=True) # 轉換為 OpenCV 格式 img_array = np.array(image) # 偵測水母 with st.spinner('正在偵測水母...'): results = model(img_array) # 判斷檔案類型 file_ext = uploaded_file.name.lower().split('.')[-1] if file_ext in ['jpg', 'jpeg', 'png']: # 處理圖片 st.subheader("圖片偵測") # 顯示原始圖片 image = Image.open(uploaded_file) st.image(image, caption="原始圖片", use_column_width=True) # 轉換為 numpy array img_array = np.array(image) # 偵測 with st.spinner('正在偵測水母...'): results = model(img_array) # 畫框 count = 0 for result in results: for box in result.boxes: conf = float(box.conf[0]) if conf > 0.5: # 信心值閾值 x1, y1, x2, y2 = map(int, box.xyxy[0]) count += 1 # 畫綠色框 cv2.rectangle(img_array, (x1, y1), (x2, y2), (0, 255, 0), 3) # 標籤 label = f"水母 {conf:.2f}" cv2.putText(img_array, label, (x1, y1-10), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2) # 畫框 count = 0 for result in results: for box in result.boxes: conf = float(box.conf[0]) if conf > 0.5: # 信心值閾值 x1, y1, x2, y2 = map(int, box.xyxy[0]) count += 1 # 畫框 cv2.rectangle(img_array, (x1, y1), (x2, y2), (0, 255, 0), 3) # 標籤 label = f"水母 {conf:.2f}" cv2.putText(img_array, label, (x1, y1-10), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2) # 顯示結果 st.image(img_array, caption=f"偵測結果 ({count} 隻水母)", use_column_width=True) st.success(f"✅ 找到 {count} 隻水母!") # 下載按鈕 _, buffer = cv2.imencode('.jpg', cv2.cvtColor(img_array, cv2.COLOR_RGB2BGR)) st.download_button( label="下載結果圖片", data=buffer.tobytes(), file_name="jellyfish_detected.jpg", mime="image/jpeg" ) # 顯示結果 st.image(img_array, caption=f"偵測結果 ({count} 隻水母)", use_column_width=True) st.success(f"找到 {count} 隻水母!") elif file_ext in ['mp4', 'avi', 'mov']: # 處理影片 st.subheader("影片偵測") st.warning("影片處理較慢,請耐心等待...") # 儲存上傳的影片 tfile = tempfile.NamedTemporaryFile(delete=False, suffix=f'.{file_ext}') tfile.write(uploaded_file.read()) video_path = tfile.name # 顯示原始影片 st.video(video_path) if st.button("開始處理影片", type="primary"): with st.spinner('處理影片中...'): # 讀取影片 cap = cv2.VideoCapture(video_path) fps = int(cap.get(cv2.CAP_PROP_FPS)) width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) # 建立輸出影片 output_path = tempfile.NamedTemporaryFile(delete=False, suffix='.mp4').name fourcc = cv2.VideoWriter_fourcc(*'mp4v') out = cv2.VideoWriter(output_path, fourcc, fps, (width, height)) frame_count = 0 total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) # 進度條 progress_bar = st.progress(0) while True: ret, frame = cap.read() if not ret: break # 每隔5幀處理一次(加快速度) if frame_count % 5 == 0: results = model(frame) for result in results: for box in result.boxes: conf = float(box.conf[0]) if conf > 0.5: x1, y1, x2, y2 = map(int, box.xyxy[0]) cv2.rectangle(frame, (x1, y1), (x2, y2), (0, 255, 0), 3) label = f"Jellyfish {conf:.2f}" cv2.putText(frame, label, (x1, y1-10), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2) out.write(frame) frame_count += 1 # 更新進度 if total_frames > 0: progress_bar.progress(frame_count / total_frames) cap.release() out.release() # 完成 progress_bar.progress(1.0) st.success(f"✅ 完成!處理了 {frame_count} 幀") # 顯示結果影片 st.video(output_path) # 下載按鈕 with open(output_path, 'rb') as f: video_bytes = f.read() st.download_button( label="下載處理後的影片", data=video_bytes, file_name="jellyfish_detected.mp4", mime="video/mp4" ) # 清理暫存檔 os.unlink(video_path) if 'output_path' in locals(): os.unlink(output_path)
# 頁腳st.markdown("---")st.markdown("**教學用途 | 水母偵測系統**")st.markdown("使用 YOLOv8 模型進行物件偵測教學")app.py+161-34