【问题标题】:How to use torchvision.io.read_image with image as variable, not stored file?如何使用 torchvision.io.read_image 与图像作为变量,而不是存储文件?
【发布时间】:2021-09-13 08:45:09
【问题描述】:

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

【问题讨论】:

    标签: python torch torchvision


    【解决方案1】:

    如果内存中的图像是 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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-31
      • 1970-01-01
      • 2015-07-15
      • 1970-01-01
      相关资源
      最近更新 更多