将图像从python文件夹导入numpy数组列表

将图像从python文件夹导入numpy数组列表,python,numpy,machine-learning,scikit-learn,python-import,Python,Numpy,Machine Learning,Scikit Learn,Python Import,我有一个包含10000个图像的文件夹和3个子文件夹,每个文件夹包含不同数量的图像。我想导入这些图像中的一小部分用于训练,这是我每次想要拾取一部分数据时手动选择的有限大小。 我已经编写了以下python代码: train_dir = 'folder/train/' # This folder contains 10.000 images and 3 subfolders , each folder contains different number of images from tqdm imp

我有一个包含10000个图像的文件夹和3个子文件夹,每个文件夹包含不同数量的图像。我想导入这些图像中的一小部分用于训练,这是我每次想要拾取一部分数据时手动选择的有限大小。 我已经编写了以下python代码:

train_dir = 'folder/train/' # This folder contains 10.000 images and 3 subfolders , each folder contains different number of images

from tqdm import tqdm
def get_data(folder):
    """
    Load the data and labels from the given folder.
    """
    X = []
    y = []
    for folderName in os.listdir(folder):
        if not folderName.startswith('.'):
            if folderName in   ['Name1']:
                label = 0
            elif folderName in ['Name2']:
                label = 1
            elif folderName in ['Name3']:
                label = 2
            else:
                label = 4
            for image_filename in tqdm(os.listdir(folder + folderName)):
                img_file = cv2.imread(folder + folderName + '/' + image_filename)
                if img_file is not None:
                    img_file = skimage.transform.resize(img_file, (imageSize, imageSize, 1))
                    img_arr = np.asarray(img_file)
                    X.append(img_arr)
                    y.append(label)
    X = np.asarray(X) # Keras only accepts data as numpy arrays 
    y = np.asarray(y)
    return X,y


X_test, y_test= get_data(train_dir)
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X_test, y_test, test_size=0.2)

我想指定
Size
参数,以便选择要导入的图像数量。从每个子文件夹导入的图像数量应相等。您可以在单独的列表中读取和存储每个文件夹中的每个路径,并选择相等数量的路径

folder1_files = []
for root, dirs, files in os.walk('path/folder1', topdown=False):
    for i in files:
        folder1_files.append("path/folder1/"+i)
选择:

train = folder1[:n] + folder2[:n] + folder3[:n]

n-每个文件夹中的图像数

似乎您需要的是Keras
ImageDataGenerator
类,其中包含目录中的
flow\u
。是否可以使用ImageDataGenerator指定从文件夹导入的图像数?如果是,怎么上传?谢谢,但是我想上传上面提到的代码结构(有编码和很多东西…),有可能吗?