torch.nn.functional.grid_sample()函数的参数grid,表示的是范围为[-1, 1]坐标系下的(x, y, z),坐标与数组的对应关系是:
x -> w, y -> h, z -> d,测试代码如下:
import numpy as np
from torch.nn import functional as F
import torch
if __name__ == '__main__':
d, h, w = 8, 10, 12
input = torch.zeros((2, 1, 8, 10, 12), dtype=torch.float32)
input[:, 0, 2, 3, 4] = 1
grid = torch.zeros((2, 1, 1, 1, 3), dtype=torch.float32)
x, y, z = 4, 3, 2 # 对应input的w, h, d
# rescale to [-1, 1]
x = 2. * x / (w - 1) - 1.
y = 2. * y / (h - 1) - 1.
z = 2. * z / (d - 1) - 1.
grid[0, 0, 0, 0, :] = torch.from_numpy(np.array([x, y, z]).astype(np.float32))
grid[1, 0, 0, 0, :] = torch.from_numpy(np.array([x, y, z]).astype(np.float32))
out = F.grid_sample(input, grid, mode='nearest')
print(out)
可以看到输出为:
tensor([[[[[1.]]]],
[[[[1.]]]]])
本文详细解析了PyTorch中grid_sample函数的工作原理,重点介绍了如何使用该函数进行坐标转换,并通过实例展示了其在3D张量上的应用过程。
952

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



