np.ndarray转为torch.Tensor
在深度学习中,原始图像需要转换为深度学习框架自定义的数据格式,在pytorch中,需要转为torch.Tensor。
pytorch提供了torch.Tensor 与numpy.ndarray转换为接口
| 方法名 | 作用 |
torch.from_numpy(xxx) |
numpy.ndarray转为torch.Tensor |
tensor1.numpy() |
获取tensor1对象的numpy格式数据 |
torch.Tensor 高维矩阵的表示: N x C x H x W
numpy.ndarray 高维矩阵的表示:N x H x W x C
因此在两者转换的时候需要使用numpy.transpose( ) 方法 。
def imshow(img): img = img / 2 + 0.5 img = np.transpose(img.numpy(),(1,2,0)) plt.imshow(img)