3 回答

TA貢獻1963條經驗 獲得超6個贊
因此,網格生成器和采樣器是 Spatial Transformer 的子模塊(JADERBERG、Max 等人)。這些子模塊不可訓練,它們可讓您應用可學習的以及不可學習的空間變換。theta在這里,我使用這兩個子模塊,并使用 PyTorch 的函數torch.nn.functional.affine_grid和(這些函數分別是生成器和采樣器的實現)來旋轉圖像torch.nn.functional.affine_sample:
import torch
import torch.nn.functional as F
import numpy as np
import matplotlib.pyplot as plt
def get_rot_mat(theta):
theta = torch.tensor(theta)
return torch.tensor([[torch.cos(theta), -torch.sin(theta), 0],
[torch.sin(theta), torch.cos(theta), 0]])
def rot_img(x, theta, dtype):
rot_mat = get_rot_mat(theta)[None, ...].type(dtype).repeat(x.shape[0],1,1)
grid = F.affine_grid(rot_mat, x.size()).type(dtype)
x = F.grid_sample(x, grid)
return x
#Test:
dtype = torch.cuda.FloatTensor if torch.cuda.is_available() else torch.FloatTensor
#im should be a 4D tensor of shape B x C x H x W with type dtype, range [0,255]:
plt.imshow(im.squeeze(0).permute(1,2,0)/255) #To plot it im should be 1 x C x H x W
plt.figure()
#Rotation by np.pi/2 with autograd support:
rotated_im = rot_img(im, np.pi/2, dtype) # Rotate image by 90 degrees.
plt.imshow(rotated_im.squeeze(0).permute(1,2,0)/255)
在上面的示例中,假設我們將圖像im視為一只穿著裙子跳舞的貓:
rotated_im
將是一只穿著裙子逆時針旋轉 90 度的跳舞貓:
如果我們用rot_img
等號theta
調用,就會得到以下結果np.pi/4
:
最好的部分是它可以區分輸入并具有 autograd 支持!萬歲!

TA貢獻2011條經驗 獲得超2個贊
使用 torchvision 應該很簡單:
import torchvision.transforms.functional as TF
angle = 30
x = torch.randn(1,3,512,512)
out = TF.rotate(x, angle)
例如如果x是:
out
旋轉 30 度為(注:逆時針):

TA貢獻1813條經驗 獲得超2個贊
pytorch 有一個函數:
x = torch.tensor([[0, 1], [2, 3]]) x = torch.rot90(x, 1, [0, 1])
>> tensor([[1, 3], [0, 2]])
以下是文檔:https://pytorch.org/docs/stable/ generated/torch.rot90.html
添加回答
舉報