yolo v8 + flask部署到云服务器,以及问题记录

环境安装

1、运行项目报错:no python application found, check your startup logs for errors

在云服务器pytorch版本安装错了,安装了GPU版本,需要安装CPU版本

# CPU only 使用下面这段代码避免出现第二个错误
pip install torch==2.3.1 torchvision==0.18.1 torchaudio==2.3.1 --index-url https://download.pytorch.org/whl/cpu

2、运行项目报错:RuntimeError: operator torchvision::nms does not exist

检查发现pytorch中torchvision版本不匹配:

卸载重装对应匹配版本:

# CPU only
pip install torch==2.3.1 torchvision==0.18.1 torchaudio==2.3.1 --index-url https://download.pytorch.org/whl/cpu

3、后端python文件编写,涉及到读写文件、模型预测、以及获取结果分析,转换yolo预测结果为指定的json格式数据。

import os
import numpy as np
import torch.hub
#导入Yolov8,需要提前安装ultralytics库
from ultralytics import YOLO
from flask import Flask
#运用Python的flask类实现与前台信息的交互
from flask import request
from flask import send_file
import base64
import cv2
import time
import json
from pathlib import Path

app = Flask(__name__)
# 调用训练好的模型
model = YOLO('./best.pt')
@app.route('/', methods=['GET', 'POST'])
def uploads():
    # 拿到变量img对应的图片
    img = request.files.get('img')
    if img:
        # 重命名
        name = 'img.jpg'
        # 保存
        img.save(os.path.join('./img', name))
        fileName = "./img/"+name
        # results = model.predict('./img/img.jpg',save=True)#调用模型进行判断 save_txt=True
        results = model.predict(fileName,save=True,save_txt=True)
        # 类名字典
        names = results[0].names
        listData = []
        for key in names:
            # print(key, names[key])
            data = {'name': names[key],"value": 0}
            listData.append(data)
        # 读取数据分析内容
        # print(listData)
        content = getContent(results,listData)
        # print(content)
        # 5. 返回结果
        data = {
            "errCode":0,
            "msg":"success",
            "data":content,
            "img":results[0].path
        }
        return json.dumps(data)

    else:
        data = {"errCode":1,"msg":"cannot find file!"}
        return json.dumps(data)

# 获取结果文本内容
def getContent(results,listData):
    # 获取文件保存的路径
    save_path = Path(results[0].save_dir)
    content = []
    # 获取label标签文件
    for r in results:
        im_name = Path(r.path).stem
        labels = save_path / f"labels/{im_name}.txt"
    # 读取标签文件中的内容
    txt_file = labels
    with open(txt_file, 'r') as file:
        # content = file.read()
        lines = file.readlines()
        print(lines)
    for line in lines:
        index = int(line.split()[0])
        print("每行---", index)
        if index

前端接收到返回数据:

yolo v8 + flask部署到云服务器,以及问题记录_第1张图片

4、flask上传的图片文件无法访问的问题

根据上述返回数据中,预测目标后的结果图片地址:https://***.com/runs/detect/predict/***.jpg,这个路径无法被访问,需要单独配置:

# 配置路径访问
from flask import send_from_directory

# .....

# 文件访问 runs/detect/predict*/
@app.route('/runs/')
def send_image(path):
    # print(path,'------path')
    # print(send_from_directory('runs/', path))
    return send_from_directory('runs/', path)
import os
import numpy as np
import torch.hub
#导入Yolov8,需要提前安装ultralytics库
from ultralytics import YOLO
from flask import Flask
#运用Python的flask类实现与前台信息的交互
from flask import request
from flask import send_file
import base64
import cv2
import time
import json
from pathlib import Path
# 配置路径访问
from flask import send_from_directory

app = Flask(__name__)
verifyCode = "89jjkdsw909324jjkjds9f8sdf"

# 文件访问 runs/detect/predict*/
@app.route('/runs/')
def send_image(path):
    # print(path,'------path')
    # print(send_from_directory('runs/', path))
    return send_from_directory('runs/', path)

@app.route('/', methods=['GET', 'POST'])
def uploads():
    # 获取前端上传code,判断是否合法请求
    postData = request.form if request.form else request.json
    # print(postData.get("code"))
    verifyRes = verify(postData.get("code"))
    # 是否非法请求
    if verifyRes == False:
        data = {"errCode":1, "msg": "illegal request!"}
        return json.dumps(data)
        
    # 拿到变量img对应的图片
    img = request.files.get('img')
    # 请求模型识别类型
    sourceType = postData.get("sourceType")
    print(sourceType, '-------------sourceType')
    if sourceType and int(sourceType) == 1:
        # 默认捕蝇灯识别
        model = YOLO('./best2.pt')
    else:
        # 默认捕蝇灯识别
        model = YOLO('./best.pt')
    
    if img:
        # 重命名
        name = str(time.time())+'.jpg'
        # 保存
        img.save(os.path.join('./img', name))
        fileName = "./img/"+name
        # results = model.predict('./img/img.jpg',save=True)#调用模型进行判断 save_txt=True
        results = model.predict(fileName,save=True,save_txt=True)
        # 类名字典
        names = results[0].names
        listData = []
        for key in names:
            # print(key, names[key])
            data = {'name': names[key],"value": 0}
            listData.append(data)
        # 读取数据分析内容
        # print(listData)
        content = getContent(results,listData)
        # print(content)
        # 5. 返回结果
        data = {
            "errCode": 0,
            "msg": "success",
            "data": content,
            "img": results[0].save_dir+"/"+name
        }
        return json.dumps(data)

    else:
        data = {"errCode":1,"msg":"cannot find file!"}
        return json.dumps(data)

# 验证code合法性
def verify(code):
    return code == verifyCode

# 获取结果文本内容
def getContent(results,listData):
    # 获取文件保存的路径
    print(results, '-----url')
    save_path = Path(results[0].save_dir)
    content = []
    # 获取label标签文件
    for r in results:
        im_name = Path(r.path).stem
        labels = save_path / f"labels/{im_name}.txt"
    # 读取标签文件中的内容
    txt_file = labels
    if not os.path.exists(txt_file):
        return []
    with open(txt_file, 'r') as file:
        # content = file.read()
        lines = file.readlines()
        # print(lines)
    for line in lines:
        index = int(line.split()[0])
        # print("每行---", index)
        if index

参考文档:预测 -Ultralytics YOLO 文档

你可能感兴趣的:(YOLO,pytorch,python,flask)