首页 > 解决方案 > 基于烧瓶的 API 可以返回文件吗

问题描述

我正在用 Flask 编写一个 API,它将文件作为输入,用 OpenCV 操作它,然后我想返回文件。理想情况下,我可以将文件连同一些元数据(操作完成的时间)一起返回。

产生我要返回的图像的行是:

image = cv2.rectangle(image, start_point, end_point, color, thickness)

理想情况下,我可以直接从内存中返回它(无需编写临时文件)

这甚至可能吗?

标签: pythonopencvflask

解决方案


是的,这可以做到

from flask import Flask, render_template , request , jsonify
from PIL import Image
import os , io , sys
import numpy as np 
import cv2
import base64

app = Flask(__name__)

start_point = (0, 0) 
end_point = (110, 110) 
color = (255, 0, 0)
thickness = 2

@app.route('/image' , methods=['POST'])
def mask_image():
    file = request.files['image'].read()
    npimg = np.fromstring(file, np.uint8)
    img = cv2.imdecode(npimg,cv2.IMREAD_COLOR)
    img = cv2.rectangle(img, start_point, end_point, color, thickness)
    img = Image.fromarray(img.astype("uint8"))
    rawBytes = io.BytesIO()
    img.save(rawBytes, "png")
    rawBytes.seek(0)
    img_base64 = base64.b64encode(rawBytes.read())
    return jsonify({'status':str(img_base64)})


if __name__ == '__main__':
    app.run(debug = True)

在这里,您返回带有在图像上绘制的矩形的 base64 编码图像。您可以在下图中看到添加的红色矩形

在此处输入图像描述


推荐阅读