相关疑难解决方法(0)

在 FastAPI 中渲染 NumPy 数组

我发现如何使用 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 文件。

如何将数组显示为图像?

python numpy bytesio fastapi

3
推荐指数
1
解决办法
7176
查看次数

如何使用 FastAPI/Nextjs 显示 Matplotlib 图表而不在本地保存图表?

我正在为网站使用 Nextjs 前端和 FastAPI 后端。我在前端有一个“以太坊地址”的输入表单,并使用输入的地址,我在后端生成一个 matplotlib 图表,显示“一段时间内的以太坊余额”。现在,我尝试使用 FastAPI 返回此图表,以便可以在前端显示它。我不想在本地保存图表。

这是到目前为止我的相关代码:

前端/ nexjs 文件名为“Chart.tsx”。正文中的“ethAddress”正在捕获输入表单中输入的数据。

fetch("http://localhost:8000/image", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(ethAddress),
    }).then(fetchEthAddresses);
Run Code Online (Sandbox Code Playgroud)

生成名为 ethBalanceTracker.py 的 matplotlib 图表的后端 python 文件

#Imports
#Logic for chart here

        plt.plot(times, balances)
        buf = BytesIO()
        plt.savefig(buf, format="png")
        buf.seek(0)

        return StreamingResponse(buf, media_type="image/png")
Run Code Online (Sandbox Code Playgroud)

使用名为 api.py 的 FastAPI 的后端 python 文件

@app.get("/image")
async def get_images() -> dict:
    return {"data": images}

@app.post("/image")
async def add_image(ethAddress: dict) -> dict:

    test = EthBalanceTracker.get_transactions(ethAddress["ethAddress"])
    images.append(test)
Run Code Online (Sandbox Code Playgroud)

我已经尝试了上面的代码和其他一些变体。我使用是StreamingResponse因为我不想在本地保存图表。我的问题是我无法显示图表localhost:8000/images并得到一个 …

python charts matplotlib next.js fastapi

2
推荐指数
1
解决办法
2431
查看次数

如何在 React 上渲染来自 FastAPI 服务器的 Streamable 图像?

我想使用从 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)

javascript python image reactjs fastapi

1
推荐指数
1
解决办法
4829
查看次数

标签 统计

fastapi ×3

python ×3

bytesio ×1

charts ×1

image ×1

javascript ×1

matplotlib ×1

next.js ×1

numpy ×1

reactjs ×1