Numpy array indexing with another matrix

Thompson Liu

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!

Warren Weckesser

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]]])

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related