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

解决!!!

相关推荐
铁皮哥5 分钟前
【后端/Agent 开发】给你的项目配置一套 .claude/ 工作流:别再裸用 Claude Code 了!
java·windows·python·spring·github·maven·生活
m0_6315298223 分钟前
CSS如何利用CSS变量进行渐变色管理_提升渐变配置的灵活性
jvm·数据库·python
2301_8180084436 分钟前
数据库模型设计实战:如何正向工程从模型建表_规范化项目开发流程
jvm·数据库·python
科研前沿40 分钟前
多视角相机驱动的室内人员空间定位技术白皮书
大数据·人工智能·python·科技·数码相机·音视频
覆东流1 小时前
第10天:python元组
开发语言·后端·python
万事大吉CC1 小时前
【5】Django 的模板语言:页面架构设计
后端·python·django
码界奇点2 小时前
基于Python的微信公众号爬虫系统设计与实现
开发语言·爬虫·python·毕业设计·web·源代码管理
2401_846339562 小时前
Vue 3 中集成 Three.js 场景的完整实现指南
jvm·数据库·python
落雪寒窗-2 小时前
Python开发个人日常记录
开发语言·python
2301_775639892 小时前
Golang怎么写TODO待办应用_Golang TODO应用教程【深入】
jvm·数据库·python