1

I want to slice out parts of my array foo multiple times. Currently I am using a for loop which I want to substitute through matrix computation to get a better performance in terms of speed.

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

This is my current approach.

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

I tried to represent the slices as arrays, but I couldn't find the proper representation.

Cœur
  • 37,241
  • 25
  • 195
  • 267
chron0x
  • 875
  • 9
  • 19

1 Answers1

3

We can leverage np.lib.stride_tricks.as_strided based scikit-image's view_as_windows for efficient patch extraction, like so -

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)

Related :

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

Divakar
  • 218,885
  • 19
  • 262
  • 358