Adamfan/objectdetection
0
1from fastai.vision.all import *2from io import BytesIO3import requests4import streamlit as st5 6import numpy as np7import torch8import cv29from numpy import random10import os11import sys12 13# 避免模型監聽錯誤14os.environ["STREAMLIT_PREVENT_RUN_ON_SAVE"] = "true"15os.environ["STREAMLIT_WATCHDOG_MODE"] = "none"16os.environ["PYTORCH_NO_OPENCV"] = "1"17 18# 加入 YOLOv7 路徑19sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))20 21from models.experimental import attempt_load22from utils.general import check_img_size, set_logging, non_max_suppression, scale_coords23from utils.plots import plot_one_box24 25# 初始化裝置26set_logging()27device = torch.device("cuda" if torch.cuda.is_available() else "cpu")28 29# Resize and pad image30def letterbox(img, new_shape=(640, 640), color=(114, 114, 114), auto=True, scaleFill=False, scaleup=True, stride=32):31 shape = img.shape[:2] # [height, width]32 if isinstance(new_shape, int):33 new_shape = (new_shape, new_shape)34 35 r = min(new_shape[0] / shape[0], new_shape[1] / shape[1])36 if not scaleup:37 r = min(r, 1.0)38 39 ratio = r, r40 new_unpad = int(round(shape[1] * r)), int(round(shape[0] * r))41 dw, dh = new_shape[1] - new_unpad[0], new_shape[0] - new_unpad[1]42 if auto:43 dw, dh = np.mod(dw, stride), np.mod(dh, stride)44 elif scaleFill:45 dw, dh = 0.0, 0.046 new_unpad = (new_shape[1], new_shape[0])47 ratio = new_shape[1] / shape[1], new_shape[0] / shape[0]48 49 dw /= 250 dh /= 251 52 if shape[::-1] != new_unpad:53 img = cv2.resize(img, new_unpad, interpolation=cv2.INTER_LINEAR)54 top, bottom = int(round(dh - 0.1)), int(round(dh + 0.1))55 left, right = int(round(dw - 0.1)), int(round(dw + 0.1))56 img = cv2.copyMakeBorder(img, top, bottom, left, right, cv2.BORDER_CONSTANT, value=color)57 return img, ratio, (dw, dh)58 59# 預測函式60def detect_modify(img0, model, conf=0.4, imgsz=640, conf_thres=0.25, iou_thres=0.45):61 st.image(img0, caption="原始圖片", use_column_width=True)62 63 # 確保圖像格式正確64 img0 = np.array(img0)65 if img0.ndim == 2:66 img0 = cv2.cvtColor(img0, cv2.COLOR_GRAY2RGB)67 img0 = cv2.cvtColor(img0, cv2.COLOR_RGB2BGR)68 69 stride = int(model.stride.max())70 imgsz = check_img_size(imgsz, s=stride)71 img = letterbox(img0, imgsz, stride=stride)[0]72 73 img = img[:, :, ::-1].transpose(2, 0, 1)74 img = np.ascontiguousarray(img)75 img = torch.from_numpy(img).to(device).float() / 255.076 77 if img.ndimension() == 3:78 img = img.unsqueeze(0)79 80 names = model.module.names if hasattr(model, 'module') else model.names81 colors = [[random.randint(0, 255) for _ in range(3)] for _ in names]82 83 with torch.no_grad():84 pred = model(img)[0]85 pred = non_max_suppression(pred, conf_thres, iou_thres)86 87 det = pred[0]88 if len(det):89 det[:, :4] = scale_coords(img.shape[2:], det[:, :4], img0.shape).round()90 for *xyxy, conf, cls in reversed(det):91 label = f'{names[int(cls)]} {conf:.2f}'92 plot_one_box(xyxy, img0, label=label, color=colors[int(cls)], line_thickness=2)93 94 st.markdown("### 偵測結果:")95 st.image(Image.fromarray(cv2.cvtColor(img0, cv2.COLOR_BGR2RGB)), use_column_width=True)96 97# 模型載入與快取98@st.cache_resource99def load_model():100 current_dir = os.path.dirname(os.path.abspath(__file__))101 weight_path = os.path.join(current_dir, 'best.pt')102 model = attempt_load(weight_path, map_location=device)103 model.eval()104 return model105 106# Streamlit UI 主程式107def main():108 st.title("🧠 YOLOv7 物件偵測 Web 應用")109 st.write("請選擇圖片來源並進行偵測")110 111 model = load_model()112 113 option = st.radio("選擇輸入方式:", ["上傳圖片", "圖片 URL"])114 115 imgsz = 640116 conf = 0.4117 conf_thres = 0.25118 iou_thres = 0.45119 120 if option == "上傳圖片":121 uploaded_file = st.file_uploader("請上傳圖片", type=["jpg", "png", "jpeg"])122 if uploaded_file is not None:123 img = PILImage.create(uploaded_file)124 detect_modify(img, model, conf=conf, imgsz=imgsz, conf_thres=conf_thres, iou_thres=iou_thres)125 126 else:127 url = st.text_input("請輸入圖片 URL:")128 if url:129 try:130 response = requests.get(url)131 img = PILImage.create(BytesIO(response.content))132 detect_modify(img, model, conf=conf, imgsz=imgsz, conf_thres=conf_thres, iou_thres=iou_thres)133 except Exception as e:134 st.error(f"讀取圖片失敗:{e}")135 136if __name__ == "__main__":137 main()138 