使用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)

登录界面:

目标检测界面:

相关推荐
XW01059993 分钟前
6-函数-1 使用函数求特殊a串数列和
数据结构·python·算法
m0_5698814710 分钟前
使用Python进行网络设备自动配置
jvm·数据库·python
波诺波14 分钟前
项目pid-control-simulation-main 中的 main.py 代码讲解
开发语言·python
no_work26 分钟前
yolo摄像头下的目标检测识别集合
人工智能·深度学习·yolo·目标检测·计算机视觉
巧妹儿37 分钟前
Python 配置管理封神技:pydantic_settings+@lru_cache,支持优先级,安全又高效,杜绝重复加载!
开发语言·python·ai·配置管理
独隅41 分钟前
Python AI 全面使用指南:从数据基石到智能决策
开发语言·人工智能·python
胡耀超1 小时前
Web Crawling 网络爬虫全景:技术体系、反爬对抗与全链路成本分析
前端·爬虫·python·网络爬虫·数据采集·逆向工程·反爬虫
小陈的进阶之路1 小时前
Selenium元素定位
python·selenium
李昊哲小课1 小时前
matplotlib多子图与复杂布局实战
python·数据分析·matplotlib·数据可视化