File size: 6,105 Bytes
fb72db6 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 | 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 模型進行物件偵測教學") |