Search code examples
pythontorchtorchvision

How to use torchvision.io.read_image with image as variable, not stored file?


torchvision.io.read_image uses as an input file stored in path argument. How can I achieve the same output if the image is stored as a variable? Of course, I can just save the image as a file and then read from it but it is additional time. Is there a way to get the same result as torchvision.io.read_image with input as a variable, not path?


Solution

  • If the images in memory are PIL images, you can use a transform function to convert it to a tensor in the right format (achieving the same effect as torchvision.io.read_image without the need of reading something from the disk).

    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)