pythonnumpymultidimensional-arrayarray-indexing

NumPy 3D Array: Get items from a list of 2D co-ordinates


I have a numpy array that looks like follows.

img = [
  [
    [135. 100.  72.],
    [124. 102.  63.],
    [161.  67.  59.],
    [102.  92. 165.],
    [127. 215. 155.]
  ],
  [
    [254. 255. 255.],
    [216. 195. 238.],
    [109. 200. 141.],
    [ 99. 141. 153.],
    [ 55. 200.  95.]
  ],
  [
    [255. 254. 255.],
    [176. 126. 221.],
    [121. 185. 158.],
    [134. 224. 160.],
    [168. 136. 113.]
  ]
]

Then I have another array which looks like follows. I'd like to treat this as a co-ordinates array for the previous one

crds = [
  [1, 3], # Corresponds to [ 99. 141. 153.] in img
  [2, 2] # Corresponds to [121. 185. 158.] in img
]

I need the following result, to be extracted from the img array.

[
  [ 99. 141. 153.],
  [121. 185. 158.]
]

How do I achieve this? Can I do this without iterating?


Solution

  • Assuming two numpy arrays as input:

    img = np.array(img)
    crds = np.array(crds)
    

    you can use:

    img[crds[:,0], crds[:,1]]
    

    output:

    array([[ 99, 141, 153],
           [121, 185, 158]])