Torchvision.transforms.functional.normalize throws Error: img should be PIL Image. Got <class 'torch.Tensor'>

Hi there,

I am trying to transform my input data. I have images of shape [6, height, width] and want to reshape them to [6, 112, 112]. Since I have 6 channels, I can’t use PILImage. Therefore I coose to use torchvision.transforms.functional.resize() because it is supposed to take torch.Tensors as input aswell.
I tried:

            img = torch.tensor(img)
            img = transforms.functional.resize(img, size =(112,112))
            img = transforms.functional.normalize(img, (0.5,0.5,0.5,0.5,0.5,0.5), (0.25,0.25,0.25,0.25,0.25,0.25))

But I get the following error:

TypeError: img should be PIL Image. Got <class 'torch.Tensor'>

Can somebody tell me what I can do to transform my 6 channel images?

Thanks =)

You might need to update to the latest torchvision version, as the tensor input functionality was just recently added. :wink:

Could you point out which version of torchvision do you refer to?

I am using torch==1.7.1+cu101 torchvision==0.8.2+cu101. According to PyTorch 1.7.1 documentation: “All transformations accept PIL Image, Tensor Image or batch of Tensor Images as input.”

Still, when trying to apply transforms.RandomVerticalFlip() and transforms.RandomHorizontalFlip() to a torch.tensor with torch.Size([10, 8, 8])(C, H, W) shape, I am getting:

TypeError: img should be PIL Image. Got <class 'numpy.ndarray'> from site-packages/torchvision/transforms/functional_pil.py", line 73, in vflip
raise TypeError(‘img should be PIL Image. Got {}’.format(type(img))).

The error points towards a numpy array as the input, which isn’t supported.
Try to convert it to a tensor and rerun it.

Hi @ptrblck,

Yes, you are right, I was inputting a NumPy array. What I finally did was building Torchvision from the source, as the tensor use is only allowed in the master branch (not available in the releases).

:slight_smile:

Good to hear it’s working now!
As a side note: you could also install the nightly binary, which would ship with the latest features (built from the master branch from “last night”) by selecting the “Preview (Nightly)” tab here.

1 Like