我发现如何使用 FastAPI 将 numpy 数组作为图像返回?然而,我仍然在努力展示图像,它看起来只是一个白色的方块。
io.BytesIO我像这样读入一个数组:
def iterarray(array):
output = io.BytesIO()
np.savez(output, array)
yield output.get_value()
Run Code Online (Sandbox Code Playgroud)
在我的端点中,我的回报是StreamingResponse(iterarray(), media_type='application/octet-stream')
当我留空media_type以推断时,会下载一个 zip 文件。
如何将数组显示为图像?
我想使用从 FastAPI 后端返回的 React 来渲染图像StreamingResponse。图像是数组的形式numpy,是cv2对象类型。
@app.post("/predict")
async def root(file: UploadFile = File(...)):
global model
global store_coordinates
global store_faces
global store_mesh
content = await file.read()
nparr = np.fromstring(content, np.uint8)
bg_img = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
......................
for i in range(len(store_coordinates)):
x, y, w, h = store_coordinates[i]
bg_img [b:b + d, a:a + c] = store_mesh[i]
res,im_png = cv2.imencode(".png", bg_img)
return StreamingResponse(io.BytesIO(im_png.tobytes()), media_type="image/png")
Run Code Online (Sandbox Code Playgroud)
在这里,我创建了一个 API 端点,其中使用POST请求接收上传的图像,并StreamableResponse(Image)返回 a。如何在 React 前端渲染这个返回的响应?
反应代码:
import React, { Component …Run Code Online (Sandbox Code Playgroud)