如何将 PyTorch Tensor 转换为 Numpy 的 ndarray?

How can I convert PyTorch Tensor to ndarray of Numpy?

我的张量的形状是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)

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

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

我找到了另一个解决方案

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