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

Viewed 3980

as part of training a CNN, I am working with an array inputs that contain <class 'torch.Tensor'> objects. I want to rotate an individual <class 'torch.Tensor'> object by some random number of degrees x, as shown here:

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

How can I do this? For existing implementations, I can only find that torch has a rot90 function, but that limits me to multiples of 90 degrees which does not help my scenario.

Thanks, Vinny

1 Answers

To transform an torch.tensor you can use scipy.ndimage.rotate function (read here),that rotates a torch.tensor but also it converts it to numpy.ndarray, so you have to convert it back to torch.tensor. See this toy example.

Function:

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

Detailed explanation:

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

Also, You can directly transform PIL image before converting it to tensor if that's a possibility. To transform PIL image you can use PyTorch builtin torchvision.transforms.functional.rotate (read here).

Related