我有一个Torch张量,我需要将其转换为Byte对象,以便将其传递给Starlette的StreamingResponse,后者将从Byte对象返回重建的图像.我正在try 转换张量并返回它,如下所示:

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")

下面的代码可以很好地处理常规的Byte对象,并且我的API将返回重建的图像:

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

    return_image = io.BytesIO()
    image.save(return_image, "JPEG")
    return_image.seek(0)
    return StreamingResponse(content=return_image, media_type="image/jpeg")

为此使用PIL个库

我到底做错了什么?

推荐答案

使用torchvision.transforms.ToPILImage()模块将PyTorch张量器转换为PIL图像对象,然后将其视为PIL图像作为您的第二个函数.这里有一个例子.

def some_unimportant_function(params):
    tensor = # read the tensor from disk or whatever
    image = torchvision.transforms.ToPILImage()(tensor.unsqueeze(0))
    return_image = io.BytesIO()
    image.save(return_image, "JPEG")
    return_image.seek(0)
    return StreamingResponse(content=return_image, media_type="image/jpeg")

Python相关问答推荐

根据不同列的值在收件箱中移动数据

删除任何仅包含字符(或不包含其他数字值的邮政编码)的观察

在Pandas DataFrame操作中用链接替换'方法的更有效方法

为什么这个带有List输入的简单numba函数这么慢

在极性中创建条件累积和

把一个pandas文件夹从juyter笔记本放到堆栈溢出问题中的最快方法?

如何根据一列的值有条件地 Select 前N组?

为什么numpy. vectorize调用vectorized函数的次数比vector中的元素要多?

在Python中计算连续天数

如何使用两个关键函数来排序一个多索引框架?

如何获取Python synsets列表的第一个内容?

以异步方式填充Pandas 数据帧

Js的查询结果可以在PC Chrome上显示,但不能在Android Chrome、OPERA和EDGE上显示,而两者都可以在Firefox上运行

使用polars. pivot()旋转一个框架(类似于R中的pivot_longer)

如何用FFT确定频变幅值

如何在Python中自动创建数字文件夹和正在进行的文件夹?

在一个数据帧中,我如何才能发现每个行号是否出现在一列列表中?

时间戳上的SOAP头签名无效

401使用有效的OAuth令牌向Google Apps脚本Web App发出POST请求时出现未经授权的错误(";

搜索结果未显示.我的URL选项卡显示:http://127.0.0.1:8000/search?";,而不是这个:";http://127.0.0.1:8000/search?q=name";