任何帮助都感激不尽。 transforms.py 中的代码表示转换应该/将适用于 PIL 图像以及 ndarrays。
鉴于变换:
data_transforms = {
'train': transforms.Compose([
transforms.Scale(256),
transforms.Pad(4,0),
transforms.ToTensor(),
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
]),
'val': transforms.Compose([
transforms.Scale(256),
transforms.Pad(4,0),
transforms.ToTensor(),
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
]),
}
我希望对从其他代码获得的 ndarray 应用转换。假设它是 x_data,其形状为 (1000,120,160,3),其中尺寸为(总行数、宽度、高度、 channel )
执行以下操作失败(我要做的就是应用转换):
foo = data_transforms['train']
bar = foo(x_data[0])
带有以下消息:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-93-a703e3b9c76d> in <module>()
----> 1 foo(x_data[1])
~/anaconda3/envs/pytorch/lib/python3.5/site-packages/torchvision-0.1.9-py3.5.egg/torchvision/transforms.py in __call__(self, img)
32 def __call__(self, img):
33 for t in self.transforms:
---> 34 img = t(img)
35 return img
36
~/anaconda3/envs/pytorch/lib/python3.5/site-packages/torchvision-0.1.9-py3.5.egg/torchvision/transforms.py in __call__(self, img)
185 """
186 if isinstance(self.size, int):
--> 187 w, h = img.size
188 if (w <= h and w == self.size) or (h <= w and h == self.size):
189 return img
TypeError: 'int' object is not iterable
最佳答案
大多数转换方法仅将 PIL 对象作为输入。但是您可以添加另一个名为 transforms.ToPILImage()
的转换,它以 nd-array 作为输入,将 nd-array 转换为 PIL 对象。所以在你的情况下,字典变量应该变成:
data_transforms = {
'train': transforms.Compose([
transforms.ToPILImage()
transforms.Scale(256),
transforms.Pad(4,0),
transforms.ToTensor(),
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
]),
'val': transforms.Compose([
transforms.Scale(256),
transforms.Pad(4,0),
transforms.ToTensor(),
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
]),
}
请注意,这些转换是按顺序进行的。所以有必要添加
toPILImage
转换作为第一个转换。因此,您的 nd-array 首先转换为 PIL 对象,然后应用其他转换。
关于numpy - Pytorch:尝试将转换应用于 numpy 数组...失败并出现错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46586616/