如何将PyTorch张量转换为Numpy ndarray

时间:2020-03-15 22:44:42

标签: python numpy tensorflow computer-vision pytorch

我具有旋转MNIST图像的功能。该函数返回一个pytorch张量。我对Tensorflow更加熟悉,我想将pytorch张量转换为我可以使用的numpy ndarray。有没有可以让我做到的功能?我试图通过在tensor(img.rotate(rotation)).view(784)之后添加.numpy()来稍微修改该函数,并将其保存在一个空的ndarray中,但这没有用。参数d是保存在.pt(我认为是张量)中的MNIST数据。谢谢! (很想知道是否存在可以旋转数据的张量流功能。)

t = 1
min_rot = 1.0 * t / 20 * (180 - 0) + \
        0
max_rot = 1.0 * (t + 1) / 20 * \
    (180 - 0) + 0
rot = random.random() * (max_rot - min_rot) + min_rot
rotate_dataset(x_tr, rot)
def rotate_dataset(d, rotation):
    result = torch.FloatTensor(d.size(0), 784)
    tensor = transforms.ToTensor()

    for i in range(d.size(0)):
        img = Image.fromarray(d[i].numpy(), mode='L')
        result[i] = tensor(img.rotate(rotation)).view(784)
    return result

1 个答案:

答案 0 :(得分:0)

首先不转换为tensor怎么样:

result[i] = np.array(img.rotate(rotation)).flatten()