Last active
April 11, 2019 00:58
-
-
Save kevinzakka/0b807675453c7d8cf94bb477834f01fe to your computer and use it in GitHub Desktop.
Rotate a Tensor in PyTorch
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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