简体   繁体   English

如何创建用于重新缩放 PyTorch 张量的缩放矩阵,然后如何使用它?

[英]How do I create a scale matrix for rescaling a PyTorch tensor, and then how do I use it?

I need to create a scale matrix that is autograd compatible, works on B,C,H,W tensors, and takes input values (possibly generated randomly) for controlling the scaling.我需要创建一个与 autograd 兼容的缩放矩阵,适用于 B、C、H、W 张量,并采用输入值(可能随机生成)来控制缩放。 How can I generate and use a scale matrix for this?如何为此生成和使用比例矩阵?

import torch
import torch.nn.functional as F
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)


def get_scale_mat(theta):
    ...
    return scale_mat


def scale_img(x, theta, dtype):
    scale_mat = get_scale_mat(theta)

    # Can F.affine_grid & F.grid_sample be used with a scale matrix?
    grid = F.affine_grid(scale_mat , x.size()).type(dtype)
    x = F.grid_sample(x, grid)
    return x


# Shear tensor
test_input = # Test image
scale = 5 # Example value
scaled_tensor = scale_img(test_input, scale)

This is how you create and use a 3x2 scale matrix with F.affine_grid and F.grid_sample:这是创建和使用带有 F.affine_grid 和 F.grid_sample 的 3x2 比例矩阵的方法:

def get_scale_mat(m, device, dtype):
    scale_mat = torch.tensor([[m, 0., 0.],
                              [0., m, 0.]])
    return scale_mat
    
def scale_tensor(x, scale):
    assert scale > 0
    scale_matrix = get_scale_mat(scale, x.device, x.dtype)[None, ...].repeat(x.shape[0],1,1)                                        
    grid = F.affine_grid(scale_matrix, x.size())
    x = F.grid_sample(x, grid)
    return x

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM