索引 2D 数组中的每隔一个 2x2 块

Indexing every other 2x2 block in 2D array

假设我有一个看起来像

的数组
array([[ 0,  1,  2,  3,  4,  5,  6,  7],
       [ 8,  9, 10, 11, 12, 13, 14, 15],
       [16, 17, 18, 19, 20, 21, 22, 23],
       [24, 25, 26, 27, 28, 29, 30, 31],
       [32, 33, 34, 35, 36, 37, 38, 39],
       [40, 41, 42, 43, 44, 45, 46, 47],
       [48, 49, 50, 51, 52, 53, 54, 55],
       [56, 57, 58, 59, 60, 61, 62, 63]])

我想提取以下数组:

array([[ 0,  1, 4,  5],
       [ 8,  9, 12, 13],
       [32, 33, 36, 37],
       [40, 41, 44, 45]])

本质上它是每个 4x4 宏块中左上角的 2x2 块。 我在 1D 中看到了 ,但无法弄清楚 2D 的情况。 我能想到的另一种方法是:

h, w = full.shape
X, Y = np.meshgrid(np.arange(w), np.arange(h))
tl = full[(X%4<2) & (Y%4<2)].reshape((h//2,-1))

但我想知道是否有更简洁的方法。

这是您可以做到的一种方法:

In [73]: a
Out[73]: 
array([[ 0,  1,  2,  3,  4,  5,  6,  7],
       [ 8,  9, 10, 11, 12, 13, 14, 15],
       [16, 17, 18, 19, 20, 21, 22, 23],
       [24, 25, 26, 27, 28, 29, 30, 31],
       [32, 33, 34, 35, 36, 37, 38, 39],
       [40, 41, 42, 43, 44, 45, 46, 47],
       [48, 49, 50, 51, 52, 53, 54, 55],
       [56, 57, 58, 59, 60, 61, 62, 63]])

In [74]: nr, nc = [s // 2 for s in a.shape]  # Shape of the new array

In [75]: b = a.reshape((nr, 2, nc, 2))[::2, :, ::2, :].reshape(nr, nc)

In [76]: b
Out[76]: 
array([[ 0,  1,  4,  5],
       [ 8,  9, 12, 13],
       [32, 33, 36, 37],
       [40, 41, 44, 45]])

通过指定索引数组,所以if a.shape[0] % 2 == 0(偶数):

注: 这些方法不仅可以处理a.shape[0] % 4 == 0,还可以处理[=13] =](对于所有偶数)。

第一种方法:

使用高级索引:

w = 2
ind = np.arange(a.shape[1]).reshape(-1, w)[::2].ravel()    # [0 1 4 5]
b = a[ind[:, None], ind[None, :]]

第二种方法:

来自 np.delete:

w = 2
ind = np.arange(a.shape[1]).reshape(-1, w)[1::2].ravel()    # [2 3 6 7]
b = np.delete(a, ind, axis=0)
b = np.delete(b, ind, axis=1)

第三种方法:

通过拆分和堆叠为:

b = np.asarray(np.hsplit(a, a.shape[0] // 2)[::2])

# [[[ 0  1]       [[ 4  5]
#   [ 8  9]        [12 13]
#   [16 17]        [20 21]
#   [24 25]   ,    [28 29]
#   [32 33]        [36 37]
#   [40 41]        [44 45]
#   [48 49]        [52 53]
#   [56 57]]       [60 61]]]

b = np.asarray(np.vsplit(np.hstack(b), a.shape[0] // 2)[::2])

# [[[ 0  1  4  5]
#   [ 8  9 12 13]]
#         ,
#  [[32 33 36 37]
#   [40 41 44 45]]]

b = np.vstack(b).squeeze()