How to save generated image without grid?- GAN

Hi, I want to save generated images as a single image instead of grid. What change should I need to make in the following code:
def save_samples(index, latent_tensors, show=True):

fake_images = generator(latent_tensors)

fake_fname = 'generated-images-{0:0=4d}.png'.format(index)

save_image(denorm(fake_images), os.path.join(sample_dir, fake_fname), nrow=8)

print('Saving', fake_fname)

if show:

    fig, ax = plt.subplots(figsize=(8, 8))

    ax.set_xticks([]); ax.set_yticks([])

    ax.imshow(make_grid(fake_images.cpu().detach(), nrow=8).permute(1, 2, 0))

Any help shall be highly appreciated.

Just pick a single image from fake_images.

It is a batch of them, so you need to choose from first dimension.

1 Like

def save_samples(index, latent_tensors, show=True):

fake_images = generator(latent_tensors)

#print(fake_images.shape)

plt.imshow(fake_images[0][0].cpu().detach())

fake_fname = 'generated-images-{0:0=4d}.png'.format(index)

save_image(denorm(fake_images[0][0]), os.path.join(sample_dir, fake_fname))

print('Saving', fake_fname)

@Sebgolos My first question is since “fake_image” is a tensor so how could I enumerate through it to get all the generated image.
Secondly, I am not understanding how fake_image[0][0] is giving me an image. I am not getting its dimensions. Please help.

Your fake_images tensor has (probably) 4 dimensions. The first one is a batch dimension:
(Batch, Channels, Height, Width).
Each “projection” from this first dimension leaves you with (C, H, W) - a single image.

You can get the number of images (3D tensors along first batch dimension) you can use tensor method shape(). You can specify the index of dimension you want to know the length of.

1 Like

Ok. I got your point. If I want to get first image should I write something like this fake_images[0] or fake_images[0][0]??

With fake_images[0][0] you would pick first image and first channel.

This can be ok if your images are in grayscale. This causes the C value to be 1 (a single channel image), so it makes sense in such case. So you’re then left with (H, W).

1 Like