Skip to main content
 首页 » 编程设计

python之如何将许多 2D numpy 数组快速放入 4D numpy 数组中

2025年02月15日19lyhabc

我有大约 150,000 张图像,我想将它们加载到形状为 [index][y][x][channel] 的 numpy 数组中。目前,我是这样做的:

images = numpy.zeros((len(data), 32, 32, 1)) 
for i, fname in enumerate(data): 
    img = scipy.ndimage.imread(fname, flatten=False, mode='L') 
    img = img.reshape((1, img.shape[0], img.shape[1], 1)) 
    for y in range(32): 
        for x in range(32): 
            images[i][y][x][0] = img[0][y][x][0] 

这可行,但我认为必须有比遍历元素更好的解决方案。我可以去掉 reshape ,但这仍然会留下两个嵌套的 for 循环。

要获得相同的 images 4D 数组,需要加载 150,000 张图像,最快的方法是什么?

请您参考如下方法:

在处理 numpy 数组时,通常不需要复制单个元素。您只需指定要将数组复制到和/或从中复制数组的轴(如果它们大小相等或可广播):

images[i,:,:,0] = img[0,:,:,0] 

而不是你的循环。事实上,你根本不需要 reshape :

images[i,:,:,0] = scipy.ndimage.imread(fname, flatten=False, mode='L') 

这些 : 指定您希望保留这些轴(不切片)并且 numpy 支持数组到数组的分配,例如:

>>> a = np.zeros((3,3,3)) 
>>> a[0, :, :] = np.ones((3, 3)) 
>>> a 
array([[[ 1.,  1.,  1.], 
        [ 1.,  1.,  1.], 
        [ 1.,  1.,  1.]], 
 
       [[ 0.,  0.,  0.], 
        [ 0.,  0.,  0.], 
        [ 0.,  0.,  0.]], 
 
       [[ 0.,  0.,  0.], 
        [ 0.,  0.,  0.], 
        [ 0.,  0.,  0.]]]) 

或

>>> a = np.zeros((3,3,3)) 
>>> a[:, 1, :] = np.ones((3, 3)) 
>>> a 
array([[[ 0.,  0.,  0.], 
        [ 1.,  1.,  1.], 
        [ 0.,  0.,  0.]], 
 
       [[ 0.,  0.,  0.], 
        [ 1.,  1.,  1.], 
        [ 0.,  0.,  0.]], 
 
       [[ 0.,  0.,  0.], 
        [ 1.,  1.,  1.], 
        [ 0.,  0.,  0.]]])