繁体   English   中英

从张量提取补丁的更快方法?

[英]Faster way to extract patches from a tensor?

我试图提取以某个给定位置(x,y,z)为中心的固定大小的补丁。 代码如下:

x = np.random.randint(0,99,(150, 80, 50, 3))
patch_size = 32
half = int(patch_size//2)
indices = np.array([[40, 20, 30], [60, 30, 27], [20, 18, 21]])
n_patches = indices.shape[0]
patches = np.empty((n_patches, patch_size, patch_size,patch_size, x.shape[-1]))
for ix,_ in enumerate(indices):
   patches[ix, ...] = x[indices[ix, 0]-half:indices[ix, 0]+half,
                        indices[ix, 1]-half:indices[ix, 1]+half,
                        indices[ix, 2]-half:indices[ix, 2]+half, ...]

谁能告诉我如何使这项工作更快? 或任何其他替代方法(如果您可以建议这样做的话)会很有帮助。 我在https://stackoverflow.com/a/37901746/4296850中看到了类似的问题,但仅适用于2D图像。 谁能帮我概括这个解决方案?

我们可以利用np.lib.stride_tricks.as_strided基于scikit-image's view_as_windows得到滑动窗口。 有关使用基于view_as_windowsas_strided的更多信息

from skimage.util.shape import view_as_windows

# Get sliding windows
w = view_as_windows(x,(2*half,2*half,2*half,1))[...,0]

# Get starting indices for indexing along the first three three axes
idx = indices-half

# Use advanced-indexing to index into first 3 axes with idx and a
# final permuting of axes to bring the output format as desired
out = np.moveaxis(w[idx[:,0],idx[:,1],idx[:,2]],1,-1)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM