2
from torchvision.utils import save_image

...
save_image(im, f'im_name.png')

In my case (standard mnist), using code from here, im is a Tensor:96, and save_image works.

I want that image in memory to show it in other plots, and I don't want to read it back after saving it, which seems kind of stupid.

Is there a way to separate the functionality of generating the image and of saving it?


Edit

clarification: I want an equivalent to

save_image(im, f'im_name.png')
reread = plt.imread(f'im_name.png')

without saving the image and reading it back. I just want the image, and I want to save it later. the save_image function does some work, like stacking multiple images into one, converting the tensor to images of correct sizes and so on. I want only that part without the saving to disk.

Gulzar
  • 23,452
  • 27
  • 113
  • 201
  • Are you trying to convert the tensor to an image? If so, check `torchvision.transforms.functional.to_pil_image` . Otherwise, could you clarify what you mean by "wanting the image in memory?" or "generating the image" ? – Dan Ganea Dec 15 '20 at 08:46

1 Answers1

3

About 2 weeks later, I stumbled upon the solution by accident.

grid = torchvision.utils.make_grid(im)

grid will be the image save_image was just saving.

Gulzar
  • 23,452
  • 27
  • 113
  • 201
  • Did you by chance get into a situation where the save_image() saves an image with wrong colors different from the original image? I have been facing this challenge and could not find a way to solve it. save_image() saves my image with a dimmer color. I do not want to ask a new question to avoid repetition. – Craving_gold Apr 06 '22 at 14:06
  • @Craving_gold Can't tell for sure, but likely you have either replaced RGB with BGR, or have [normalization issues](https://stackoverflow.com/a/60021899/913098). Also check data types - You may lose information due to type conversions. Anyway this is not related to this specific question. – Gulzar Apr 07 '22 at 07:59