python - 基于烧瓶的 API 可以返回文件吗
问题描述
我正在用 Flask 编写一个 API,它将文件作为输入,用 OpenCV 操作它,然后我想返回文件。理想情况下,我可以将文件连同一些元数据(操作完成的时间)一起返回。
产生我要返回的图像的行是:
image = cv2.rectangle(image, start_point, end_point, color, thickness)
理想情况下,我可以直接从内存中返回它(无需编写临时文件)
这甚至可能吗?
解决方案
是的,这可以做到
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 编码图像。您可以在下图中看到添加的红色矩形
推荐阅读
- identityserver4 - Identity Server 4:在 OnTokenValidated 中重定向或显示错误消息
- sql - 我需要将 SQL 参数转换为 Sequelize
- tmux - 如何解决tmux create pane failed::no such file or directory的问题
- flutter - 如何在 Flutter 桌面应用程序中集成 Linky TCP/IP 接口
- java - 什么是 junit-bom 和 junit 平台,我应该将它们包含在 gradle 依赖项中吗?
- sql - SQL 查询不检索正确的结果与计数
- android - CSS 到 android Drawable xml
- powershell - 有人可以告诉我这些安装 Chocolatey 的 PowerShell 脚本是否安全?
- identityserver4 - Identity Server 4:IProfileService.GetProfileDataAsync 中的 RequestedClaimTypes 不包括 IdentityResourceClaims
- c++ - 是否有比 std::mutex 更轻的互斥锁用于单写单读数据保护?