Numpy. 如何按照网格将2D数组拆分为多个数组?

huangapple go评论82阅读模式
英文:

Numpy. How to split 2D array to multiple arrays by grid?

问题

我有一个numpy的二维数组:

c = np.arange(36).reshape(6, 6)

[[ 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]]

我想要按3x3的网格将它拆分成多个二维数组(就像将大图像按3x3的网格拆分为9个小图像):

[[ 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]]

最后,我需要一个包含9个二维数组的数组,如下所示:

[[[0, 1], [6, 7]], 
 [[2, 3], [8, 9]],
 [[4, 5], [10, 11]],
 [[12, 13], [18, 19]],
 [[14, 15], [20, 21]],
 [[16, 17], [22, 23]],
 [[24, 25], [30, 31]],
 [[26, 27], [32, 33]],
 [[28, 29], [34, 35]]]

这只是我需要的一个示例。我想知道如何通过网格(N,M)从大的二维数组中制作小的二维数组。

英文:

I have a numpy 2D-array:

c = np.arange(36).reshape(6, 6)

[[ 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]]

I want to split it to multiple 2D-arrays by grid 3x3. (It's like a split big image to 9 small images by grid 3x3):

[[ 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]]

At final i need array with 9 2D-arrays. Like this:

[[[0, 1], [6, 7]], 
 [[2, 3], [8, 9]],
 [[4, 5], [10, 11]],
 [[12, 13], [18, 19]],
 [[14, 15], [20, 21]],
 [[16, 17], [22, 23]],
 [[24, 25], [30, 31]],
 [[26, 27], [32, 33]],
 [[28, 29], [34, 35]]]

It's just a sample what i need. I want to know how to make small 2D arrays from big 2D array by grid (N,M)

答案1

得分: 2

可以使用类似以下的方法

```python
from numpy.lib.stride_tricks import sliding_window_view

out = np.vstack(sliding_window_view(c, (2, 2))[::2, ::2])

输出:

>>> out.tolist()
[[[0, 1], [6, 7]],
 [[2, 3], [8, 9]],
 [[4, 5], [10, 11]],
 [[12, 13], [18, 19]],
 [[14, 15], [20, 21]],
 [[16, 17], [22, 23]],
 [[24, 25], [30, 31]],
 [[26, 27], [32, 33]],
 [[28, 29], [34, 35]]]

<details>
<summary>英文:</summary>

You can use something like:

from numpy.lib.stride_tricks import sliding_window_view

out = np.vstack(sliding_window_view(c, (2, 2))[::2, ::2])


Output:

>>> out.tolist()
[[[0, 1], [6, 7]],
[[2, 3], [8, 9]],
[[4, 5], [10, 11]],
[[12, 13], [18, 19]],
[[14, 15], [20, 21]],
[[16, 17], [22, 23]],
[[24, 25], [30, 31]],
[[26, 27], [32, 33]],
[[28, 29], [34, 35]]]



</details>



huangapple
  • 本文由 发表于 2023年1月9日 18:46:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/75056147.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定