接着上一篇生成TFRecord文件
读取TFRecord文件首先采用输入生成器tf.train.string_input_producer
将其加载到一个队列,然后读出tf.TFRecordReader()
并将tf.parse_single_example
Example对象拆解为图像数据和标签数据,最后对图像数据解码并保持成JPG文件。
# 定义数据流队列
filename_queue = tf.train.string_input_producer([folder+'cat_dog.tfrecords'])
reader = tf.TFRecordReader()
_, serialized_example = reader.read(filename_queue) #返回文件名和文件
features = tf.parse_single_example(serialized_example,
features={
'label': tf.FixedLenFeature([], tf.int64),
'img_raw': tf.FixedLenFeature([], tf.string),
})# 取出包含image和label的features对象,拆解为图像数据和标签数据
# bytes: 字符串类型的张量。所有元素的长度必须相同
# out_type: 来自tf.half,tf.float32,tf.float64,tf.int32,tf.uint16,tf.uint8,tf.int16,tf.int8,tf.int64的tf.DType
image = tf.decode_raw(features['img_raw'], tf.uint8)
image = tf.reshape(image, [128, 128, 3])
label = tf.cast(features['label'], tf.int32)
# 开始一个会话
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
# 协同启动的线程;调用 tf.train.Coordinator() 来创建一个线程协调器,用来管理之后在Session中启动的所有线程;
coord = tf.train.Coordinator()
# 以多线程的方式启动对队列的处理
threads = tf.train.start_queue_runners(coord=coord)
for i in range(count):
example, l = sess.run([image, label])# 在会话中取出image和label
img = Image.fromarray(example, 'RGB')# from PIL import Image 的引用
img.save(folder + str(i) + '_Label_' + str(l) + '.jpg')# 存下图片
print(example, l)
coord.request_stop()# 请求停止线程
coord.join(threads)# 等待所有进程结束
项目目录截图:
上一篇。
项目源代码请点击这里