后端
第一步,先建一个项目文件夹。
打开你电脑上任意一个地方,新建一个文件夹,就叫 ebike-detection,然后把你的 best.pt 复制进去。
第二步,安装Flask和相关依赖。
打开命令提示符(按 Win+R,输入 cmd,回车),然后把下面这行命令复制进去运行:
pip install flask flask-cors ultralytics pillow
好,第三步,创建Flask后端文件。
在你的 ebike-detection 文件夹里,新建一个文件叫 app.py,把下面的代码完整复制进去:
python
1from flask import Flask, request, jsonify 2from flask_cors import CORS 3from ultralytics import YOLO 4from PIL import Image 5import io 6import base64 7import datetime 8 9app = Flask(__name__) 10CORS(app) 11 12# 加载模型,把路径改成你的best.pt实际路径 13model = YOLO(r"C:\你的路径\best.pt") 14 15detection_history = [] 16 17@app.route('/detect', methods=['POST']) 18def detect(): 19 if 'image' not in request.files: 20 return jsonify({'error': '没有收到图片'}), 400 21 22 file = request.files['image'] 23 img = Image.open(io.BytesIO(file.read())) 24 25 results = model(img) 26 27 detections = [] 28 has_ebike = False 29 30 for result in results: 31 for box in result.boxes: 32 cls_id = int(box.cls[0]) 33 cls_name = model.names[cls_id] 34 conf = float(box.conf[0]) 35 36 if conf > 0.5: 37 detections.append({ 38 'class': cls_name, 39 'confidence': round(conf, 3) 40 }) 41 if cls_name in ['bicycle', 'motorcycle']: 42 has_ebike = True 43 44 record = { 45 'time': datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'), 46 'detections': detections, 47 'has_ebike': has_ebike, 48 'alert': has_ebike 49 } 50 detection_history.insert(0, record) 51 if len(detection_history) > 50: 52 detection_history.pop() 53 54 return jsonify(record) 55 56@app.route('/history', methods=['GET']) 57def history(): 58 return jsonify(detection_history) 59 60@app.route('/stats', methods=['GET']) 61def stats(): 62 total = len(detection_history) 63 alerts = sum(1 for r in detection_history if r['alert']) 64 return jsonify({ 65 'total': total, 66 'alerts': alerts, 67 'safe': total - alerts 68 }) 69 70if __name__ == '__main__': 71 app.run(host='0.0.0.0', port=5000, debug=True)
注意: 第8行把路径改成你 best.pt 的实际路径,比如 r"C:\Users\你的名字\ebike-detection\best.pt"。
现在运行后端,看看能不能跑起来。
在命令提示符里,先进入你的项目文件夹:
cd C:\你的ebike-detection文件夹路径
然后运行:
python app.py
运行之后你应该会看到类似这样的输出:
* Running on http://0.0.0.0:5000
前端(微信小程序)
《【毕设】前后端(无模型训练)》 是转载文章,点击查看原文。

