tensorflow学习(9):TFRecord介绍和样例程序(附详细解读)

由于图像的亮度、对比度等属性对图像的影响是非常大的,相同物体在不同亮度、对比度下差别非常大,然而在很多图像识别问题中,这些因素都不应该影响最后的识别结果。因此,本文将介绍如何对图像数据处理进行预处理使训练得到的神经网络模型尽可能小的被无关因素影响。

由于来自实际问题的数据往往有很多格式和属性,我们将使用TFRecord格式来统一不同的原始数据格式,并更加有效的管理不同的属性。

一、TFRecord格式

TFRecord文件中的数据都是通过tf.train.Example Protocol Buffer格式存储的,以下代码给出了tf.train.Example的定义

message Example{
	Features features = 1
};

message Features{
	map<string, Feature> feature = 1
};

message Feature{
	oneof kind{
		ByteList bytes_list = 1;
		FloatList float_list = 1;
		Int64List int64_lsit = 1;
		}
};

从以上代码中可以看出tf.train.Example的数据结构是比较简洁的。tf.train.Example中包含了一个从属性名称到取值的字典。其中属性名称为一个字符串,属性的取值可以是字符串、实数列表、整数列表。比如将一张解码前的图像存储为一个字符串,图像所对应的类别编号存储为整数列表。

二、将数据写入TFRecord

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

#生成整数型的属性
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]))
#path是存储已经下载好的mnist数据集的路径
mnist = input_data.read_data_sets("path",dtype=tf.uint8,one_hot=True)
images = mnist.train.images
#训练数据所对应的正确答案,可以作为一个属性保存在TFRecord
labels = mnist.train.labels
#训练数据的图像的分辨率,可以作为Example中的一个属性
pixels = images.shape[1]
num_examples = mnist.train.num_examples

#输出TFRecord文件的地址
filename = '/path/to/output.tfrecords'
#创建一个writer来写TFRecord文件
writer = tf.python_io.TFRecordWriter(filename)

for index in range(num_examples):
    #将图像矩阵转化为一个字符串
    image_raw = images[index].tostring()
    #将一个样例转化为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读出数据

import tensorflow as tf

#创建一个reader来读取TFRecord文件中的样例
reader = tf.TFRecordReader()
#创建一个队列来维护文件列表
filename_queue = tf.train.string_input_producer(['output.tfrecords'])#存储路径

#从一个文件中读出一个样例,也可以使用read_up_to函数一次性读取多个样例
_, serialized_example = reader.read(filename_queue)
#解析读入的一个样例,如果需要解析多个样例,可以用parse_example函数
features = tf.parse_single_example(serialized_example,
            features = {
                'image_raw':tf.FixedLenFeature([],tf.string),
                'pixels':tf.FixedLenFeature([],tf.int64),
                'label':tf.FixedLenFeature([],tf.int64)
            })

#tf.decode_raw可以将字符串解析成图像对应的像素数组
image = tf.decode_raw(features['image_raw'],tf.uint8)
label = 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):
    print(sess.run([image,label,pixels]))

猜你喜欢

转载自blog.csdn.net/shanlepu6038/article/details/84751990