将二维数组切成更小的二维数组 [英] Slice 2d array into smaller 2d arrays

查看:73
本文介绍了将二维数组切成更小的二维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法将 numpy 中的二维数组切成更小的二维数组?

Is there a way to slice a 2d array in numpy into smaller 2d arrays?

示例

[[1,2,3,4],   ->    [[1,2] [3,4]   
 [5,6,7,8]]          [5,6] [7,8]]

所以我基本上想把一个 2x4 的数组切成 2 个 2x2 的数组.寻找用于图像的通用解决方案.

So I basically want to cut down a 2x4 array into 2 2x2 arrays. Looking for a generic solution to be used on images.

推荐答案

几个月前有另一个问题这让我想到了使用 reshapeswapaxes 的想法.h//nrows 是有意义的,因为这将第一个块的行保持在一起.您需要 nrowsncols 作为形状的一部分也是有道理的.-1 告诉 reshape 填写使 reshape 有效所需的任何数字.凭借解决方案的形式,我只是尝试了一些事情,直到找到有效的公式.

There was another question a couple of months ago which clued me in to the idea of using reshape and swapaxes. The h//nrows makes sense since this keeps the first block's rows together. It also makes sense that you'll need nrows and ncols to be part of the shape. -1 tells reshape to fill in whatever number is necessary to make the reshape valid. Armed with the form of the solution, I just tried things until I found the formula that works.

您应该能够将数组分成块";使用 reshapeswapaxes 的某种组合:

You should be able to break your array into "blocks" using some combination of reshape and swapaxes:

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, f"{h} rows is not evenly divisible by {nrows}"
    assert w % ncols == 0, f"{w} cols is not evenly divisible by {ncols}"
    return (arr.reshape(h//nrows, nrows, -1, ncols)
               .swapaxes(1,2)
               .reshape(-1, nrows, ncols))

c

np.random.seed(365)
c = np.arange(24).reshape((4, 6))
print(c)

[out]:
[[ 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))

[out]:
[[[ 0  1  2]
  [ 6  7  8]]

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

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

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


我发布了一个反函数,unblockshape,这里,还有一个 N-维度概括此处.泛化让我们更深入地了解该算法背后的推理.


I've posted an inverse function, unblockshaped, here, and an N-dimensional generalization here. The generalization gives a little more insight into the reasoning behind this algorithm.

请注意,还有 superbatfish 的blockwise_view.它安排了不同格式的块(使用更多轴)但它具有(1)的优点总是返回一个视图并且 (2) 能够处理任何数组维度.

Note that there is also superbatfish's blockwise_view. It arranges the blocks in a different format (using more axes) but it has the advantage of (1) always returning a view and (2) being capable of handling arrays of any dimension.

这篇关于将二维数组切成更小的二维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆