How can I resize a 3D image tensor of size 143 x 512 x 512
to 143 x 256 x 256
?
Most image transformations can be done using PyTorch transforms. For your particular question, you can can use torchvision.transforms.Resize
.
import torch
from torchvision import transforms
resize = transforms.Resize((256, 256)) # the output shape you want
# an example 3D tensor
t = torch.rand(143, 512, 512)
t_resized = resize(t) # you should get its shape as (143, 256, 256), preserving the channel dimension
That’s exactly what I did.
gt_transform = transforms.Compose([
transforms.ToPILImage(),
transforms.Resize((256, 256), interpolation=0),
transforms.ToTensor()
])
label = torch.from_numpy(label.npy) # [143, 512, 512]
label_transform = gt_transform(label)
But I got the error
ValueError Traceback (most recent call last)
<ipython-input-31-da837537eac8> in <module>()
----> 1 label = gt_transform(label)
2 frames
/usr/local/lib/python3.7/dist-packages/torchvision/transforms/functional.py in to_pil_image(pic, mode)
229 # check number of channels
230 if pic.shape[-3] > 4:
--> 231 raise ValueError('pic should not have > 4 channels. Got {} channels.'.format(pic.shape[-3]))
232
233 elif isinstance(pic, np.ndarray):
ValueError: pic should not have > 4 channels. Got 143 channels.
You’re getting the error because you’re using the transform ToPILImage
on a tensor that just cannot form a PIL Image. PIL images have a maximum channel dimension of 4 that they can work with, whereas you have 143 channels.
You can see how your error arises if you check out the source code for ToPILImage
here:
https://pytorch.org/vision/stable/_modules/torchvision/transforms/functional.html#to_pil_image
Thanks, I will check as suggested.
My question is why you are using ToPILImage transformation?
can you try this:
gt_transform = transforms.Compose([
transforms.Resize((256, 256), interpolation=0),
transforms.ToTensor()
])
label = torch.from_numpy(label.npy) # [143, 512, 512]
label_transform = gt_transform(label)
Got this error
TypeError: pic should be PIL Image or ndarray. Got <class 'torch.Tensor'>
I remove the ToTensor()
and it works. Thanks to all