如何创建类似于MNIST数据集的图像数据集?

24

我有10000张手写数字的BMP图像。如果我想将这些数据馈送到神经网络中,我应该怎么做?对于MNIST数据集,我只需要编写

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

我正在使用Python的Keras库。我该如何创建这样的数据集?

4个回答

11

9
最好直接在这里编写代码。链接的内容可能会随时间流逝而丢失,尤其是 Github 的链接。我认为在SO社区中放置整个代码而不是链接是最佳实践。 - ziMtyth

3
你应该编写自己的函数来加载所有的图片,或者像这样做:
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

2
我可能会迟到,但我会发布我的答案来帮助那些寻找答案的人。在这个答案中,我将解释数据集类型、如何生成这些数据集以及如何加载这些文件。
文件格式是什么?
这些数据集已经进行了矢量化,并以Numpy格式存储。请参阅此处(Keras数据集文档)以获得参考。这些数据集存储在.npz文件格式中。请查看此处(MNIST数字分类数据集)。以下是从文档中复制的代码块,供参考。
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)

1
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')]


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接