简体   繁体   English

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

[英]import images from folder python to numpy array list

I have a folder that contains 10000 images, and 3 subfolders , each folder contains different number of images.我有一个包含 10000 张图像的文件夹和 3 个子文件夹,每个文件夹包含不同数量的图像。 I want to import a small portion of these images for training, that the limited size i chose manually each time i want to pick a portion of the data.我想导入这些图像的一小部分用于训练,每次我想选择一部分数据时手动选择的有限大小。 I have already this python code :我已经有了这个 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)

i want to specify Size parameter so that i can choose the number of images to import.我想指定Size参数,以便我可以选择要导入的图像数量。 the number of imported images from each subfolder should be equal从每个子文件夹导入的图像数量应该相等

You can read and store every paths from each folder in a separate list and select equal number of them.您可以在单独的列表中读取和存储每个文件夹中的每个路径,并选择相同数量的路径。

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

to select:选择:

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

n - number of images from each folder n - 每个文件夹中的图像数量

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

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