Torchvision transformation toGrayScale requires Image?

torchvision/transforms/", line 743, in to_grayscale
    raise TypeError('img should be PIL Image. Got {}'.format(type(img)))
TypeError: img should be PIL Image. Got <class 'torch.Tensor'>

Hello, I understand the error. However, this should not happen. Transformation toGrayScale accepts both PIL images and Tensors according to the documentation. Also, this error only comes up on my machine and it doesn’t while running my script on Google Colab.

I guess your local setup might be using an older torchvision release, so you might want to update it.

Thank you. My torchvision version is in fact outdated. However, I can’t update it for lack of permission. I found out that linalg from scipy somehow conflicted with my torchvision version. I swapped the import statements (FIST: scipy, SECOND: torchvision) and now it works.

Did the import switch “fix” the issue in the same (old) torchvision release? If so, which torchvision version are you using?

For some reason, I was running torchvision 0.2.2.

Not it is updated to torchvision 0.11.1

The scipy problem raised later. Apparently I cannot do the following.

import torchvision
form scipy import linalg

I have to do this instead

from scipy import linalg
import torchvision

Apologies for the confusion. And thank you again :slight_smile:

I can’t reproduce the issue by swapping the import order in this code:

import torch
# from scipy import linalg
import torchvision
from scipy import linalg

img = torch.randn(3, 224, 224)
transform = torchvision.transforms.Grayscale()
out = transform(img)

However, also note that the functional API op:

torchvision.transforms.functional.to_grayscale(img, num_output_channels=1)

is not supporting tensors:

Convert PIL image of any mode (RGB, HSV, LAB, etc) to grayscale version of image. This transform does not support torch Tensor.

and you might want to use:

torchvision.transforms.functional.rgb_to_grayscale(img: torch.Tensor, num_output_channels: int = 1)