Home > Software design >  Slicing of 3-dimensional numpy.ndarray along one axis with gaps
Slicing of 3-dimensional numpy.ndarray along one axis with gaps

Time:10-08

I've got a video sequence, saved in 3-dimensional numpy array.

import numpy as np
noise_50 = np.ones((422, 480, 640), dtype=np.float)

I want to remove frames 0:25, 231:272, 372:421 and keep frames 26:231 and 273:371.

Is it possible to do with slice objects in one operation?

I've seen the question Python: shorter syntax for slices with gaps? but it considers only 1-dimensional arrays.

If I try s_ from index tricks, as suggested there, it broadcasts second slice to the next axis and crops frames

retain = np.s_[26:230, 273:371]
n_50 = noise_50[retain]
n_50.shape

>>> (204, 98, 640)
     ^^^  ^^ - should be 303, 480

I also cannot create sum of slices

retain = slice(26, 230)   slice(273, 371)

> TypeError: unsupported operand type(s) for  : 'slice' and 'slice'

CodePudding user response:

Hey there is sort of a way of doing it in one operation. Numpy allows you to pass in a list/array of indices to a dimension of the slice. So all you need to do is join some ranges that you want to keep and pass that into the first dim. Like in the example below that outputs New shape (303, 480, 640)

import numpy as np

def mslice(data, ranges):
    d = np.concatenate([np.arange(*r, step=1) for r in ranges])
    return data[d, :, :]

# some dummy frame data
frames = np.zeros((422, 480, 640))
keep = mslice(frames, [(26, 231), (273, 371)])

print('New shape', keep.shape)
  • Related