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

张开发
2026/4/18 17:20:34 15 分钟阅读

分享文章

Flask项目+YOLOv11模型+部署在阿里云服务器上(宝塔控制面板)+uniapp微信小程序
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, saveTrue, devicecpu) 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(host0.0.0.0, port5000, debugTrue)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(fDirectory deleted: {directory_path}) else: print(fDirectory does not exist: {directory_path}) except Exception as e: print(fError 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_okTrue) img_path os.path.join(./img, name) img.save(img_path) # 调用 YOLO 模型进行预测 result_path model.predict(img_path, saveTrue, devicecpu)[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_attachmentTrue) response.headers[Cache-Control] no-store, no-cache, must-revalidate, post-check0, pre-check0 response.headers[Pragma] no-cache response.headers[Expires] 0 return response if __name__ __main__: app.run(host0.0.0.0, port5000, debugTrue)4.注意事项(1)(2)5.说明(1)从小白到部署成功大概需要两天我是边学习边部署(2)需要源码辅导的同学点击(只给部分重要代码)源码服务_网信大数据信用风险报告查询系统源码-CSDN博客参考文章YOLOv11目标检测模型部署到微信小程序上-CSDN博客Yolov5/8的小程序部署前后端实现_yolov8微信小程序-CSDN博客

更多文章