Update app.py
Browse files1 unmodified line23456789101112131415161718192021222324252627282930313233343536373839404142434445464748491 unmodified lineimport cv2import numpy as npfrom PIL import Imagefrom ultralytics import YOLOst.title("🪼 水母偵測器")# 載入模型@st.cache_resourcedef load_model():return YOLO("best.pt")model = load_model()# 上傳圖片uploaded_file = st.file_uploader("上傳水母圖片", type=['jpg', 'png', 'jpeg'])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)# 畫框count = 0for 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} 隻水母!")1 unmodified line234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761 unmodified lineimport cv2import numpy as npfrom PIL import Imageimport tempfileimport os# 頁面設定st.set_page_config(page_title="水母偵測系統",page_icon="🪼",layout="centered")# 標題st.title("🪼 水母偵測系統")st.markdown("使用 YOLOv8 模型偵測水母")# 嘗試載入模型(使用延遲載入)@st.cache_resourcedef load_model():try:from ultralytics import YOLOreturn YOLO("best.pt")except Exception as e:st.error(f"載入模型失敗: {e}")return Nonemodel = load_model()if model is None:st.warning("無法載入模型,請確認 best.pt 檔案存在")st.stop()# 上傳檔案uploaded_file = st.file_uploader("上傳水母圖片或影片",type=['jpg', 'jpeg', 'png', 'mp4', 'avi', 'mov'],help="支援 JPG, PNG, MP4 格式")if uploaded_file is not None:# 判斷檔案類型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 arrayimg_array = np.array(image)# 偵測with st.spinner('正在偵測水母...'):results = model(img_array)# 畫框count = 0for 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")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').namefourcc = cv2.VideoWriter_fourcc(*'mp4v')out = cv2.VideoWriter(output_path, fourcc, fps, (width, height))frame_count = 0total_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