如何将numpy数组拆分为固定大小的块(有无重叠)? [英] How to split a numpy array in fixed size chunks with and without overlap?

查看:318
本文介绍了如何将numpy数组拆分为固定大小的块(有无重叠)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我说我有一个数组:

>>> arr = np.array(range(9)).reshape(3, 3)
>>> arr
array([[0, 1, 2],
       [3, 4, 5],
       [6, 7, 8]])

我想创建一个函数f(arr, shape=(2, 2)),该函数采用数组和形状,并将数组拆分为给定形状的块,而无需填充.因此,如有必要,通过重叠某些部分.例如:

I would like to create a function f(arr, shape=(2, 2)) that takes the array and a shape, and splits the array into chunks of the given shape without padding. Thus, by overlapping certain parts if necessary. For example:

>>> f(arr, shape=(2, 2))
array([[[[0, 1],
         [3, 4]],

        [[1, 2],
         [4, 5]]],

       [[[3, 4],
         [6, 7]],

        [[4, 5],
         [7, 8]]]])

我设法用np.lib.stride_tricks.as_strided(arr, shape=(2, 2, 2, 2), strides=(24, 8, 24, 8))在上面创建了输出.但是我不知道如何将其推广到所有数组和所有块大小.

I managed to creates to output above with np.lib.stride_tricks.as_strided(arr, shape=(2, 2, 2, 2), strides=(24, 8, 24, 8)). But I don't know how to generalize this for to all arrays and all chunk sizes.

最好用于3D阵列.

如果没有必要重叠,则应避免重叠.另一个示例:

If no overlap is necessary, it should avoid that. Another example:

>>> arr = np.array(range(16).reshape(4,4)
>>> arr
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11],
       [12, 13, 14, 15]])
>>> f(arr, shape=(2,2))
array([[[[0, 1],
         [4, 5]],

        [[2, 3],
         [6, 7]]],

       [[[8, 9],
         [12, 13]],

        [[10, 11],
         [14, 15]]]])

skimage.util.view_as_blocks接近,但要求数组和块的形状兼容.

skimage.util.view_as_blocks comes close, but requires that the array and block shape are compatible.

推荐答案

There's a builtin in scikit-image as view_as_windows for doing exactly that -

from skimage.util.shape import view_as_windows

view_as_windows(arr, (2,2))

样品运行-

In [40]: arr
Out[40]: 
array([[0, 1, 2],
       [3, 4, 5],
       [6, 7, 8]])

In [41]: view_as_windows(arr, (2,2))
Out[41]: 
array([[[[0, 1],
         [3, 4]],

        [[1, 2],
         [4, 5]]],


       [[[3, 4],
         [6, 7]],

        [[4, 5],
         [7, 8]]]])


对于第二部分,使用其来自同一个家族/模块的表亲 view_as_blocks -


For the second part, use its cousin from the same family/module view_as_blocks -

from skimage.util.shape import view_as_blocks

view_as_blocks(arr, (2,2))

这篇关于如何将numpy数组拆分为固定大小的块(有无重叠)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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