我想围绕其中心随机旋转图像张量(B、C、H、W)(我认为是二维旋转?)。我想避免使用 NumPy 和 Kornia,这样我基本上只需要从 torch 模块导入。我也没有使用torchvision.transforms
,因为我需要它与 autograd 兼容。本质上,我正在尝试为 DeepDream 等可视化技术创建一个 autograd 兼容版本torchvision.transforms.RandomRotation()
(因此我需要尽可能避免伪影)。
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')
我想要完成的一些示例输出:
神不在的星期二
森林海
慕姐8265434
相关分类