简体   繁体   English

将二维 numpy 阵列(灰色图像)重塑为 3D 堆叠阵列的最快方法

[英]fastest way to reshape 2D numpy array (gray image) into a 3D stacked array

I have a 2D image with the shape (M, N), and would like to reshape it into (M//m * N//n, m, n).我有一个形状为 (M, N) 的 2D 图像,并且想将其重塑为 (M//m * N//n, m, n)。 That is, to stack small patches of images into a 3D array.也就是说,将小块图像堆叠到 3D 数组中。

Currently, I used two for-loop to achieve that目前,我使用了两个 for 循环来实现这一点

import numpy as np
a = np.arange(16).reshape(4,4)
b = np.zeros( (4,2,2))

# a = array([[ 0,  1,  2,  3],
#       [ 4,  5,  6,  7],
#       [ 8,  9, 10, 11],
#       [12, 13, 14, 15]])


row_step = 2
col_step = 2
row_indices = np.arange(4, step = 2)
col_indices = np.arange(4, step = 2)

for i, row_idx in enumerate(row_indices):
    for j, col_idx in enumerate(col_indices):
        b[i*2+j, :,:] = a[row_idx:row_idx+row_step, col_idx:col_idx+col_step]

# b = array([[[ 0.,  1.],
#        [ 4.,  5.]],
#
#       [[ 2.,  3.],
#        [ 6.,  7.]],
#
#       [[ 8.,  9.],
#        [12., 13.]],
#
#       [[10., 11.],
#        [14., 15.]]])

Is there any other faster way to do this?有没有其他更快的方法来做到这一点? Thanks a lot!非常感谢!

Use skimage.util.view_as_blocks :使用skimage.util.view_as_blocks

from skimage.util.shape import view_as_blocks

out = view_as_blocks(a, (2,2))#.copy()

Output: Output:

array([[[[ 0,  1],
         [ 4,  5]],

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


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

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

NB.注意。 Be aware that you have a view of the original object.请注意,您看到的是原始 object。 If you want a copy, use view_as_blocks(a, (2,2)).copy()如果你想要一个副本,使用view_as_blocks(a, (2,2)).copy()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM