使用yolov8+flask实现精致登录界面+图片视频摄像头检测体系

[复制链接]
发表于 2025-10-14 23:15:38 | 显示全部楼层 |阅读模式
这个是使用flask实现悦目登录界面和友好的检测界面实现yolov8推理和展示,代码仅仅有2个html文件和一个python文件,真正做到了用最轻便的代码实现复杂功能
测试通过环境:
windows x64
anaconda3+python3.8
ultralytics==8.3.81
flask==1.1.2
torch==2.3.0
运行步调: 安装好环境实验python login.py
后端实当代码
  1. from flask import Flask, render_template, request, redirect, url_for, session, flash, Response, jsonify
  2. import os
  3. from functools import wraps
  4. from ultralytics import YOLO
  5. import cv2
  6. import numpy as np
  7. import base64
  8. import json
  9. app = Flask(__name__)
  10. app.secret_key = 'your_secret_key'  # 设置密钥用于session
  11. # 初始化YOLOv8模型
  12. model = YOLO('yolov8n.pt')  # 或使用其他版本如 yolov8s.pt, yolov8m.pt
  13. # 登录验证装饰器
  14. def login_required(f):
  15.     @wraps(f)
  16.     def decorated_function(*args, **kwargs):
  17.         if 'logged_in' not in session:
  18.             return redirect(url_for('login'))
  19.         return f(*args, **kwargs)
  20.     return decorated_function
  21. # 登录路由
  22. @app.route('/', methods=['GET', 'POST'])
  23. @app.route('/login', methods=['GET', 'POST'])
  24. def login():
  25.     if request.method == 'POST':
  26.         username = request.form['username']
  27.         password = request.form['password']
  28.         
  29.         if username == 'admin' and password == 'admin':
  30.             session['logged_in'] = True
  31.             return redirect(url_for('detection'))
  32.         else:
  33.             flash('Invalid username or password!')
  34.             
  35.     return render_template('login.html')
  36. # 目标检测路由
  37. @app.route('/detection')
  38. @login_required
  39. def detection():
  40.     return render_template('detection.html')
  41. @app.route('/detect', methods=['POST'])
  42. @login_required
  43. def detect():
  44.     try:
  45.         data = request.json
  46.         image_data = data['image'].split(',')[1]
  47.         confidence = float(data['confidence'])
  48.         iou = float(data['iou'])
  49.         
  50.         # 解码base64图像
  51.         image_bytes = base64.b64decode(image_data)
  52.         nparr = np.frombuffer(image_bytes, np.uint8)
  53.         image = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
  54.         
  55.         # 运行检测
  56.         results = model(image, conf=confidence, iou=iou)[0]
  57.         
  58.         # 在图像上绘制检测结果
  59.         for box in results.boxes:
  60.             x1, y1, x2, y2 = map(int, box.xyxy[0])
  61.             conf = float(box.conf[0])
  62.             cls = int(box.cls[0])
  63.             label = f'{results.names[cls]} {conf:.2f}'
  64.             
  65.             cv2.rectangle(image, (x1, y1), (x2, y2), (0, 255, 0), 2)
  66.             cv2.putText(image, label, (x1, y1 - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)
  67.         
  68.         # 将结果图像转换为base64
  69.         _, buffer = cv2.imencode('.jpg', image)
  70.         image_base64 = base64.b64encode(buffer).decode('utf-8')
  71.         
  72.         return jsonify({
  73.             'success': True,
  74.             'image': f'data:image/jpeg;base64,{image_base64}'
  75.         })
  76.         
  77.     except Exception as e:
  78.         return jsonify({
  79.             'success': False,
  80.             'error': str(e)
  81.         })
  82. @app.route('/detect_video_frame', methods=['POST'])
  83. @login_required
  84. def detect_video_frame():
  85.     # 类似于detect路由,但专门处理视频帧
  86.     # ... implementation similar to detect route ...
  87.     pass
  88. if __name__ == '__main__':
  89.     app.run(debug=True)
复制代码
登录界面:

目标检测界面:



免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

×
回复

使用道具 举报

登录后关闭弹窗

登录参与点评抽奖  加入IT实名职场社区
去登录
快速回复 返回顶部 返回列表