如何以随机度数旋转 Torch 张量

How to rotate a Torch Tensor by a random number of degrees

作为训练 CNN 的一部分,我正在使用一个包含 <class 'torch.Tensor'> 个对象的数组 inputs。我想将单个 <class 'torch.Tensor'> 对象旋转某个随机度数 x,如下所示:

def rotate(inputs, x):
    # Rotate inputs[0] by x degrees, x can take on any value from 0 - 180 degrees

我该怎么做?对于现有的实现,我只能发现 torch 具有 rot90 函数,但这将我限制为 90 度的倍数,这对我的场景没有帮助。

谢谢,文尼

要转换 torch.tensor,您可以使用 scipy.ndimage.rotate 函数(阅读 here),它会旋转 torch.tensor,但也会将其转换为 numpy.ndarray ,因此您必须将其转换回 torch.tensor。请参阅这个玩具示例。

函数:

def rotate(inputs, x):
    return torch.from_numpy(ndimage.rotate(inputs, x, reshape=False))

详细解释:

import torch
from scipy import ndimage
alpha = torch.rand(3,3)
print(alpha.dtype)#torch.float32

angle_in_degrees = 45
output = ndimage.rotate(alpha, angle_in_degrees, reshape=False)

print(output.dtype) #numpy_array

output = torch.from_numpy(output) #convert it back to torch tensor

print(output.dtype)  #torch.float32

此外,如果可能的话,您可以在将 PIL 图像转换为张量之前直接对其进行转换。要转换 PIL 图像,您可以使用 PyTorch 内置 torchvision.transforms.functional.rotate(阅读 here)。