Numpy矩阵的高级索引功能。

根据用户手册,numpy数组支持数组索引。返回的数组与索引数组具有相同的形状,与原数组元素具有相同的类型和值(被索引位置)。针对你的问题,也就是你理解的:返回的还是一个二维数组,返回数组的值是以二维数组每个元素作为一维数组索引在一维数组中的值。

Generally speaking, what is returned when index arrays are used is an array with the same shape as the index array, but with the type and values of the array being indexed.

以二维数组为例:

>>> import numpy as np
>>> x = np.arange(12).reshape(3,4)
>>> x
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11]])

>>> rows = np.array([[0,0], [1,2]])
>>> cols = np.array([[1,2], [2,3]])

>>> x[rows, cols]
array([[ 1,  2],
       [ 6, 11]])

因为二维数组有两个维度,所以需要两个索引数组,rowscols (要求形状一致或者能广播成相同的形状)

  • 索引数组的形状 2x2决定了返回数组的形状
  • 各维度的索引值索引原数组的元素,rows的第一个元素0cols的第一个元素1组成二维数组的索引(0,1),索引原数组的值1;其余位置依次类推。

更多索引相关知识可以参考官方文档:

如果用二维矩阵作为一维数组的索引的话,则是将二维数组中的值对应在一维数组中的索引值赋值给二维数组,并返回和二维数组大小相同,且数据类型和一维数组相同的矩阵。
其中最为经典的用法是图像的直方图均衡话算法。
# calculate histogram
hists = histogram(img)

# caculate cdf
hists_cumsum = np.cumsum(hists)
const_a = level / (m * n)
hists_cdf = (const_a * hists_cumsum).astype("uint8")

# mapping
img_eq = hists_cdf[img]

hists_cdf 作为像元值的映射函数,其中记录了每个像元值在均衡化后应该映射到哪个像元值。

其作用是将图像的像元值修改为每个像元值对应在hists_cdf的映射值。

>>> array
array([1, 2, 3, 4, 5, 6, 7, 8], dtype=uint8)
>>> index_array
array([[0, 1, 2],
[3, 4, 5]], dtype=uint8)
>>> array[index_array]
array([[1, 2, 3],
[4, 5, 6]], dtype=uint8)

 
posted @ 2021-04-04 21:12  Anm半夏  阅读(590)  评论(0编辑  收藏  举报