tensorflow学习笔记之tfrecord文件的生成与读取
作者:wxsy024680 发布时间:2021-05-24 13:12:43
标签:tensorflow,tfrecord,生成,读取
训练模型时,我们并不是直接将图像送入模型,而是先将图像转换为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


猜你喜欢
- SQLSERVER与MySQL的差异功能差异SQLServer和MySQL都支持大多数SQL语言的基本功能,如SELECT,UPDATE,I
- 开始之前,安利一本正在看的书《站在两个世界的边缘》,作者程浩,上帝丢给他太多理想,却忘了给他完成理想的时间。OK,有兴趣的可以看一看。nod
- 绘制八个子图import matplotlib.pyplot as pltfig = plt.figure()shape=['.
- 条件去官网下载.war和.msi文件夹https://www.jenkins.io第一条线是war第二条线是msi保存到的地方(根据你的电脑
- 我介绍了 Systemd 的主要命令,今天介绍如何使用它完成一些基本的任务。一、开机启动对于那些支持 Systemd 的软件,安装的时候,会
- Iterable – 可迭代对象能够逐一返回其成员项的对象。 可迭代对象的例子包括所有序列类型 (例如 list, str 和 tuple)
- 这篇文章主要给大家介绍了关于Django跨域请求问题解决的相关资料,文中介绍的实现方法包括:使用django-cors-headers全局控
- 1、先看看什么是 iterable 对象以内置的max函数为例子,查看其doc:>>> print max.__doc__
- runtime 调度器是个非常有用的东西,关于 runtime 包几个方法:Gosched:让当前线程让出 cpu 以让其它线程运行,它不会
- Python在用GPU跑模型的时候最好开多进程,因为很明显这种任务就是计算密集型的。用进程池好管理,但是tensorflow默认情况会最大占
- 1. 导入各种模块基本形式为:import 模块名from 某个文件 import 某个模块2. 导入数据(以两类分类问题为例,即numCl
- selenium 安装与 chromedriver安装我们前文提到,Python脚本中使用了selenium库,而selenium又通过ch
- 本文实例讲述了Mysql存储过程中游标的用法。分享给大家供大家参考。具体如下:1. 批量插入商户路由关联数据:DELIMITER $$USE
- 由于这个数据库服务器存放的数据库比较多且都是小数据库,所以最初的时候是运行在windows服务器上的。前一段时间由于机房服务器要做调整,于是
- 背景golang版本:1.16之前遇到的问题,docker启动时禁用了oom-kill(kill后服务受损太大),导致golang内存使用接
- 作用:pygame一般用来做游戏注意:1.在使用pygame提供的功能之前,需要调用init方法2.在游戏结束前需要调用 quit 方法py
- cooper谈到用户的视觉路径一般是:从上到下,从左到右。好的视觉设计路径应该是顺应这样的用户习惯,糟糕的设计会让用户无所适从,焦点到处都是
- 有一个群友在群里问个如何快速搭建一个搜索引擎,在搜索之后我看到了这个代码所在Git:https://github.com/asciimoo/
- 本文实例讲述了Python将阿拉伯数字转换为罗马数字的方法。分享给大家供大家参考。具体实现方法如下:def numToRomanNum(Nu
- 在处理表格型数据时,常会用到排序,比如,按某一行或列的值对表格排序,要怎么做呢?这就要用到 pandas 中的 sort_values()