tensorflow学习笔记之tfrecord文件的生成与读取

作者:wxsy024680 时间:2021-05-24 13:12:43 

训练模型时,我们并不是直接将图像送入模型,而是先将图像转换为tfrecord文件,再将tfrecord文件送入模型。为进一步理解tfrecord文件,本例先将6幅图像及其标签转换为tfrecord文件,然后读取tfrecord文件,重现6幅图像及其标签。
1、生成tfrecord文件


import os
import numpy as np
import tensorflow as tf
from PIL import Image

filenames = [
'images/cat/1.jpg',
'images/cat/2.jpg',
'images/dog/1.jpg',
'images/dog/2.jpg',
'images/pig/1.jpg',
'images/pig/2.jpg',]

labels = {'cat':0, 'dog':1, 'pig':2}

def int64_feature(values):
if not isinstance(values, (tuple, list)):
values = [values]
return tf.train.Feature(int64_list=tf.train.Int64List(value=values))

def bytes_feature(values):
return tf.train.Feature(bytes_list=tf.train.BytesList(value=[values]))

with tf.Session() as sess:
output_filename = os.path.join('images/train.tfrecords')
with tf.python_io.TFRecordWriter(output_filename) as tfrecord_writer:
for filename in filenames:
#读取图像
image_data = Image.open(filename)
#图像灰度化
image_data = np.array(image_data.convert('L'))
#将图像转化为bytes
image_data = image_data.tobytes()
#读取label
label = labels[filename.split('/')[-2]]
#生成protocol数据类型
example = tf.train.Example(features=tf.train.Features(feature={'image': bytes_feature(image_data),
'label': int64_feature(label)}))
tfrecord_writer.write(example.SerializeToString())

2、读取tfrecord文件


import tensorflow as tf
import matplotlib.pyplot as plt
from PIL import Image

# 根据文件名生成一个队列
filename_queue = tf.train.string_input_producer(['images/train.tfrecords'])
reader = tf.TFRecordReader()
# 返回文件名和文件
_, serialized_example = reader.read(filename_queue)
features = tf.parse_single_example(serialized_example,
features={'image': tf.FixedLenFeature([], tf.string),
'label': tf.FixedLenFeature([], tf.int64)})
# 获取图像数据
image = tf.decode_raw(features['image'], tf.uint8)
# 恢复图像原始尺寸[高,宽]
image = tf.reshape(image, [60, 160])
# 获取label
label = tf.cast(features['label'], tf.int32)

with tf.Session() as sess:
# 创建一个协调器,管理线程
coord = tf.train.Coordinator()
# 启动QueueRunner, 此时文件名队列已经进队
threads = tf.train.start_queue_runners(sess=sess, coord=coord)

for i in range(6):
image_b, label_b = sess.run([image, label])
img = Image.fromarray(image_b, 'L')
plt.imshow(img)
plt.axis('off')
plt.show()
print(label_b)

# 通知其他线程关闭
coord.request_stop()
# 其他所有线程关闭之后,这一函数才能返回
coord.join(threads)

来源:https://blog.csdn.net/wxsy024680/article/details/115291692

标签:tensorflow,tfrecord,生成,读取
0
投稿

猜你喜欢

  • 关于python中逆序的三位数

    2021-08-09 05:17:28
  • asp如何更好地保护我的网页?

    2009-11-22 19:29:00
  • python中dict()的高级用法实现

    2022-06-16 23:24:29
  • python记录程序运行时间的三种方法

    2023-08-25 03:12:19
  • numpy中轴处理的实现

    2021-08-14 12:06:16
  • Python Handler处理器和自定义Opener原理详解

    2022-05-15 10:57:48
  • “验证码”等于“流氓软件”

    2007-10-19 18:29:00
  • 多级联动下拉选择框,动态获取下一级

    2008-09-04 10:34:00
  • Python实现GUI学生信息管理系统

    2022-03-19 19:35:36
  • 用Dreamweaver MX制作文字特效

    2011-06-14 09:49:47
  • python实现获取单向链表倒数第k个结点的值示例

    2022-10-12 17:38:10
  • Django 解决由save方法引发的错误

    2022-04-07 06:06:56
  • 如何随机显示图片计数器?

    2010-05-16 15:21:00
  • 给zblog加上运行代码功能

    2007-12-19 13:07:00
  • Pytorch自动求导函数详解流程以及与TensorFlow搭建网络的对比

    2023-07-08 18:44:37
  • Insert into与AddNew哪一个更好?

    2009-10-28 18:30:00
  • Python函数参数基础介绍及示例

    2021-02-03 03:11:04
  • 编程经验点滴 动态SQL的拼接技巧

    2012-11-30 20:03:58
  • 浅析“Rich”设计模式

    2009-03-12 12:36:00
  • python K近邻算法的kd树实现

    2022-01-09 19:05:43
  • asp之家 网络编程 m.aspxhome.com