【问题标题】:Pytorch: Trying to apply the transform to a numpy array... fails with an errorPytorch:尝试将转换应用于 numpy 数组...失败并出现错误
【发布时间】:2018-03-17 03:09:09
【问题描述】:

任何帮助将不胜感激。 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),尺寸为(总行数、宽度、高度、通道数)

执行以下操作失败(我要做的只是应用转换):

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

【问题讨论】:

    标签: numpy pytorch


    【解决方案1】:

    我认为您不能对 numpy 数组应用转换。缩放(现在调整大小)适用于 PIL 图像,类似于许多其他转换。

    源码真的很容易看懂看这里:https://github.com/pytorch/vision/blob/master/torchvision/transforms.py

    【讨论】:

      【解决方案2】:

      大多数转换方法仅将 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 数组首先转换为 PIL 对象,然后应用其他转换。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-01-23
        • 2018-05-09
        • 2020-04-28
        • 1970-01-01
        • 1970-01-01
        • 2018-03-31
        • 1970-01-01
        • 2020-12-10
        相关资源
        最近更新 更多