【问题标题】:return predicted results in jsonify在 jsonify 中返回预测结果
【发布时间】:2021-05-01 17:12:33
【问题描述】:

我是一名学生,目前正在从事我的 python(FLASK) 图像分类项目。 我已经实现了所有的功能和模型,它作为网络应用程序运行良好。现在我想制作一个导致 JSONIFY 的 api,这样我也可以轻松地在移动应用程序中使用。 我有下面列出的代码

@app.route('/predict', methods=['GET', 'POST'])
def predict():
    if request.method == 'POST':
        img = request.files['image']
        filename = img.filename
        path = os.path.join('static/uploads', filename)
        img.save(path)
        print(filename)

        predictions = pipeline_model(path)
        return render_template("predict.html", p="uploads/{}".format(filename), pred=predictions)
    return render_template("predict.html", p="images/dog.jpg", pred="")

另一个管道功能是:

def pipeline_model(path):
    img = image.load_img(path, target_size=(299, 299))
    img = image.img_to_array(img)
    img = img / 255.0
    img = np.expand_dims(img, axis=0)

    pred = model.predict(img)
    max_preds = []
    pred = pred[0]
    for i in range(5):
        name = labels[pred.argmax()]
        per = round(np.amax(pred) * 100, 2)
        max_preds.append([name, per])
        ele = pred.argmax()
        pred = np.delete(pred, ele)

    paths = glob('static/uploads/*')
    if len(paths) > 5:
        for path in paths[:4]:
            os.remove(path)
    return max_preds

所以我想把这个“return render_template”函数转换成“return jsonify”的形式,如何实现,我们也可以在移动应用中使用。

【问题讨论】:

  • 图片中的代码无济于事,请将您的代码粘贴到问题中,以便重现和建议您。
  • @simpleApp,我已经在这个问题中编辑并发布了代码。
  • 谢谢,在答案部分添加了回复。我希望这会有所帮助。

标签: python api flask image-processing image-classification


【解决方案1】:

基于用户代理,您可以发送 json 或 HTML(因此应用程序和 HTML 应用程序都可以工作)。根据您的需要,您可以保留两个返回或使用唯一的 json。在此示例中,我使用了一个简单的字典,如果您需要帮助,请告诉我们。

@app.route("/get_my_prediction",methods=['GET','POST'])
def get_my_predicts():
    # print(request.headers) # for debug in case needed
    # print(f"request.headers.accept {request.headers.get('Accept')}") # for debug in case needed
    data = {"label1": "value 1", "label2": "value2", "label3": 3.6}
    data_type, *_ = request.headers.get('Accept').split(",")
    if "text/html" in data_type: # this code can be made cleaner based on need
        return make_response(str(data),200) # send as html, here you can keep your existing method to render html
    else:
        return make_response(jsonify(data), 200) # send as a json data

【讨论】:

  • 我刚刚写了,它对我有用:return jsonify({ })
  • 太棒了!请接受作为答案。谢谢
猜你喜欢
  • 1970-01-01
  • 2011-11-30
  • 1970-01-01
  • 2015-08-01
  • 1970-01-01
  • 2019-07-25
  • 2021-01-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多