這是我當前作業正常的 Flask 代碼,它從客戶端接收帶有影像的 POST 請求,通過模型運行它(基于此 GH:https : //github.com/matterport/Mask_RCNN),并發送一個掩碼影像回傳給客戶端。
但是,它正在從Configuration檔案加載模型并為每個請求加載權重,這需要很長時間。我想在服務器啟動時加載模型和權重并將其傳遞給索引函式。我已經嘗試了其他問題的解決方案,但沒有運氣。我想知道是不是因為我正在加載一個模型,然后是權重,而不是僅僅加載一個 h5 模型檔案?
如何在燒瓶應用程式中初始化時加載檔案 在燒瓶應用程式 啟動后運行代碼
燒瓶應用程式:
from flask import Flask, jsonify, request
import base64
import cv2
import numpy as np
from Configuration import create_model
app = Flask(__name__)
@app.route('/', methods=['GET', 'POST'])
def index():
if request.method == "POST":
# Load the image sent from the client
imagefile = request.files['image'].read() # Type: bytes
jpg_as_np = np.frombuffer(imagefile, dtype=np.uint8) # Convert to numpy array
img = cv2.imdecode(jpg_as_np, flags=1) # Decode from numpy array to opencv object - This is an array
### Enter OpenCV/Tensorflow below ###
model = create_model()
image = img[..., ::-1]
# Detect objects
r = model.detect([image], verbose=0)[0]
REDACTED VISUALIATION CODE
### ###
string = base64.b64encode(cv2.imencode('.jpg', masked_image)[1]).decode() # Convert back to b64 string ready for json.
return jsonify({"count": str(r["masks"].shape[2]), 'image': string})
if __name__ == "__main__":
app.run()
配置:
def create_model():
device = "/cpu:0"
weights_path = "weights.h5"
with tf.device(device):
model = modellib.MaskRCNN(mode="inference", model_dir=weights_path, config=InferenceConfig())
model.load_weights(weights_path, by_name=True)
print("Weights Loaded")
return model
uj5u.com熱心網友回復:
我使用before_first_request裝飾器解決了這個問題。下面是一般結構:
app = Flask(__name__)
@app.before_first_request
def before_first_request_func():
MOODEL WEIGHT LOADING CODE
return model
@app.route('/', methods=['POST'])
def index():
if request.method == "POST":
REDACTED LOADING CODE
# Detect objects
r = model.detect([image], verbose=0)[0]
REDACTED VISUALISATION CODE
string = base64.b64encode(cv2.imencode('.jpg', masked_image)[1]).decode() # Convert back to b64 string ready for json.
return jsonify({"count": str(r["masks"].shape[2]), 'image': string})
if __name__ == "__main__":
app.run()
model存盤在記憶體中,以后可以在檢測函式中參考。它可用于每個 POST 請求,不需要重新加載。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/349233.html
