F.grid_sample

本文通过示例详细解析了PyTorch中的torch.nn.functional.grid_sample函数使用方法,特别是grid参数设置及其与输入张量之间的关系。通过具体代码演示了如何将坐标转换为符合该函数要求的[-1,1]区间内,并展示了如何获取特定位置的像素值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

torch.nn.functional.grid_sample()函数的参数grid,表示的是范围为[-1, 1]坐标系下的(x, y, z),坐标与数组的对应关系是:

x -> w, y -> h, z -> d,测试代码如下:

 
  1. import numpy as np

  2. from torch.nn import functional as F

  3. import torch

  4.  
  5. if __name__ == '__main__':

  6. d, h, w = 8, 10, 12

  7. input = torch.zeros((2, 1, 8, 10, 12), dtype=torch.float32)

  8. input[:, 0, 2, 3, 4] = 1

  9. grid = torch.zeros((2, 1, 1, 1, 3), dtype=torch.float32)

  10. x, y, z = 4, 3, 2 # 对应input的w, h, d

  11. # rescale to [-1, 1]

  12. x = 2. * x / (w - 1) - 1.

  13. y = 2. * y / (h - 1) - 1.

  14. z = 2. * z / (d - 1) - 1.

  15. grid[0, 0, 0, 0, :] = torch.from_numpy(np.array([x, y, z]).astype(np.float32))

  16. grid[1, 0, 0, 0, :] = torch.from_numpy(np.array([x, y, z]).astype(np.float32))

  17. out = F.grid_sample(input, grid, mode='nearest')

  18. print(out)###torch.Size([2, 1, 1, 1, 1])

可以看到输出为:

tensor([[[[[1.]]]],

        [[[[1.]]]]])

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值