后端第一步先建一个项目文件夹。打开你电脑上任意一个地方新建一个文件夹就叫ebike-detection然后把你的best.pt复制进去。第二步安装Flask和相关依赖。打开命令提示符按WinR输入cmd回车然后把下面这行命令复制进去运行pip install flask flask-cors ultralytics pillow好第三步创建Flask后端文件。在你的ebike-detection文件夹里新建一个文件叫app.py把下面的代码完整复制进去pythonfrom flask import Flask, request, jsonify from flask_cors import CORS from ultralytics import YOLO from PIL import Image import io import base64 import datetime app Flask(__name__) CORS(app) # 加载模型把路径改成你的best.pt实际路径 model YOLO(rC:\你的路径\best.pt) detection_history [] app.route(/detect, methods[POST]) def detect(): if image not in request.files: return jsonify({error: 没有收到图片}), 400 file request.files[image] img Image.open(io.BytesIO(file.read())) results model(img) detections [] has_ebike False for result in results: for box in result.boxes: cls_id int(box.cls[0]) cls_name model.names[cls_id] conf float(box.conf[0]) if conf 0.5: detections.append({ class: cls_name, confidence: round(conf, 3) }) if cls_name in [bicycle, motorcycle]: has_ebike True record { time: datetime.datetime.now().strftime(%Y-%m-%d %H:%M:%S), detections: detections, has_ebike: has_ebike, alert: has_ebike } detection_history.insert(0, record) if len(detection_history) 50: detection_history.pop() return jsonify(record) app.route(/history, methods[GET]) def history(): return jsonify(detection_history) app.route(/stats, methods[GET]) def stats(): total len(detection_history) alerts sum(1 for r in detection_history if r[alert]) return jsonify({ total: total, alerts: alerts, safe: total - alerts }) if __name__ __main__: app.run(host0.0.0.0, port5000, debugTrue)注意第8行把路径改成你best.pt的实际路径比如rC:\Users\你的名字\ebike-detection\best.pt。现在运行后端看看能不能跑起来。在命令提示符里先进入你的项目文件夹cd C:\你的ebike-detection文件夹路径然后运行python app.py运行之后你应该会看到类似这样的输出* Running on http://0.0.0.0:5000前端微信小程序