How to save image?

for i in train_loader:
     images.shape = [64,3,28,28]

I can save images but 64 images are drawed.
How can I save only one image from them?

2 Likes

Are you trying to save an image from a tensor? if yes, then you need to specifiy the correct index.

e.g.

tensor1 has shape [64,3,28,28]

then to get one/first image out of it (the batch of 64), you need

image1_tensor= tensor1[0]

now you need to swap the axis to convert it into numpy

image1_numpy = image1_tensor.numpy()

Now if you save image1_numpy, you will get one image.

1 Like
from torchvision.utils import save_image

images.shape #torch.Size([64,3,28,28])
img1 = images[0] #torch.Size([3,28,28]
# img1 = img1.numpy() # TypeError: tensor or list of tensors expected, got <class 'numpy.ndarray'>
save_image(img1, 'img1.png')

Process finished with exit code 139 (interrupted by signal 11: SIGSEGV)

In this situation, What should I do?

4 Likes

I tested, this works :

from torchvision.utils import save_image
import torch
import torchvision

rand_tensor= torch.rand(64, 3,28,28) 

img1 = rand_tensor[0]
# img1 = img1.numpy() # TypeError: tensor or list of tensors expected, got <class 'numpy.ndarray'>
save_image(img1, 'img1.png')
11 Likes

In my case, I always visualize the images in 2 ways, there are really common I guess:

Suppose our torch tensor follows the NCHW format.

  1. save tensor into image directly
    In this situation, you can use
save_image(make_grid(postprocess_image(batch_tensor), nrow=8),"XXX.jpg")` 

where the postprocess_image() executes some post processing operation, say, unnormalizing.

  1. save tensor into summayWriter
    In this case, you can use:
SummaryWriter.add_image("image", make_grid(postprocess_image(batch_tensor), nrow=8), step)

Yep! Note that add_image() assume the input tensor is a 3D tensor with CHW format, for other formations, check the docs out!

Hope this helps. :smile:

3 Likes

hi, what if I would like to save image into paritcular folder?
what should be added in the save_image function?

1 Like
save_image(img1, 'img1.png')

Here, you are saving the img1 as img1.png in your current working directory, that argument is actually the path where you want to save your file, you can pass anything like folder1/img1.png in that function as an argument if your file structure looks like this, then the img1.png will get saved in the folder1.

current_working_directory
|__folder1
|__file.py