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

Time:08-17

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?

CodePudding user response:

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

CodePudding user response:

Apologies if I don't fully understand your question, but you could use indices of your coordinates as indices for your array. For example,

print(img[crds[0, 0], crds[0, 1]])

would print the result of [99 141 153]. and

print(img[crds[1, 0], crds[1, 1]])

would print the result of [121 185 158].

This is my first attempt at answering a question, so I am sorry if I misunderstood.

  • Related