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

解决!!!

相关推荐
Carl_奕然2 分钟前
【智能体】Loop 的四种设计模式之:Event-Driven Loop(2026 最新版)
人工智能·驱动开发·python·设计模式
Carl_奕然11 分钟前
【智能体】Loop 的四种设计模式之:Hill Climbing Loop(2026 最新版)
人工智能·python·设计模式
专业程序开发源21 分钟前
springboot全民健身和饮食健康管理系统29158-计算机课程设计、毕业设计
java·spring boot·后端·python·django·php·课程设计
在世修行1 小时前
干货:业务标识 vs 自动判据
python
zwd20051 小时前
Manim move_to 和 shift 用法详解:相对位移、绝对落点与 aligned_edge(0.21.0 实测)
python·动画·可视化·shift·manim·数学动画·move_to
“AI国潮设计-小江”1 小时前
《Python+SDXL实战:用ControlNet精准控制“英歌舞戚风蛋糕”质感,附批量生成脚本》
开发语言·人工智能·python·prompt·aigc
jayhgq1 小时前
新一代Python包与项目管理工具——UV
开发语言·python·uv
for_ever_love__1 小时前
文件与异常——open、json、with 与 try-except 的工程写法
python·异常处理·文件操作·大模型开发
XLYcmy1 小时前
PDF 论文处理器 — 技术报告文档
数据库·python·网络安全·pdf·embedding·dify·rag
weixin_440401691 小时前
质朴的可视化绘图+pyecharts
开发语言·python·信息可视化·pyecharts