小编Jus*_*mer的帖子

How do I convert a torch tensor to an image to be returned by FastAPI?

I have a torch tensor which I need to convert to a byte object so that I can pass it to starlette's StreamingResponse which will return a reconstructed image from the byte object. I am trying to convert the tensor and return it like so:

def some_unimportant_function(params):
    return_image = io.BytesIO()
    torch.save(some_img, return_image)
    return_image.seek(0)
    return_img = return_image.read()
    
    return StreamingResponse(content=return_img, media_type="image/jpeg")

Run Code Online (Sandbox Code Playgroud)

The below works fine on regular byte objects and my API returns the reconstructed image:

def some_unimportant_function(params):
    image = Image.open(io.BytesIO(some_image))

    return_image …
Run Code Online (Sandbox Code Playgroud)

python pytorch starlette fastapi

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

标签 统计

fastapi ×1

python ×1

pytorch ×1

starlette ×1