Home > Mobile >  Numpy array indexing with another matrix
Numpy array indexing with another matrix

Time:10-23

I looked into other posts related to indexing numpy array with another numpy array, but still could not wrap my head around to accomplish the following:

a = [[[1,2,3],[4,5,6]],[[7,8,9],[10,11,12]]],
b = [[[1,0],[0,1]],[[1,1],[0,1]]]
a[b] = [[[7,8,9],[4,5,6]],[[10,11,12],[4,5,6]]]

a is an image represented by 3D numpy array, with dimension 2 * 2 * 3 with RGB values for the last dimension. b contains the index that will match to the image. For instance for pixel index (0,0), it should map to index (1,0) of the original image, which should give pixel values [7,8,9]. I wonder if there's a way to achieve this. Thanks!

CodePudding user response:

Here's one way:

In [54]: a = np.array([[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]])

In [55]: b = np.array([[[1, 0], [0, 1]], [[1, 1], [0, 1]]])

In [56]: a[b[:, :, 0], b[:, :, 1]]
Out[56]: 
array([[[ 7,  8,  9],
        [ 4,  5,  6]],

       [[10, 11, 12],
        [ 4,  5,  6]]])
  • Related