1.效果

Flask项目+YOLOv11模型+部署在阿里云服务器上(宝塔控制面板)+uniapp微信小程序

2.有bug代码,但是速度快

有时候会一直返回同一张识别结果图片

import os
import shutil
import numpy as np
import torch.hub
from ultralytics import YOLO
from flask import request, Flask, send_file
import base64
import cv2
import time

directory_path = './runs'
if os.path.exists(directory_path):
    shutil.rmtree(directory_path)

model = YOLO('./best.pt')
app = Flask(__name__)

@app.route('/request', methods=['GET', 'POST'])
def uploads():
    img = request.files.get('img')
    name = 'img.jpg'
    img.save(os.path.join('./img', name))
    model.predict('./img', save=True, device='cpu')
    return 'success'

@app.route('/get', methods=['GET', 'POST'])
def download():
    print("working")
    return send_file('./runs/detect/predict/img.jpg')

if __name__ == '__main__':
    model = YOLO('./best.pt')
    app.run(host='0.0.0.0', port=5000, debug=True)

3.没有bug代码,速度慢

import os
import shutil
import uuid
from flask import Flask, request, send_file, after_this_request
from ultralytics import YOLO

# 初始化 YOLO 模型
model = YOLO('./best.pt')

# 初始化 Flask 应用
app = Flask(__name__)

def delete_directory(directory_path):
    """删除指定目录"""
    try:
        if os.path.exists(directory_path):
            shutil.rmtree(directory_path)
            print(f"Directory deleted: {directory_path}")
        else:
            print(f"Directory does not exist: {directory_path}")
    except Exception as e:
        print(f"Error deleting directory: {e}")

@app.route('/request', methods=['POST'])
def uploads():
    # 删除旧的 ./runs 目录和 ./img 目录
    delete_directory('./runs')
    delete_directory('./img')
    
    # 保存上传的图片
    img = request.files.get('img')
    if not img:
        return "No image uploaded", 400

    # 生成唯一文件名
    unique_id = str(uuid.uuid4())
    name = f'{unique_id}.jpg'
    os.makedirs('./img', exist_ok=True)
    img_path = os.path.join('./img', name)
    img.save(img_path)
    
    # 调用 YOLO 模型进行预测
    result_path = model.predict(img_path, save=True, device='cpu')[0]  # 假设 model.predict 返回结果路径列表
    # 注意:这里假设 model.predict 返回了结果图片的路径列表,实际情况可能需要根据 YOLO 的 API 进行调整

    # 返回成功信息(通常这里不应该返回图片路径,因为那是内部实现细节)
    return 'Image processed successfully'

@app.route('/get', methods=['GET'])
def download():
    # 查找预测结果中的第一张图片
    image_dir = './runs/detect/predict'
    image_files = [f for f in os.listdir(image_dir) if f.endswith(('.jpg', '.png', '.jpeg'))]
    if not image_files:
        return "No processed image found", 404

    image_name = image_files[0]
    image_path = os.path.join(image_dir, image_name)

    # 禁用缓存并发送文件
    response = send_file(image_path, as_attachment=True)
    response.headers['Cache-Control'] = 'no-store, no-cache, must-revalidate, post-check=0, pre-check=0'
    response.headers['Pragma'] = 'no-cache'
    response.headers['Expires'] = '0'
    return response

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000, debug=True)

4.注意事项

(1)

(2)

5.说明

(1)从小白到部署成功,大概需要两天,我是边学习边部署

(2)需要源码+辅导的同学点击(只给部分重要代码)

源码+服务_网信大数据信用风险报告查询系统源码-CSDN博客

参考文章

YOLOv11目标检测模型部署到微信小程序上-CSDN博客

Yolov5/8的小程序部署前后端实现_yolov8微信小程序-CSDN博客

 

 

 

Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐