如何重建滤波后的2D阵列的线性索引



假设我有以下numpy数组

>>> arr = np.array([[0,1,0,1],
[0,0,0,1],
[1,0,1,0]])

其中CCD_ 1的值指示";有效的";CCD_ 2的值和值表示";无效";价值观接下来,假设我过滤掉无效的1值,如下所示:

>>> mask = arr == 1
>>> arr_filt = arr[~mask]
array([0, 0, 0, 0, 0, 0, 0])

如果我想从原始arr中有效值(0(的线性索引到新过滤的arr_filt中相同值的线性索引,我可以如下进行:

# record the cumulative total number of invalid values
num_invalid_prev = np.cumsum(mask.flatten())
# example of going from the linear index of a valid value in the
# original array to the linear index of the same value in the
# filtered array
ij_idx = (0,2)
linear_idx_orig = np.ravel_multi_index(ij_idx,arr.shape)
linear_idx_filt = linear_idx_orig - num_invalid_prev[linear_idx_orig]

然而,我有兴趣走另一条路。也就是说,给定滤波后的arr_filt和相同的num_invalid_prev数组中有效值的线性索引,我可以在未滤波的arr中取回相同有效值的直线索引吗?

您可以使用00获取索引:

ix = np.c_[np.nonzero(~mask)]
>>> ix
array([[0, 0],
[0, 2],
[1, 0],
[1, 1],
[1, 2],
[2, 1],
[2, 3]])

然后,例如,您可以查找第二个有效值的索引:

>>> tuple(ix[1])
(0, 2)
>>> arr[tuple(ix[1])]
0

最新更新