如何将PyTorch张量转换为Numpy的ndarray?

时间:2020-11-12 16:33:32

标签: numpy pytorch reshape numpy-ndarray

张量的形状为torch.Size([3, 320, 480])

张量是

tensor([[[0.2980, 0.4353, 0.6431,  ..., 0.2196, 0.2196, 0.2157],
         [0.4235, 0.4275, 0.5569,  ..., 0.2353, 0.2235, 0.2078],
         [0.5608, 0.5961, 0.5882,  ..., 0.2314, 0.2471, 0.2588],
         ...,

         ...,
         [0.0588, 0.0471, 0.0784,  ..., 0.0392, 0.0471, 0.0745],
         [0.0275, 0.1020, 0.1882,  ..., 0.0196, 0.0157, 0.0471],
         [0.1569, 0.2353, 0.2471,  ..., 0.0549, 0.0549, 0.0627]]])

我需要形状为320、480、3的东西

因此,张量应该看起来像这样

array([[[0.29803923, 0.22352941, 0.10980392],
        [0.43529412, 0.34117648, 0.20784314],
        [0.6431373 , 0.5254902 , 0.3764706 ],
        ...,

        ...,
        [0.21960784, 0.13333334, 0.05490196],
        [0.23529412, 0.14509805, 0.05490196],
        [0.2627451 , 0.1764706 , 0.0627451 ]]], dtype=float32)

2 个答案:

答案 0 :(得分:1)

首先使用.cpu()将设备更改为主机/ cpu(如果在cuda上),然后使用.detach()将其与计算图分离,然后使用.numpy()转换为numpy

t = torch.tensor(...).reshape(320, 480, 3)
numpy_array = t.cpu().detach().numpy()

答案 1 :(得分:0)

我为我找到了另一种解决方法

t = torch.tensor(...).permute(1, 2, 0).numpy()