Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

There is a 2-d array like this:

img = [
  [[1, 2, 3], [4, 5, 6], [7, 8, 9]],
  [[2, 2, 2], [3, 2, 3], [6, 7, 6]],
  [[9, 8, 1], [9, 8, 3], [9, 8, 5]]
]

And i just want to get the sum of certain indices which are like this:

indices = [[0, 0], [0, 1]] # which means img[0][0] and img[0][1]
# means here is represents

There was a similar ask about 1-d array in stackoverflow in this link, but it got a error when I tried to use print(img[indices]). Because I want to make it clear that the element of img are those which indicates by indices, and then get the mean sum of it.

Expected output

[5, 7, 9]
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
256 views
Welcome To Ask or Share your Answers For Others

1 Answer

Use NumPy:

import numpy as np

img = np.array(img)
img[tuple(indices)].sum(axis = 0)
#array([5, 7, 9])

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...