首页 > 解决方案 > 如何通过循环将 ND numpy 数组附加到 (N+1)D numpy 数组?

问题描述

例如,我需要从图像创建的 30x30 numpy 数组输入神经网络。如果我有一个要预测的图像目录,我应该能够遍历该目录,获取图像数据并创建一个 (n,30,30) 形状的 np 数组这是我目前的方法,我打算在喂食之前重塑每一行到模型

def get_image_vectors(path):
    img_list=os.listdir(path)
    print(img_list)
    X=np.empty((900,))
    for img_file in img_list:
        img= Image.open(os.path.join(path,img_file))
        img_grey= img.convert("L")
        resized = img_grey.resize((30,30))
        flattened = np.array(resized.getdata())
        # print(flattened.shape)
        X=np.vstack((X,flattened))
        print(img_file,'=>',X.shape)
    return X[1:,:]

标签: pythonarraysnumpy

解决方案


与其附加到现有数组,不如先使用列表,附加到它,然后在最后转换为数组。从而节省了许多对 np 数组的冗余修改。

这是一个玩具示例:

import numpy as np

def get_image_vectors():
    X= [] #Create empty list
    for i in range(10):
        flattened = np.zeros(900)
        X.append(flattened) #Append some np array to it
    return np.array(X) #Create array from the list

结果:

array([[0., 0., 0., ..., 0., 0., 0.],
       [0., 0., 0., ..., 0., 0., 0.],
       [0., 0., 0., ..., 0., 0., 0.],
       ...,
       [0., 0., 0., ..., 0., 0., 0.],
       [0., 0., 0., ..., 0., 0., 0.],
       [0., 0., 0., ..., 0., 0., 0.]])

推荐阅读