【问题标题】:Trouble with PyTorch's 'ToPILImage'PyTorch 的“ToPILImage”问题
【发布时间】:2020-10-18 09:37:06
【问题描述】:

为什么这不起作用?

import torchvision.transforms.functional as tf
from torchvision import transforms
pic = np.random.randint(0, 255+1, size=28*28).reshape(28, 28)
pic = pic.astype(int)
plt.imshow(pic)
t = transforms.ToPILImage()
t(pic.reshape(28, 28, 1))
# tf.to_pil_image(pic.reshape(28, 28, 1))

matplotlib 绘制了一张漂亮的随机图片,但无论我为我的 NumPy ndarray 选择什么数据类型,to_pil_imageToPILImage 都无法按预期工作。

文档是这样说的:

将张量 ... 或形状为 H x W x C 的 numpy ndarray 转换为 PIL 图像,同时保留值范围。 ... 如果输入有 1 个通道,则 mode 由数据类型确定(即 intfloatshort

除了“short”之外,这些数据类型都不起作用。

其他所有结果:

TypeError: Input type int64/float64 is not supported

torchvision/transforms/functional.pyto_pil_image() 中抛出。

此外,即使 short 数据类型适用于我首先提供的独立代码 sn-p,但在从 Dataset 对象的 __getitem__ 调用的 transform.Compose() 中使用时它会崩溃:

choices = transforms.RandomChoice([transforms.RandomAffine(30),
                                   transforms.RandomPerspective()])

transform = transforms.Compose([transforms.ToPILImage(),
                                transforms.RandomApply([choices], 0.5),
                                transforms.ToTensor(),
                                transforms.Normalize((0.5,), (0.5,))])

trainset = MNIST('data/train.csv', transform=transform)
trainloader = DataLoader(trainset, batch_size=32, shuffle=True, num_workers=4)


RuntimeError: DataLoader worker (pid 12917) is killed by signal: Floating point exception.
RuntimeError: DataLoader worker (pid(s) 12917) exited unexpectedly

【问题讨论】:

    标签: python numpy pytorch torchvision


    【解决方案1】:

    查看to_pil_imagesource code,可以看到只支持np.{uint8, int16, uint32, float32} 类型的numpy 数组。

    尝试将图片投射到np.uint8

    pic = pic.astype(np.uint8)
    

    这应该适合你

    【讨论】:

      【解决方案2】:

      上述答案仅对我有用,但需要进行以下更改:

      pic = pic.astype('uint8')
      

      希望它对你有用。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-02-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-02-15
        • 2021-01-28
        • 2019-01-15
        • 2019-01-25
        相关资源
        最近更新 更多