如何从文件夹创建图像数据集

How to create dataset of images from folder

我在一个文件夹中有一个包含来自 this dataset 的 35,000 多张图像的数据集。如何将这些图像转换为 train_images 中 python 的数组,我可以将其输入张量流深度学习模型?

方法一(简单但不推荐)

使用 numpy、PIL 或 opencv 加载您的数据,并使用占位符将其提供给您的网络。这意味着您的数据足够小以适合内存。示例代码看起来像

import glob
import cv2
import numpy as np
import tensorflow as tf

data = []
for i in glob.glob('path/to/my/data/**/*.png', recursive=True):
    data.append(cv2.imread(i))

data = np.stack(data) # array of shape [num_images, height, width, channel]

def get_batch(data, batch_size):
    data_size = data.shape[0]
    indexes = list(range(data_size))
    np.random.shuffle(indexes)
    for i in range(0, data_size, batch_size):
        yield data[indexes[i:i+batch_size]]

images = tf.placeholder(tf.float32, [None, height, width, channel])
my_net = build_network(images)

...

for epoch in range(max_epochs):
    for batch_images in get_batch(data, batch_size):
        sess.run(train_op, feed_dict={images: batch_images})

方法 2(涉及更多但规模更好)

您应该根据数据创建 TF 记录,并使用 TensorFlow 中的排队机制和数据集 API 而不是占位符。

要从您的数据集文件夹中获取所有 file/image 名称,请遵循此

import os

# train_images list of name of files or images in data set folder 
train_images = list()

image_path = ' path to the data set (image) folder '
for image in os.walk(image_path):
    train_images.append(image[2]) 
# os.walk('path') traverse recursively so used index 2 to give file name in same folder only

trian_images is required array which you can pass/feed to tensorflow.

遵循@Olivier Moindrot 的这个解决方案并将train_images传递给文件名并根据需要标记数据。