Spaces:
No application file

Test2 / app.py
marcoTest's picture
Create app.py
fb72db6 verified
Raw History Blame Contribute Delete
6.11 kB
import streamlit as st
import cv2
import numpy as np
from PIL import Image
import tempfile
import os
# 頁面設定
st.set_page_config(
page_title="水母偵測系統",
page_icon="🪼",
layout="centered"
)
# 標題
st.title("🪼 水母偵測系統")
st.markdown("使用 YOLOv8 模型偵測水母")
# 嘗試載入模型(使用延遲載入)
@st.cache_resource
def load_model():
try:
from ultralytics import YOLO
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', '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 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)
# 顯示結果
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').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 模型進行物件偵測教學")