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

解决!!!

相关推荐
2301_78204045几秒前
CSS Flex布局中如何实现导航栏与Logo的左右分布_利用justify-content- space-between
jvm·数据库·python
yaoxin5211237 分钟前
400. Java 文件操作基础 - 使用 Buffered Stream I/O 读取文本文件
java·开发语言·python
用户83562907805143 分钟前
使用 Python 自动创建 Excel 折线图
后端·python
小白学大数据1 小时前
面向大规模爬取:Python 全站链接爬虫优化(过滤 + 断点续爬)
开发语言·爬虫·python
赵药师1 小时前
Cityscape数据集转YOLO
人工智能·深度学习·yolo
WL_Aurora2 小时前
【每日一题】贪心
python·算法
IT策士2 小时前
Python 中间件系列:redis 深入浅出
redis·python·中间件
Dxy12393102162 小时前
Python Pillow库:`img.format`与`img.mode`的区别详解
开发语言·python·pillow
༒࿈南林࿈༒3 小时前
刺猬猫小说下载
python·js逆向
.柒宇.3 小时前
AI-Agent入门实战-AI私厨
人工智能·python·langchain·agent·fastapi