【问题标题】:Multidimensional Slicing多维切片
【发布时间】:2018-09-04 04:14:36
【问题描述】:

我想多次切出数组foo 的一部分。目前我正在使用一个 for 循环,我想通过矩阵计算来代替它以获得更好的速度性能。

foo = np.arange(6000).reshape(6,10,10,10)
target = np.zeros((100,6,3,4,5))
startIndices = np.random.randint(5, size=(100))

这是我目前的方法。

for i in range(len(target)):
    startIdx=startIndices[i]
    target[i, :]=foo[:, startIdx:startIdx+3,
                        startIdx:startIdx+4,
                        startIdx:startIdx+5]

我尝试将切片表示为数组,但找不到合适的表示。

【问题讨论】:

    标签: arrays python-2.7 performance numpy slice


    【解决方案1】:

    我们可以利用基于scikit-image's view_as_windowsnp.lib.stride_tricks.as_strided 进行有效的补丁提取,就像这样 -

    from skimage.util.shape import view_as_windows
    
    # Get sliding windows (these are simply views)
    WSZ = (1,3,4,5) # window sizes along the axes
    w = view_as_windows(foo,WSZ)[...,0,:,:,:]
    
    # Index with startIndices along the appropriate axes for desired output
    out = w[:,startIndices, startIndices, startIndices].swapaxes(0,1)
    

    相关:

    NumPy Fancy Indexing - Crop different ROIs from different channels

    Take N first values from every row in NumPy matrix that fulfill condition

    Selecting Random Windows from Multidimensional Numpy Array Rows

    how can I extract multiple random sub-sequences from a numpy array

    【讨论】:

      猜你喜欢
      • 2020-03-11
      • 2018-01-09
      • 2020-05-03
      • 2021-11-23
      • 2014-08-25
      • 2014-01-31
      • 1970-01-01
      • 2013-02-01
      相关资源
      最近更新 更多