Resize image before calling torchvision.utils.save_image

Hi!
I’m using save_image after some conv layer to output the image. But since the output shape of the tensor is torch.Size([32, 1, 3, 3]). I end up having very tiny images. How can I resize before calling save_image.
By the way, using scipy works

img = x.detach().cpu().numpy()
img = img[0] # Taking one image to test with
img = np.transpose(img, (2, 1, 0))
print(img.shape)
from scipy.misc import imsave, imresize
img = imresize(img, (224, 224))
imsave("./images/att.png", img)

Thank you

You could use:

x = torch.randn(32, 1, 3, 3)
transform = transforms.Compose([
    transforms.ToPILImage(),
    transforms.Resize(size=24),
    transforms.ToTensor()
])
x = [transform(x_) for x_ in x]
torchvision.utils.save_image(x, 'test.png')
2 Likes

Using x = torch.randn(32, 1, 3, 3) works, but using my x tensor does’nt work

File "/home/paul/miniconda3/lib/python3.6/site-packages/torchvision/transforms/transforms.py", line 49, in __call__
    img = t(img)
  File "/home/paul/miniconda3/lib/python3.6/site-packages/torchvision/transforms/transforms.py", line 110, in __call__
    return F.to_pil_image(pic, self.mode)
  File "/home/paul/miniconda3/lib/python3.6/site-packages/torchvision/transforms/functional.py", line 109, in to_pil_image
    npimg = np.transpose(pic.numpy(), (1, 2, 0))
RuntimeError: Can't call numpy() on Variable that requires grad. Use var.detach().numpy() instead.

I have tested this

x = att.view(b, 1, h, w)
print(x.size())  # ==> torch.Size([32, 1, 3, 3])
print(type(x))  # ==> <class 'torch.Tensor'>
x = torch.randn(32, 1, 3, 3)
print(x.size())  # ==> torch.Size([32, 1, 3, 3])
print(type(x))  # ==> <class 'torch.Tensor'>

So why mine doesn’t work
Thanks

Sorry, it still didn’t work

RuntimeError: Can't call numpy() on Variable that requires grad. Use var.detach().numpy() instead.

Try to call x = att.detach() before passing it to the transform.

using x = att.detach() didn’t work

TypeError: can't convert CUDA tensor to numpy. Use Tensor.cpu() to copy the tensor to host memory first.

But using x = detach().cpu() works.
For someone who will face the same problem
Thank you.