Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/329.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何围绕Pytork图像张量旋转';s中心是否支持自动签名?_Python_Rotation_Pytorch_Image Rotation_Rotational Matrices - Fatal编程技术网

Python 如何围绕Pytork图像张量旋转';s中心是否支持自动签名?

Python 如何围绕Pytork图像张量旋转';s中心是否支持自动签名?,python,rotation,pytorch,image-rotation,rotational-matrices,Python,Rotation,Pytorch,Image Rotation,Rotational Matrices,我想随机旋转一个图像张量(B,C,H,W)围绕它的中心(我想是2d旋转?)。我希望避免使用NumPy和Kornia,因此我基本上只需要从torch模块导入。我也没有使用torchvision.transforms,因为我需要它与自动加载兼容。本质上,我正在尝试创建一个与autograd兼容的版本torchvision.transforms.RandomRotation(),用于像DeepDream这样的可视化技术(因此我需要尽可能避免伪影) 我试图完成的一些示例输出: 因此,电网发生器和采样器是

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

我试图完成的一些示例输出:


因此,电网发生器和采样器是空间变压器的子模块(JADERBERG、Max等)。这些子模块是不可训练的,它们允许您应用可学习和不可学习的空间变换。 在这里,我使用这两个子模块,使用PyTorch的函数
F.affine_grid
F.affine_sample
(这些函数分别是生成器和采样器的实现)将图像旋转
theta

在上面的例子中,假设我们把我们的图像,
im
,想象成一只穿着裙子跳舞的猫:

rotated_im
将是一只穿着裙子的逆时针旋转90度的舞猫:

这就是如果我们用θ调用
rot\u img
,得到的结果


最好的部分是,它是可微的w.r.t的输入和有自动标签的支持!万岁

有一个pytorch函数:

x=torch.tensor([[0,1],
[2, 3]])
x=火炬旋转90(x,1,[0,1])

以下是文档:

我建议您看看空间变压器,特别是电网发电机和采样器模块。有关实现的详细信息,请参阅。@GilPinsky,这似乎与创建可训练层有关。我将只优化单个图像/张量,并使用旋转来帮助优化。我想指出的是,kornia完全依赖于Pytork,因此不会有任何额外的依赖性,但这只允许您旋转90度、180度或270度……谢谢,您的代码运行得非常好!但是,我应该如何处理跨批次维度堆叠的多个图像?我应该使用相同的旋转矩阵单独执行每项操作,还是可以稍微修改它,使其在没有for语句的情况下工作?我很高兴:),我刚刚更新了代码,以便它也可以跨批处理维度工作。您只需在
rot\u img
中使用
.repeat(x.shape[0],1,1)
来重复旋转矩阵,使其具有与x相同的批处理维度。先生,请您在回答中解释旋转一个灰度图像的方法好吗?@ToughMind这应该也适用于单个灰度图像。只需确保图像(im)具有适当的尺寸:1 x 1 x H x W,其中H和W分别是高度和宽度。
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')
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)
>> tensor([[1, 3],
           [0, 2]])