https://blog.csdn.net/qq_34914551/article/details/107559031
import torch
from torch.nn import functional as F
inp = torch.ones(1, 1, 4, 4)
# 目的是得到一个 长宽为20的tensor
out_h = 20
out_w = 20
# grid的生成方式等价于用mesh_grid
# 这里是直接生成的[-1,1]的grid坐标,在实际应用中需要把图像的对应像素坐标统一到[-1,1]
new_h = torch.linspace(-1, 1, out_h).view(-1, 1).repeat(1, out_w)
print("new_h shape:",new_h.shape)
print(new_h) # new_h shape: torch.Size([20, 20])
new_w = torch.linspace(-1, 1, out_w).repeat(out_h, 1)
print("new_w shape:", new_w.shape)
print(new_w) #new_w shape: torch.Size([20, 20])
grid = torch.cat((new_h.unsqueeze(2), new_w.unsqueeze(2)), dim=2)
print(grid.shape) #torch.Size([20, 20, 2])
grid = grid.unsqueeze(0)
print(grid.shape) # torch.Size([1, 20, 20, 2])
outp = F.grid_sample(inp, grid=grid, mode='bilinear')
print(outp.shape) #torch.Size([1, 1, 20, 20])