Skip to content

Instantly share code, notes, and snippets.

@kevinzakka
Last active April 11, 2019 00:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kevinzakka/0b807675453c7d8cf94bb477834f01fe to your computer and use it in GitHub Desktop.
Save kevinzakka/0b807675453c7d8cf94bb477834f01fe to your computer and use it in GitHub Desktop.
Rotate a Tensor in PyTorch
import numpy as np
import torch
import torch.nn.functional as F
def rotz(theta):
return np.array([
[np.cos(theta), -np.sin(theta), 0],
[np.sin(theta), np.cos(theta), 0],
[0, 0, 1],
], dtype="float64")
device = torch.device("cuda")
x = torch.rand(5, 3, 200, 200).to(device)
angle = np.deg2rad(7)
rotm = rotz(angle)[:2, :].reshape(2, 3, 1)
rotm = torch.FloatTensor(rotm).permute(2, 0, 1).repeat(x.shape[0], 1, 1)
affine_grid = F.affine_grid(rotm, x.size()).to(device)
with torch.no_grad():
x_r = F.grid_sample(x, affine_grid)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment