【问题标题】:Faster way to extract patches from a tensor?从张量中提取补丁的更快方法?
【发布时间】:2018-10-23 16:44:30
【问题描述】:

我正在尝试提取以某个给定位置 (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 图像。谁能帮我概括一下这个解决方案?

【问题讨论】:

    标签: python performance numpy tensor


    【解决方案1】:

    我们可以利用基于np.lib.stride_tricks.as_stridedscikit-image's view_as_windows 来获得滑动窗口。 More info on use of as_strided based view_as_windows.

    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)
    

    【讨论】:

    • 有效!谢谢!你能解释一下你是怎么解决的吗?
    • @pbellot 请关注代码旁边的 cmets 和链接的问答。
    猜你喜欢
    • 2016-10-20
    • 2020-05-05
    • 1970-01-01
    • 2017-01-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-21
    • 2021-01-20
    相关资源
    最近更新 更多