Hi,
I am following the DC GAN tutorial of pytorch for generating synthetic images. I want to store generated after the last epoch individually.
https://pytorch.org/tutorials/beginner/dcgan_faces_tutorial.html
I am new to this. I don’t know how to save these images individually in a folder on local drive. Please help me.
Torchvision has a function called save_image()
. Here is the documentation.
You might want to take a look at this old discussion to see some examples.
Here is also a minimal example.
from torchvision.utils import save_image
# Batch x Channel x Height x Width = BxCxHxW = 64x3x28x28
rand_tensor= torch.rand(64, 3,28,28)
# Taking the first image from the batch (B)
# Img size CxHxW
img1 = rand_tensor[0]
save_image(img1, 'img1.png')
Thank you very much for your reply. This code will save only one image. Do I have to use loop to save all images individuallly?
Depending on what you want to save, if you want to save every image individually then yes, you can make a loop and save every one of them.
Or you can use the following code to save a grid of all of the images generated.
import torch
from torchvision.utils import save_image
t = torch.rand((64, 3, 50, 50))
save_image(t, "img_grid.png", nrow=8)
In the link provided in the previous post is the documentation for save_image
and it says you can use other **kwargs
specified in the make_grid
function.
Hope this helps
Thank you. It will solve my issue.
I was able to save the images individually like this:
import os
sample_dir = ‘samples’
if not os.path.exists(sample_dir):
os.makedirs(sample_dir)
if(epoch == num_epochs-1 ):
fake_fname = ‘fake-{0:0=4d}.png’.format(i)
#save_image(fake, os.path.join(sample_dir, fake_fname), nrow=8)
save_image(fake[i], os.path.join(sample_dir, fake_fname), nrow=1)