這個是使用flask實現好看登錄界面和友好的檢測界面實現yolov11推理和展示,代碼僅僅有2個html文件和一個python文件,真正做到了用最簡潔的代碼實現復雜功能。
測試通過環境:
windows x64
anaconda3+python3.8
ultralytics==8.3.81
flask==1.1.2
torch==2.3.0
運行步驟: 安裝好環境執行python main.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 jsonapp = Flask(__name__)
app.secret_key = 'your_secret_key' # 設置密鑰用于session# 初始化YOLO11模型
model = YOLO('yolo11n.pt') # 或使用其他版本如 yolo11s.pt, yolo11m.pt
#熱啟動
model(np.zeros((300, 300, 3), np.uint8))# 登錄驗證裝飾器
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'] = Truereturn 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.jsonimage_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 ...passif __name__ == '__main__':app.run(debug=True)
登錄界面:
目標檢測界面:
?