如何使用torchvision.io.read_image,将图像作为变量,而不是存储文件



torchvision.io.read_image使用存储在path参数中的输入文件。如果图像作为变量存储,我如何实现相同的输出?当然,我可以将图像保存为文件,然后从中读取,但这需要额外的时间。有没有一种方法可以获得与torchvision.io.read_image相同的结果,将输入作为变量,而不是路径?

如果内存中的图像是PIL图像,则可以使用变换函数将其转换为正确格式的张量(无需从磁盘读取内容即可实现与torchvision.io.read_image相同的效果(。

import PIL
import torchvision.transforms.functional as transform
# Reads a file using pillow
PIL_image = PIL.Image.open(image_path)
# The image can be converted to tensor using
tensor_image = transform.to_tensor(PIL_image)
# The tensor can be converted back to PIL using
new_PIL_image = transform.to_pil_image(tensor_image)

最新更新