axes don't match array in pytorch
一个有意思的错误:
self.transformer = transforms.Compose([transforms.ToTensor()])
img = self.transformer(img)
该语句在python3.7中运行无问题,在python2.7中出现如下错误:
img = torch.from_numpy(pic.transpose((2, 0, 1)))
ValueError: axes don't match array
解决方案:
错误原因:You are applying the transformation to a list of numpy arrays instead of to a single PIL image (which is usually what ToTensor()
transforms expects).(来源:https://stackoverflow.com/questions/53995708/axes-dont-match-array-in-pytorch)
代码修改:
img = torch.Tensor(img/255.0)
img = img.unsqueeze(0)
用上述语句替换img = self.transformer(img)这个语句。
1. 因为transforms.ToTensor()完成了类型 转换+归一化两个步骤,而torch.Tensor仅完成类型转换。
2. 我的代码中因为img是灰度图像,大小H*W,使用transforms.ToTensor()后大小为1*H*W,而使用torch.Tensor后仅为H*W,所以加了img = img.unsqueeze(0)语句,将其大小变为1*H*W。
这两个语句在python2.7中运行的效果与原语句在python3.7中运行效果一样。
环境整体:
环境1:python3.7,torch1.1.0,torchvision0.3.0
环境2:python2.7,torch0.4.0,torchvision0.2.0