NLi10Me
NLi10Me

Reputation: 3302

Indexing numpy arrays with numpy arrays, in arbitrary dimension

Suppose img is a 2 dimensional numpy array. Suppose also that x and y are integer valued 2 dimensional numpy arrays of the same shape as img. Consider:

newImg = img[x, y]

newImg is now a 2 dimensional array of the same shape as img where newImg[i,j] == img[ x[i,j], y[i,j] ] for all i and j.

I want to generalize this procedure to an arbitrary number of dimensions. That is, let img be a d-dimensional numpy array and take x[i], for i in range(0, d), to be an integer valued d-dimensional numpy array of the same shape as img. What I basically want is:

newImg = img[x[0], x[1], ..., x[d-1]]

Which is obviously pseudocode, and not expected to work.

How can I do this with NumPy?

Upvotes: 2

Views: 209

Answers (1)

wim
wim

Reputation: 363456

Have you tried simply

newImg = img[x]

It looks like this should work!

I'm assuming x is a list or tuple of integer arrays satisfying the following conditions

len(x) == img.ndim
all(a.shape == img.shape for a in x)

which seems to match what you are describing.

Upvotes: 1

Related Questions