您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

将2D阵列切成较小的2D阵列

将2D阵列切成较小的2D阵列

你应该能够打破你的数组转换成“块”使用的一些组合reshapeswapaxes

def blockshaped(arr, nrows, ncols):
    """
    Return an array of shape (n, nrows, ncols) where
    n * nrows * ncols = arr.size

    If arr is a 2D array, the returned array should look like n subblocks with
    each subblock preserving the "physical" layout of arr.
    """
    h, w = arr.shape
    assert h % nrows == 0, "{} rows is not evenly divisble by {}".format(h, nrows)
    assert w % ncols == 0, "{} cols is not evenly divisble by {}".format(w, ncols)
    return (arr.reshape(h//nrows, nrows, -1, ncols)
               .swapaxes(1,2)
               .reshape(-1, nrows, ncols))

转弯 c

c = np.arange(24).reshape((4,6))
print(c)
# [[ 0  1  2  3  4  5]
#  [ 6  7  8  9 10 11]
#  [12 13 14 15 16 17]
#  [18 19 20 21 22 23]]

进入

print(blockshaped(c, 2, 3))
# [[[ 0  1  2]
#   [ 6  7  8]]

#  [[ 3  4  5]
#   [ 9 10 11]]

#  [[12 13 14]
#   [18 19 20]]

#  [[15 16 17]
#   [21 22 23]]]

我已经张贴了[反函数unblockshaped在这里](http://codingdict.com/questions/164064,和N维泛化这里。泛化使该算法背后的原因有了更多的了解。

注意,还有超级蝙蝠blockwise_view鱼的。它以不同的格式(使用更多的轴)排列块,但是它的优点是(1)始终返回视图,并且(2)能够处理任何尺寸的数组。

其他 2022/1/1 18:43:48 有439人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶