pytorch grid_sample易错点

易错点是:
grid_sample函数中, x对应w, y对应h !!
grid_sample函数中, x对应w, y对应h !!
grid_sample函数中, x对应w, y对应h !!
函数的作用
output的size和grid的size是一样的,所以output中某一位置(h, w)的值,是根据grid的同一位置(h,w)提供的index信息去input中寻找。如果input的网格中存在这个索引,直接赋值。若不存在,则进行插值计算。

例子
先看一个错误的例子
import torch
inp = torch.arange(3*3).view(1, 1, 3, 3).float()
d = torch.linspace(-1, 1, 3)
meshx, meshy = torch.meshgrid((d, d), indexing = "ij")
grid = torch.stack((meshx, meshy), 2).unsqueeze(0)
output = torch.nn.functional.grid_sample(inp, grid, align_corners=True)
print(inp)
print(meshx)
print(meshx)
print(output)

output是input的转置
那么如果想得到非转置的结果,就要将grid更改一下
import torch
inp = torch.arange(3*3).view(1, 1, 3, 3).float()
d = torch.linspace(-1, 1, 3)
meshx, meshy = torch.meshgrid((d, d), indexing = "ij")
grid = torch.stack((meshy, meshx), 2).unsqueeze(0)
output = torch.nn.functional.grid_sample(inp, grid, align_corners=True)
print(inp)
print(meshx)
print(meshx)
print(output)

文章详细解释了在PyTorch的grid_sample函数中,x对应宽度(w),y对应高度(h)这一常见错误。该函数按照grid提供的索引信息从input中获取值,如果索引超出范围,则进行插值。示例代码展示了如何通过调整grid的顺序来避免得到转置的结果。

905

被折叠的 条评论
为什么被折叠?



