【发布时间】:2021-03-30 13:44:49
【问题描述】:
如何用未知的值和大小裁剪张量的恒定值填充(填充高度和宽度相同)?
我认为,因为我的张量周围的填充具有恒定值和相同的高度/宽度,所以应该可以知道在哪里裁剪张量以移除填充。
import torch
# Test tensor with NCHW dimensions
a = torch.randn(1,4,5,5) # Can have any H & W size
# Create padding for testing
b = torch.nn.functional.pad(a, (2,2,2,2), 'constant', value=1.2) # Value can be any number
c = # equal to a, without being able to use the variables a or b (or their argument values)
NumPy 解决方案是可以接受的,因为我可以轻松地将它们转换为 PyTorch。
编辑:
pad = torch.where(b[0, 0] - b[0, 0, 0, 0] != 0)[0][0]
x_pad, y_pad = 0, 0
if (b.size(3) % 2) == 0:
x_pad = 1
if (b.size(2) % 2) == 0:
y_pad = 1
c = b[:, :, pad : -(pad + y_pad), pad : -(pad + x_pad)]
assert c == a
【问题讨论】:
标签: python numpy pytorch padding crop