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

这个是使用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

后端实现代码:

复制代码
from flask import Flask, render_template, request, redirect, url_for, session, flash, Response, jsonify
import os
from functools import wraps
from ultralytics import YOLO
import cv2
import numpy as np
import base64
import json

app = Flask(__name__)
app.secret_key = 'your_secret_key'  # 设置密钥用于session

# 初始化YOLOv8模型
model = YOLO('yolov8n.pt')  # 或使用其他版本如 yolov8s.pt, yolov8m.pt

# 登录验证装饰器
def login_required(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        if 'logged_in' not in session:
            return redirect(url_for('login'))
        return f(*args, **kwargs)
    return decorated_function

# 登录路由
@app.route('/', methods=['GET', 'POST'])
@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        
        if username == 'admin' and password == 'admin':
            session['logged_in'] = True
            return redirect(url_for('detection'))
        else:
            flash('Invalid username or password!')
            
    return render_template('login.html')

# 目标检测路由
@app.route('/detection')
@login_required
def detection():
    return render_template('detection.html')

@app.route('/detect', methods=['POST'])
@login_required
def detect():
    try:
        data = request.json
        image_data = data['image'].split(',')[1]
        confidence = float(data['confidence'])
        iou = float(data['iou'])
        
        # 解码base64图像
        image_bytes = base64.b64decode(image_data)
        nparr = np.frombuffer(image_bytes, np.uint8)
        image = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
        
        # 运行检测
        results = model(image, conf=confidence, iou=iou)[0]
        
        # 在图像上绘制检测结果
        for box in results.boxes:
            x1, y1, x2, y2 = map(int, box.xyxy[0])
            conf = float(box.conf[0])
            cls = int(box.cls[0])
            label = f'{results.names[cls]} {conf:.2f}'
            
            cv2.rectangle(image, (x1, y1), (x2, y2), (0, 255, 0), 2)
            cv2.putText(image, label, (x1, y1 - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)
        
        # 将结果图像转换为base64
        _, buffer = cv2.imencode('.jpg', image)
        image_base64 = base64.b64encode(buffer).decode('utf-8')
        
        return jsonify({
            'success': True,
            'image': f'data:image/jpeg;base64,{image_base64}'
        })
        
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        })

@app.route('/detect_video_frame', methods=['POST'])
@login_required
def detect_video_frame():
    # 类似于detect路由,但专门处理视频帧
    # ... implementation similar to detect route ...
    pass

if __name__ == '__main__':
    app.run(debug=True)

登录界面:

目标检测界面:

相关推荐
傻啦嘿哟3 小时前
某招聘平台爬虫:爬取招聘岗位数据,分析各城市薪资水平
开发语言·爬虫·python
2501_933670793 小时前
2026秋招量化分析岗技能栈:Python、SQL、统计建模、回测项目怎么准备
开发语言·python·sql
2601_962077603 小时前
python Dejavu库快速识别音频指纹实例探究
python·音乐识别·dejavu库·音频指纹识别·实例探究
科技苑4 小时前
如何用Python编程实现一个简单的Web爬虫?
人工智能·python
dayDayupbetter4 小时前
Visual C++ 2010安装与使用高手秘籍
python
隐擎fox4 小时前
深入理解网络传输层安全:TLS 指纹识别(JA3/JA4)原理与 Python 协议层检测实战
爬虫·python·网络协议·安全·网络安全·https
医疗信息化王工4 小时前
DataForge:基于 Python 的数据库批量导出 Excel 工具——从架构到部署的全流程实战
数据库·python·excel
小玮看世界5 小时前
[Python]从合并区间到传感器融合区:合并区间在传感器区域融合的实际落地
开发语言·python
Java陈序员6 小时前
轻量运维面板!一款现代化的服务器控制面板工具!
运维·服务器·python·react.js·github
2601_962097366 小时前
1. 使用 C 或 C++ 扩展 Python
python·api·c·引用计数·扩展模块