pytorch save a minibatch of 4D tensor as images

Viewed 3390

I have set of 8 tensors in 4D tensor of shape (B, C, H, W). More specifically, the shape of my tensor is (8,3,64,64) i.e 8 images with [3x64x64] format.

I would like to save these in 1.png, 2.png ..., 8.png etc. When I try torchvision.utils.save_images(my_tensor), this is working fine. However, that is saving the images in a single grid instead of individual images.

How can I fix this issue?

I tried below code but that did not work.

for i in range(tensor.size(0)):

        np_data = tensor.cpu().numpy()
        imgplot = plt.imshow(np_data)
1 Answers

If you want to save individual images you could use:

for i in range(tensor.size(0)):
           torchvision.utils.save_image(tensor[i, :, :, :], '{}.png'.format(i))

which will save as : 1.png, 2.png ..., 8.png

Related