如何像 MNIST 数据集一样创建图像数据集?

How to create a Image Dataset just like MNIST dataset?

我有10000张手写数字的BMP图片。如果我想将数据提供给神经网络,我需要做什么?对于 MNIST 数据集,我只需要写

(X_train, y_train), (X_test, y_test) = mnist.load_data()

我在 python 中使用 Keras 库。我怎样才能创建这样的数据集?

您可以编写一个函数来加载所有图像并将它们堆叠到一个 numpy 数组中(如果所有图像都适合 RAM)或使用 Keras ImageDataGenerator(https://keras.io/preprocessing/image/) which includes a function flow_from_directory. You can find an example here https://gist.github.com/fchollet/0830affa1f7f19fd47b06d4cf89ed44d.

您应该编写自己的函数来加载所有图像,或者这样做:

imagePaths = sorted(list(paths.list_images(args["testset"])))

# loop over the input images
for imagePath in imagePaths:
    # load the image, pre-process it, and store it in the data list
    image = cv2.imread(imagePath)
    image = cv2.resize(image, (IMAGE_DIMS[1], IMAGE_DIMS[0]))
    image = img_to_array(image)
    data.append(image)
    # extract the class label from the image path and update the
    # labels list


data = np.array(data, dtype="float") / 255.0

numpy 可以将数组保存为二进制文件 numpy save

import numpy as np

def save_data():
  [images, labels] = read_data()
  outshape = len(images[0])
  npimages = np.empty((0, outshape), dtype=np.int32)
  nplabels = np.empty((0,), dtype=np.int32)

  for i in range(len(labels)):
      label = labels[i]
      npimages = np.append(npimages, [images[i]], axis=0)
      nplabels = np.append(nplabels, y)

  np.save('images', npimages)
  np.save('labels', nplabels)


def read_data():
  return [np.load('images.npy'), np.load('labels.npy')]

我可能会迟到,但我发布我的答案是为了帮助访问此问题的其他人寻找答案。在这个答案中,我将解释数据集类型、如何生成此类数据集以及如何加载这些文件。

文件格式是什么

这些数据集已经是 vectorizedNumpy format 中的数据集。检查 here (Keras Datasets Documentation) for the reference. These datasets are stored in .npz file format. Check here(MNIST digits classification dataset)。这是从文档中复制的代码块以供参考。

tf.keras.datasets.mnist.load_data(path="mnist.npz")

生成 .npz 文件后,您可以像使用 mnist 默认数据集一样使用它。

如何生成 .npz 文件

以下是如何从文件夹中的所有图像生成这样的数据集

#generate and save file
from PIL import Image
import os
import numpy as np

path_to_files = "./images/"    
vectorized_images = []

for _, file in enumerate(os.listdir(path_to_files)):
    image = Image.open(path_to_files + file)
    image_array = np.array(image)
    vectorized_images.append(image_array)        
# save as DataX or any other name. But the same element name is to be used while loading it back. 
np.savez("./mnistlikedataset.npz",DataX=vectorized_images) 

如果您想使用保存多个元素,您可以通过对代码进行适当的其他更改来执行类似的操作。

np.savez("./mnistlikedataset.npz",DataX=vectorized_images_x,DataY=vectorized_images_Y)

如何加载数据文件

#load and use file
import numpy as np

path = "./mnistlikedataset.npz"
with np.load(path) as data:
    #load DataX as train_data
    train_data = data['DataX']
    print(train_data)

类似于保存多个元素,如果你想从一个文件中加载多个元素,你可以通过其他适当的更改来执行类似的操作

with np.load(path) as data:
    train_data = data['DataX']
    print(train_data)
    test_data = data['DataY']
    print(test_data)