python - 如何以支持 autograd 的方式围绕其中心旋转 PyTorch 图像张量?

标签 python rotation pytorch image-rotation rotational-matrices

我想围绕它的中心随机旋转图像张量(B、C、H、W)(我认为是 2d 旋转?)。我想避免使用 NumPy 和 Kornia,这样我基本上只需要从 torch 模块导入。我也没有使用 torchvision.transforms ,因为我需要它与 autograd 兼容。本质上,我正在尝试创建一个与 autograd 兼容的版本 torchvision.transforms.RandomRotation()对于像 DeepDream 这样的可视化技术(所以我需要尽可能避免伪像)。

import torch
import math
import random
import torchvision.transforms as transforms
from PIL import Image


# Load image
def preprocess_simple(image_name, image_size):
    Loader = transforms.Compose([transforms.Resize(image_size), transforms.ToTensor()])
    image = Image.open(image_name).convert('RGB')
    return Loader(image).unsqueeze(0)
    
# Save image   
def deprocess_simple(output_tensor, output_name):
    output_tensor.clamp_(0, 1)
    Image2PIL = transforms.ToPILImage()
    image = Image2PIL(output_tensor.squeeze(0))
    image.save(output_name)


# Somehow rotate tensor around it's center
def rotate_tensor(tensor, radians):
    ...
    return rotated_tensor

# Get a random angle within a specified range 
r_degrees = 5
angle_range = list(range(-r_degrees, r_degrees))
n = random.randint(angle_range[0], angle_range[len(angle_range)-1])

# Convert angle from degrees to radians
ang_rad = angle * math.pi / 180


# test_tensor = preprocess_simple('path/to/file', (512,512))
test_tensor = torch.randn(1,3,512,512)


# Rotate input tensor somehow
output_tensor = rotate_tensor(test_tensor, ang_rad)


# Optionally use this to check rotated image
# deprocess_simple(output_tensor, 'rotated_image.jpg')
我试图完成的一些示例输出:
First example of rotated image Second example of rotated image

最佳答案

所以网格生成器和采样器是空间更改器(mutator)(JADERBERG、Max 等)的子模块。这些子模块是不可训练的,它们让您可以应用可学习和不可学习的空间转换。
在这里,我使用这两个子模块并使用它们将图像旋转 theta使用 PyTorch 的函数 F.affine_gridF.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 ,做一只穿裙子的舞猫:
enter image description hererotated_im将是一只穿着裙子的逆时针旋转 90 度旋转舞猫:
enter image description here
这就是我们调用 rot_img 时得到的结果与 theta等于 np.pi/4 :
enter image description here
最好的部分是它可以区分输入并具有 autograd 支持!万岁!

关于python - 如何以支持 autograd 的方式围绕其中心旋转 PyTorch 图像张量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64197754/

相关文章:

python - 如何等待 elasticsearch helpers.reindex 在 Python 中完成?

python - 计算数据框中每一行和特定列在列表中的出现次数

jupyter-notebook - 使用pytorch时无法在jupyter笔记本中导入 'torchtext'模块

python - 如何使用PyTorch计算偏导数?

python - matplotlib 的 xkcd() 不工作

Python - 任务计划程序 0x1

javascript - CSS 在容器内旋转元素

android - 关闭 fragment 中的自动旋转

jquery - 将图像旋转 360 度

python - 如何有效地标准化张量中的元素组