CoolFace
Apppublic

wolf6/GARBAGE

sourceHugging Faceupdated 1y agoView on Hugging Face
0likes
streamlit_app.py161 linesDownload Raw Back to src
1from fastai.vision.all import *2from io import BytesIO3import requests4import streamlit as st5 6import numpy as np7import torch8import time9import cv210from numpy import random11import os12import sys13 14# 加入上層目錄到模組搜尋路徑中15sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))16 17from models.experimental import attempt_load18from utils.general import check_img_size, check_requirements, check_imshow, non_max_suppression, apply_classifier, \19    scale_coords, xyxy2xywh, strip_optimizer, set_logging, increment_path20from utils.plots import plot_one_box21 22def letterbox(img, new_shape=(640, 640), color=(114, 114, 114), auto=True, scaleFill=False, scaleup=True, stride=32):23    # Resize and pad image while meeting stride-multiple constraints24    shape = img.shape[:2]  # current shape [height, width]25    if isinstance(new_shape, int):26        new_shape = (new_shape, new_shape)27 28    # Scale ratio (new / old)29    r = min(new_shape[0] / shape[0], new_shape[1] / shape[1])30    if not scaleup:  # only scale down, do not scale up (for better test mAP)31        r = min(r, 1.0)32 33    # Compute padding34    ratio = r, r  # width, height ratios35    new_unpad = int(round(shape[1] * r)), int(round(shape[0] * r))36    dw, dh = new_shape[1] - new_unpad[0], new_shape[0] - new_unpad[1]  # wh padding37    if auto:  # minimum rectangle38        dw, dh = np.mod(dw, stride), np.mod(dh, stride)  # wh padding39    elif scaleFill:  # stretch40        dw, dh = 0.0, 0.041        new_unpad = (new_shape[1], new_shape[0])42        ratio = new_shape[1] / shape[1], new_shape[0] / shape[0]  # width, height ratios43 44    dw /= 2  # divide padding into 2 sides45    dh /= 246 47    if shape[::-1] != new_unpad:  # resize48        img = cv2.resize(img, new_unpad, interpolation=cv2.INTER_LINEAR)49    top, bottom = int(round(dh - 0.1)), int(round(dh + 0.1))50    left, right = int(round(dw - 0.1)), int(round(dw + 0.1))51    img = cv2.copyMakeBorder(img, top, bottom, left, right, cv2.BORDER_CONSTANT, value=color)  # add border52    return img, ratio, (dw, dh)53 54def detect_modify(img0, model, conf=0.4, imgsz=640, conf_thres = 0.25, iou_thres=0.45):55    st.image(img0, caption="Your image", use_column_width=True)56 57    stride = int(model.stride.max())  # model stride58    imgsz = check_img_size(imgsz, s=stride)  # check img_size59 60    # Padded resize61    img0 = cv2.cvtColor(np.asarray(img0), cv2.COLOR_RGB2BGR)62    img = letterbox(img0, imgsz, stride=stride)[0]63    # Convert64    img = img[:, :, ::-1].transpose(2, 0, 1)  # BGR to RGB, to 3x416x41665    img = np.ascontiguousarray(img)66 67    68    # Get names and colors69    names = model.module.names if hasattr(model, 'module') else model.names70    colors = [[random.randint(0, 255) for _ in range(3)] for _ in names]71 72    # Run inference73    old_img_w = old_img_h = imgsz74    old_img_b = 175 76    t0 = time.time()77    img = torch.from_numpy(img).to(device)78    # img /= 255.0  # 0 - 255 to 0.0 - 1.079    img = img/255.080    if img.ndimension() == 3:81        img = img.unsqueeze(0)82 83    # Inference84    # t1 = time_synchronized()85    with torch.no_grad():   # Calculating gradients would cause a GPU memory leak86        pred = model(img)[0]87    # t2 = time_synchronized()88 89    # Apply NMS90    pred = non_max_suppression(pred, conf_thres, iou_thres)91    # t3 = time_synchronized()92 93    # Process detections94    # for i, det in enumerate(pred):  # detections per image95        96    gn = torch.tensor(img0.shape)[[1, 0, 1, 0]]  # normalization gain whwh97 98    det = pred[0]99    if len(det):100        # Rescale boxes from img_size to im0 size101        det[:, :4] = scale_coords(img.shape[2:], det[:, :4], img0.shape).round()102 103        # Print results104        s = ''105        for c in det[:, -1].unique():106            n = (det[:, -1] == c).sum()  # detections per class107            s += f"{n} {names[int(c)]}{'s' * (n > 1)}, "  # add to string108 109        # Write results110        for *xyxy, conf, cls in reversed(det):111            label = f'{names[int(cls)]} {conf:.2f}'112            plot_one_box(xyxy, img0, label=label, color=colors[int(cls)], line_thickness=1)113 114    f"""115    ### Prediction result:116    """117    img0 = cv2.cvtColor(np.asarray(img0), cv2.COLOR_BGR2RGB)118    st.image(img0, caption="Prediction Result", use_column_width=True)119 120#set paramters121 122# 取得目前檔案 (streamlit_app.py) 所在的目錄123current_dir = os.path.dirname(os.path.abspath(__file__))124 125# 回到根目錄後組合出 .pkl 檔案的路徑126weight_path = os.path.join(current_dir, 'best.pt')127 128imgsz = 640129conf = 0.4130conf_thres = 0.25131iou_thres=0.45132device = torch.device("cpu")133path = "./"134 135# Load model136#model = attempt_load(weight_path, map_location=torch.device('cpu'))  # load FP32 model137ckpt = torch.load(weight_path, map_location=torch.device('cpu'), weights_only=False)138model = ckpt['ema' if ckpt.get('ema') else 'model'].float().fuse().eval()139 140"""141# YOLOv7142This is a object detection model for [Objects].143"""144option = st.radio("", ["Upload Image", "Image URL"])145 146if option == "Upload Image":147    uploaded_file = st.file_uploader("Please upload an image.")148 149    if uploaded_file is not None:150        img = PILImage.create(uploaded_file)151        detect_modify(img, model, conf=conf, imgsz=imgsz, conf_thres=conf_thres, iou_thres=iou_thres)152else:153    url = st.text_input("Please input a url.")154    if url != "":155        try:156            response = requests.get(url)157            pil_img = PILImage.create(BytesIO(response.content))158            detect_modify(pil_img, model, conf=conf, imgsz=imgsz, conf_thres=conf_thres, iou_thres=iou_thres)159        except:160            st.text("Problem reading image from", url)161