图像处理:TFRecord的生成和读取

图像处理:TFRecord的生成和读取

Tensorflow 提供了一种统一的格式来存储数据,这个格式就是TFRecord。
tensorflow都是用 tf.train.Example Protocol Buffer 的格式存储的。
下面的代码实现了将mnist训练数据转化成 TFRecord 的格式:

"""
用来将 mnist 的数据集转换成 TFRecord
by song
stay calm stay peace
"""

import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
import numpy as np


# 生成整数型的属性
def _int64_feature(value):
    return tf.train.Feature(int64_list = tf.train.Int64List(value=[value]))


# 生成字符串型的属性
def _bytes_feature(value):
    return tf.train.Feature(bytes_list = tf.train.BytesList(value=[value]))


mnist = input_data.read_data_sets('\TFRecord\mnist', dtype=tf.uint8, one_hot=True)
images = mnist.train.images
# 训练数据对应的正确答案,可以作为一个属性保存在 TFRecord 中。
labels = mnist.train.labels
# 训练数据的分辨率,可以作为Example中的一个属性
pixels = images.shape[1]  # 28*28 = 784

num_examples = mnist.train.num_examples  # 训练的一共有多少张图片
# 输出 TFRecord 文件的地址
filename = '/TFRecord/TFRecord_data'
# 创建一个writer来写 TFRecord 文件
writer = tf.python_io.TFRecordWriter(filename)
for index in range(num_examples):  # 循环读取每一个数据集的数据
    # 将图像矩阵转化成一个字符串。
    image_raw = images[index].tostring()  # tostring将图片转换成string
    # 将一个样例转化为Example Protocol Buffer, 并将所有的信息写入这个数据结构
    example = tf.train.Example(features=tf.train.Features(feature={
        'pixels': _int64_feature(pixels),
        'label':  _int64_feature(np.argmax(labels[index])),
        'image_raw': _bytes_feature(image_raw)
    }))

    # 将一个Example写入TFRecord文件
    writer.write(example.SerializeToString())
writer.close()

下面的代码实现了TFRecord数据的读取:

""
读取TFRecord文件
by song
stay clam stay peace
"""
import tensorflow as tf

# 创建一个 reader 来读取 TFRecord 文件中的样例
reader = tf.TFRecordReader()
# 创建一个队列来维护输入文件列表
# tf.train.string_input_producer 函数
filename_queue = tf.train.string_input_producer(['C:/Users\Song Lesheng\Desktop\TFRecord/TFRecord_data'])

# 从文件中读取一个样例。也可以使用 read_up_to 函数一次性读取多个样例
_, serialized_example = reader.read(filename_queue)
# 解析读入的一个样例。如果需要解析多个样例,可以用 parse_example 函数。
features = tf.parse_single_example(
    serialized_example,
    features={
        # tensorflow 提供两种不同的属性解析方法。一种方法是tf.FixedLenFeature
        # 这种方法解析的结果为一个 tensor ,另一种方法是 tf.VarLenFeature,这种方法得到的解析结果为 SparesTensor,用于处理稀疏数据
        # 这里解析数据的格式需要和上面程序写入数据的格式一致。
        'image_raw': tf.FixedLenFeature([], tf.string),
        'pixels': tf.FixedLenFeature([], tf.int64),
        'label': tf.FixedLenFeature([], tf.int64),
              })

# tf.decode_raw 可以将字符串解析成图像对应的像素数组
images = tf.decode_raw(features['image_raw'], tf.uint8)
labels = tf.cast(features['label'], tf.int32)
pixels = tf.cast(features['pixels'], tf.int32)

sess = tf.Session()
# 启动多线程处理输入数据
coord = tf.train.Coordinator()
threads = tf.train.start_queue_runners(sess=sess, coord=coord)

# 每次运行可以读取 TFRecord 文件中的一样样例。当所有样例都读完之后,在此样例中程序会在重头读取
for i in range(10):
    image, label, pixel = sess.run([images, labels, pixels])
    ```

猜你喜欢

转载自blog.csdn.net/qq_43225437/article/details/88018131
今日推荐