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()

解决!!!

相关推荐
张彦峰ZYF7 分钟前
快速掌握Python编程基础
python
Json____20 分钟前
使用python的 FastApi框架开发图书管理系统-前后端分离项目分享
开发语言·python·fastapi·图书管理系统·图书·项目练习
安思派Anspire26 分钟前
LangGraph + MCP + Ollama:构建强大代理 AI 的关键(二)
人工智能·后端·python
站大爷IP30 分钟前
Python文件与目录比较全攻略:从基础操作到性能优化
python
ahead~2 小时前
【大模型入门】访问GPT_API实战案例
人工智能·python·gpt·大语言模型llm
大模型真好玩2 小时前
准确率飙升!GraphRAG如何利用知识图谱提升RAG答案质量(额外篇)——大规模文本数据下GraphRAG实战
人工智能·python·mcp
19892 小时前
【零基础学AI】第30讲:生成对抗网络(GAN)实战 - 手写数字生成
人工智能·python·深度学习·神经网络·机器学习·生成对抗网络·近邻算法
applebomb3 小时前
没合适的组合wheel包,就自行编译flash_attn吧
python·ubuntu·attention·flash
19893 小时前
【零基础学AI】第31讲:目标检测 - YOLO算法
人工智能·rnn·yolo·目标检测·tensorflow·lstm
Chasing__Dreams3 小时前
python--杂识--18.1--pandas数据插入sqlite并进行查询
python·sqlite·pandas