How to slice every first 3 values for every 50 value in an array

Viewed 42

I have an array of with 300 pictures of faces of sizes (224, 224, 3), where every 50 image is of the same person. So in total I have 6 persons. What I would like to do is simple create a new array with only 3 images from every person instead of 50, so in total I would have 18 images.

X = np.random.randint(255, size=(300, 224, 224, 3))

I would like to know can I slice the array to grab the first 3 images for in every sequence of 50 frames and grab those first 3 frames and create a new array with those images

I was expecting an array of this shape (18, 224, 224, 3)

1 Answers

You can use boolean indexing:

# get first 3 items every 50 items
out = X[np.arange(X.shape[0])%50<3]

out.shape
# (18, 224, 224, 3)

# check the 4th item in out is the
# 1st of the 2nd person in X
np.allclose(out[3], X[50])
# True
Related