【问题标题】:How to return an image in fastAPI如何在 fastAPI 中返回图像
【发布时间】:2020-06-13 11:56:48
【问题描述】:

在使用 Opencv 比较两个图像后,我试图在 fastAPI 中返回一个图像。

这是我到目前为止所做的:

from fastapi import FastAPI , File, UploadFile
import numpy as np
from cv2 import *
import os
import base64


app = FastAPI(debug = True)


@app.post("/uploadfile/")
async def create_upload_file(file: UploadFile = File(...),file1: UploadFile = File(...)):
    content = await file.read()
    nparr = np.fromstring(content, np.uint8)
    img = cv2.imdecode(nparr, cv2.IMREAD_COLOR)

    content1 = await file1.read()
    nparr1 = np.fromstring(content1, np.uint8)
    img1 = cv2.imdecode(nparr1, cv2.IMREAD_COLOR)

    akaze = cv2.AKAZE_create()
    kpts1, desc1 = akaze.detectAndCompute(img, None)
    kpts2, desc2 = akaze.detectAndCompute(img1, None)
    matcher = cv2.DescriptorMatcher_create(cv2.DescriptorMatcher_BRUTEFORCE_HAMMING)
    matches_1 = matcher.knnMatch(desc1, desc2, 2)
    good_points = []
    for m,n in matches_1:
            if m.distance < 0.7 * n.distance:
                good_points.append(m)
    mat = (round(len(kpts2)/len(good_points),2))

我遇到错误的地方

    return_img = cv2.processImage(img)
    _, encoded_img = cv2.imencode('.PNG', return_img)
    encoded_img = base64.b64encode(return_img)

    return {"The similarity is": mat,'encoded_img': endcoded_img}

我做错了什么?

【问题讨论】:

标签: python api opencv opencv3.1 fastapi


【解决方案1】:

是的,您可以使用 FastAPI 返回图像,实际上非常简单。

from fastapi import FastAPI
from fastapi.responses import FileResponse

some_file_path = "some_image.jpeg"
app = FastAPI()


@app.get("/")
async def main():
    return FileResponse(some_file_path)

确保安装 aiofilespip install aiofiles 否则,您将收到如下错误:

AssertionError: 'aiofiles' must be installed to use FileResponse

如果您将图像作为字节考虑使用StreamingResponse

from io import BytesIO

@app.post("/send_image")
async def send():
    image = BytesIO()
    img =                                        # Do something here to create an image
    img.save(image, format='JPEG', quality=85)   # Save image to BytesIO
    image.seek(0)                                # Return cursor to starting point
    return StreamingResponse(image.read(), media_type="image/jpeg")

【讨论】:

  • 我确实安装了 aiofiles,但仍然遇到同样的错误
【解决方案2】:

可以在here找到解决方案。您在第 3 行编码之前转换 Opencv 图像。

    return_img = cv2.processImage(img)
    _, encoded_img = cv2.imencode('.PNG', return_img)
    encoded_img = base64.b64encode(return_img)

    return {"The similarity is": mat,'encoded_img': endcoded_img}

return_img 替换为encoded_img,一切都会按预期工作。

    return_img = cv2.processImage(img)
    _, encoded_img = cv2.imencode('.PNG', return_img)
    encoded_img = base64.b64encode(encoded_img)

    return {"The similarity is": mat,'encoded_img': endcoded_img}

【讨论】:

    【解决方案3】:

    如果您只想返回图像,则返回带有正确编码的图像本身,请参阅Return a Response Directly

    如果您还需要使用 json 中的图像返回其他信息,请参阅此 SO 问题How do you put an image file in a json object?(注意:解决方案在 javascript 中,但很容易适应 python)

    【讨论】:

      猜你喜欢
      • 2019-09-16
      • 2020-05-02
      • 1970-01-01
      • 2022-08-18
      • 1970-01-01
      • 1970-01-01
      • 2021-08-06
      • 1970-01-01
      • 2021-03-25
      相关资源
      最近更新 更多