numpy - Pytorch:尝试将转换应用于 numpy 数组...失败并出现错误

标签 numpy pytorch

任何帮助都感激不尽。 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/

相关文章:

python - 从多个 csv 文件创建二维矩阵

python - 如何将 numpy.int32 转换为 decimal.Decimal

python - Tensorflow 线性回归结果与 Numpy/SciKit-Learn 不匹配

python - torch : AttributeError: 'function' object has no attribute 'cuda'

python - PyTorch-获取 'TypeError: pic should be PIL Image or ndarray. Got <class ' numpy.ndarray'>'错误

python - numpy 数组中多个元素的索引

python - 是否可以在 NumPy 中更改随机生成器的种子?

python - 给定多个预测向量,如何有效地获得得票最多的标签(在 numpy/pytorch 中)?

使用 mini-batch 时累积的 pytorch 损失

python - 来自 torch._C import * ImportError : DLL load failed: The specified module could not be found