【问题标题】:How to get all pixs by certain indices from a image array如何通过图像数组中的某些索引获取所有像素
【发布时间】:2021-01-18 07:28:04
【问题描述】:

图像数组的形状是(540, 960, 3),它是这样的:

img_rgb = [[[ 95  71  71]
  [ 95  71  71]
  [ 95  71  71]
  ...
  [182 171 181]
  [182 171 181]
  [182 171 181]]

 [[ 95  71  70]
  [ 95  71  70]
  [ 95  71  71]
  ...
  [183 172 182]
  [183 172 182]
  [183 172 182]]

 [[ 95  72  70]
  [ 95  71  70]
  [ 95  71  71]
  ...
  [183 172 182]
  [183 172 182]
  [183 172 182]]

 ...

 [[ 36  35  45]
  [ 36  35  45]
  [ 36  35  45]
  ...
  [ 49  45  50]
  [ 49  45  50]
  [ 49  45  50]]

 [[ 36  35  45]
  [ 36  35  45]
  [ 36  35  45]
  ...
  [ 49  45  50]
  [ 49  45  50]
  [ 49  45  50]]

 [[ 36  35  45]
  [ 36  35  45]
  [ 36  35  45]
  ...
  [ 49  45  50]
  [ 49  45  50]
  [ 49  45  50]]]

我想通过indices 获取指示每个元素索引的元素,indices 如下所示:

indices = [
 [0, 0], [0, 1], [0, 2]
]

预期输出

[
  [ 95  71  71],
  [ 95  71  71],
  [ 95  71  71],
]

这些链接中有两个类似的问题,一个是Python numpy 2D array sum over certain indices,另一个是Finding the (x,y) indexes of specific (R,G,B) color values from images stored in NumPy ndarrays

当我尝试img_rgb[tuple(indices)] 提出的第一个问题时,它得到了IndexError: too many indices for array

【问题讨论】:

  • 这能回答你的问题吗? Indexing numpy array with another numpy array - 你需要转置:img_rgb[tuple(np.array(indices).T)]
  • @DanielF 或img_rgb[tuple(zip(*indices))]
  • 谢谢,img_rgb[tuple(np.array(indices).T)] 工作。

标签: python arrays numpy


【解决方案1】:

你只需要转置indices

img_rgb[tuple(np.transpose(indices))]

即使indices 只是一个列表,np.tranpose() 也可以工作,因为它期望任何“类数组”结构作为输入。

【讨论】:

  • 这个不太对,输出结果shape是(2, 3, 960, 3),shape应该是(3, 3)
  • @luneice - 很抱歉。现已编辑。
  • 糟糕,在我上当之前,你没发现你已经修好了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-12-19
  • 1970-01-01
相关资源
最近更新 更多