TypeError: img should be PIL Image. Got <class ‘numpy.ndarray’>
- 问题分析
当我们在使用
transforms.RandomHorizontalFlip(p=0.5),
transforms.RandomVerticalFlip(p=0.5),
transforms.Resize((224,224)) 等函数的时候,这时候会报错:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/opt/conda/lib/python3.7/site-packages/torchvision/transforms/transforms.py", line 175, in __call__
return F.resize(img, self.size, self.interpolation)
File "/opt/conda/lib/python3.7/site-packages/torchvision/transforms/functional.py", line 189, in resize
raise TypeError('img should be PIL Image. Got {}'.format(type(img)))
TypeError: img should be PIL Image. Got <class 'numpy.ndarray'>
- 解决办法
因为这些函数的输入应该是PIL Image的格式,其他的格式会报错,这时候我们应该把格式转为Image格式再进行,改为:
from PIL import Image
PIL_image = Image.fromarray(ndarray_image) #这里ndarray_image为原来的numpy数组类型的输入
这样就可以进行下面的步骤了。