【问题标题】:How to return image and json in one response in fastapi?如何在fastapi的一个响应中返回图像和json?
【发布时间】:2021-02-18 17:57:50
【问题描述】:

我得到一张图像,对其进行更改,然后使用神经网络对其进行分类,应该返回一个新图像和带有响应的 json。如何使用一个端点来做到这一点? 图片是通过 Streaming Response 返回的,但是如何添加 json 呢?

import io
from starlette.responses import StreamingResponse

app = FastAPI()

@app.post("/predict")
def predict(file: UploadFile = File(...)):
    img = file.read()
    new_image = prepare_image(img)
    result = predict(new_image)
    return StreamingResponse(io.BytesIO(new_image.tobytes()), media_type="image/png")

【问题讨论】:

  • 你能提供你想要的 json 响应的样子吗?
  • 这种 json :{ 'objects': { 'object1': { 'x' : 5 , 'y': 3 }, 'object2': { 'x' : 5 , 'y ': 3 }}}
  • 什么是objects,什么代表xy(你有2次相同的坐标)?
  • 这只是一个json长什么样子的例子,objects和x,y跟问题无关,问题是怎么把response图片和这个json一起发送

标签: python fastapi


【解决方案1】:

我在响应标头中添加了 json。 更改自:

@app.post("/predict")
def predict(file: UploadFile = File(...)):
    img = file.read()
    new_image = prepare_image(img)
    result = predict(new_image)
    return StreamingResponse(io.BytesIO(new_image.tobytes()), media_type="image/png")

@app.post("/predict/")
def predict(file: UploadFile = File(...)):
    file_bytes = file.file.read()
    image = Image.open(io.BytesIO(file_bytes))
    new_image = prepare_image(image)
    result = predict(image)
    bytes_image = io.BytesIO()
    new_image.save(bytes_image, format='PNG')
    return Response(content = bytes_image.getvalue(), headers = result, media_type="image/png")

【讨论】:

    猜你喜欢
    • 2019-09-16
    • 1970-01-01
    • 1970-01-01
    • 2022-08-18
    • 2020-10-11
    • 2015-05-06
    • 2016-07-26
    • 2022-08-02
    • 1970-01-01
    相关资源
    最近更新 更多