将mnist原始图像转换为tfrecords格式

官方其实是给了mnist数据读取接口的,但还是自己实现一下,这样内部的处理机制就都明白了


mnist数据集中包含测试集和训练集(训练+验证),每个集合中包含若干图片和一个标签文件:



转tfrecords代码

#! -*- coding: utf-8 -*-

import tensorflow as tf
from PIL import Image

config = [{'dir': '/home/mi/DataSet/mnist/test/', 'type': 'test'},
          {'dir': '/home/mi/DataSet/mnist/train/', 'type': 'train'}]
for each in range(len(config)):
    mnist_dir = config[each]['dir']
    mnist_type = config[each]['type']
    with tf.python_io.TFRecordWriter('mnist_' + mnist_type + '.tfrecords') as writer:
        with open(mnist_dir + 'label.txt', 'r') as f:
            label_list = f.readline().split(',')
        for index, name in enumerate(label_list):
            print(mnist_type + ': handling ' + str(index) + '.png ...')
            image_path = mnist_dir + str(index) + '.png'
            image_raw = Image.open(image_path)
            image_byte = image_raw.tobytes()
            example = tf.train.Example(features=tf.train.Features(feature={
                "label": tf.train.Feature(int64_list=tf.train.Int64List(value=[int(name)])),
                'data': tf.train.Feature(bytes_list=tf.train.BytesList(value=[image_byte]))
            }))
            writer.write(example.SerializeToString())
    pass

解析mnist示例代码

#! -*- coding: utf-8 -*-

import tensorflow as tf
from PIL import Image

filename_queue = tf.train.string_input_producer(['mnist_test.tfrecords'])
reader = tf.TFRecordReader()
_, example = reader.read(filename_queue)
features = tf.parse_single_example(example,
                                   features={'label': tf.FixedLenFeature([], tf.int64),
                                             'data': tf.FixedLenFeature([], tf.string)})
image = tf.decode_raw(features['data'], tf.uint8)
image = tf.reshape(image, [28, 28, 1])
label = tf.cast(features['label'], tf.int32)

image_batch, label_batch = tf.train.shuffle_batch([image, label],
                                                  batch_size=1,
                                                  capacity=100,
                                                  min_after_dequeue=50)
image = tf.reshape(image_batch, [28, 28])
with tf.Session() as sess:
    init = tf.global_variables_initializer()
    sess.run(init)
    coord = tf.train.Coordinator()
    threads = tf.train.start_queue_runners(sess=sess, coord=coord)
    for i in range(3):
        data, label = sess.run([image, label_batch])
        result = Image.fromarray(data)
        result.save(str(i) + '.png')
        pass
    pass
    coord.request_stop()
    coord.join(threads)


以下是将MNIST数据集转换为JSON格式的步骤: 1. 下载MNIST数据集并将其解压缩。 2. 创建一个Python脚本,并导入必要的模块,如NumPy、json和gzip。 3. 使用NumPy模块加载MNIST数据集并将其转换为NumPy数组。 4. 将NumPy数组转换为Python列表。 5. 将Python列表转换为JSON格式。 6. 将JSON格式的数据写入文件。 下面是一个示例代码: ```python import numpy as np import json import gzip # 加载MNIST数据集 def load_mnist(path, kind='train'): labels_path = path + '/' + kind + '-labels-idx1-ubyte.gz' images_path = path + '/' + kind + '-images-idx3-ubyte.gz' with gzip.open(labels_path, 'rb') as lbpath: labels = np.frombuffer(lbpath.read(), dtype=np.uint8, offset=8) with gzip.open(images_path, 'rb') as imgpath: images = np.frombuffer(imgpath.read(), dtype=np.uint8, offset=16).reshape(len(labels), 784) return images, labels # 转换为JSON格式 def mnist_to_json(images, labels, outfile): mnist_data = {"data": [], "labels": []} for i in range(len(labels)): mnist_data["data"].append(images[i].tolist()) mnist_data["labels"].append(int(labels[i])) with open(outfile, 'w') as f: json.dump(mnist_data, f) # 测试 X_train, y_train = load_mnist('mnist', kind='train') mnist_to_json(X_train, y_train, 'mnist_train.json') ``` 此代码将MNIST数据集的训练集转换为JSON格式,并将其写入名为'mnist_train.json'的文件中。您可以根据需要修改代码以转换测试集或将数据写入不同的文件。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值