YOLOv8 Flask整合问题

YOLOv8 Flask整合问题

yolov8 + flask 后代码没有进行推理问题。

Bug model.predict()+pyinstaller+HTTPServer/flask: not executing

yolov8是异步线程调用了,flask打包exe后会应该异步问题,model.predict()不会进行返回,导致没有看着没有执行而已。

Behind the scenes, ultralytics (or one of its dependencies) is using multiprocessing, and if you want to use multiprocessing in a PyInstaller-frozen application, you need to call multiprocessing.freeze_support before making any use of multiprocessing functionality.

In the case of your non-flask example:

python 复制代码
from http.server import BaseHTTPRequestHandler, HTTPServer
import json
import cv2
import multiprocessing  # For multiprocessing.freeze_support()
import numpy as np
import base64
import time
from ultralytics import YOLO

class MyServer(BaseHTTPRequestHandler):
    def do_POST(self):
        self.send_response(200)
        self.send_header("Content-type", "text/html")
        self.end_headers()

        content_length = int(self.headers['Content-Length'])
        post_data = json.loads(self.rfile.read(content_length))
        img = post_data['img']

        nparr = np.frombuffer(base64.b64decode(img), np.uint8)
        img_np = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
        
        print('starting..')
        model = YOLO('best.pt')
        print('model loaded')
        results = model.predict(source=img_np, show=False, save=False, save_conf=False, show_conf=False, save_txt=False)
        print('model predicted')

        self.wfile.write(bytes(f"ok", "utf-8"))

if __name__ == "__main__":
    multiprocessing.freeze_support()  # <--- Added
    print('starting server..')    
    webServer = HTTPServer(('localhost', 5000), MyServer)
    try:
        webServer.serve_forever()
    except KeyboardInterrupt:
        pass
    finally:
        print('aborted')
        time.sleep(2)
    webServer.server_close()

解决!!!

相关推荐
程序员大雄学编程10 分钟前
定积分的几何应用(一):平面图形面积计算详解
开发语言·python·数学·平面·微积分
小兵张健15 分钟前
Java + Spring 到 Python + FastAPI (一)
java·python·spring
2401_841495641 小时前
【自然语言处理】基于统计基的句子边界检测算法
人工智能·python·算法·机器学习·自然语言处理·统计学习·句子边界检测算法
程序员爱钓鱼1 小时前
Python编程实战 - Python实用工具与库 - 操作Word:python-docx
后端·python
程序员爱钓鱼1 小时前
Python编程实战 - Python实用工具与库 - 操作PDF:pdfplumber、PyPDF2
后端·python
啾啾啾6661 小时前
连接一个新的服务器时,打开PyCharm时报错:报错内容是服务器磁盘或配额满了
python·pycharm
长不大的蜡笔小新1 小时前
掌握NumPy:ndarray核心特性与创建
开发语言·python·numpy
luoganttcc1 小时前
已知 空间 三个 A,B C 点 ,求 顺序 经过 A B C 三点 圆弧 轨迹 ,给出 python 代码 并且 画出图像
c语言·开发语言·python
Q_Q5110082852 小时前
python+django/flask的图书馆管理系统vue
spring boot·python·django·flask·node.js·php
cwh_rs_giser2 小时前
如何高效设置机器学习超参数?——借鉴成熟AutoML框架的实践
人工智能·python·机器学习