0

I have an array of 20 ndarray objects in the shape (640, 480) which corresponds to image frames that I am working with.

I'd like to "partition" each of these ndarray objects into 8 smaller "chunks", each with the shape (160, 240) but seem to be not getting the proper results. I'm currently trying this:

frames = [np.zeros((640, 480)) for _ in range(20)] # 20 "image frames"
res = [frame.reshape((240, 160, 8)) for frame in frames]

And what res ends up equaling is an array of 20 ndarray objects with the shape (160, 240, 8), whereas instead I would like res to equal an array of subarrays, where each subarray contains 8 ndarray objects of shape (160, 240).

4

2 回答 2

1

已经提到的Slice 2d array into small 2d arrays确实是一个很好的解决方案,但现在我认为这可以更容易地完成,因为numpy现在它本身具有拆分功能,所以你的任务可以是一个单行:

chunks = [np.vsplit(sub, nrows) for sub in np.hsplit(big_array, ncols)]
# with big_array, nrows and ncols replaced by variables/values relevant for you

只是有一点区别:这里nrowsncols是每个方向上的块数,而不是每个块内的行/列数。

现在比较相同的示例数组:

c = np.arange(24).reshape((4,6))
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]])

c_blocked  = [np.vsplit(sub, 2) for sub in np.hsplit(c, 2)]
[[array([[0, 1, 2],
         [6, 7, 8]]), array([[12, 13, 14],
         [18, 19, 20]])], [array([[ 3,  4,  5],
         [ 9, 10, 11]]), array([[15, 16, 17],
         [21, 22, 23]])]]

c_blocked[0][0]
array([[0, 1, 2],
       [6, 7, 8]])

c_blocked[0][1]
array([[12, 13, 14],
       [18, 19, 20]])

c_blocked[1][0]
array([[ 3,  4,  5],
       [ 9, 10, 11]])

c_blocked[1][1]
array([[15, 16, 17],
       [21, 22, 23]])
于 2018-07-11T21:41:07.757 回答
1

我相信你想要做的是将你的二维数组分成块。这个旧答案可能对您的查询有所帮助:Slice 2d array into small 2d arrays

于 2018-07-11T18:05:33.523 回答