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
0
投稿
猜你喜欢
- 比如,若要将某个String对象s从gbk内码转换为UTF-8,可以如下操作 s.decode('gbk').encode(
- 在不久前的一天,当我为了解决一个语法问题来翻阅VBscript文档时,偶然间发现在了下面的一句话: &nb
- function chinese2unicode(Str) &nbs
- 看代码吧~import numpy as npa = np.array([[2, 4, 6, 1], [1, 5, 2, 9]])print
- python 获取网页编码方式实现代码<span style="font-family: Arial, Helvetica,
- window对象表示浏览器中打开的窗口,提供关于窗口状态的信息。可以用window对象访问窗口中绘制的文档、窗口中发生的事件和影响窗口的浏览
- 在项目中发现这样一个问题:sqlserver数据库编码为gbk,使用python3.4+pymssql 查询,中文乱码,经过一番思考问题解决
- 在做自动化测试时,遇到两种情况需要判断usb是否已连接上(注,本文仅针对用adb命令来control手机)一种是在开测时(前提是同时要测试多
- Python 中迭代器与生成器实例详解本文通过针对不同应用场景及其解决方案的方式,总结了Python中迭代器与生成器的一些相关知识,具体如下
- 一、张量定义张量:TensorFlow的张量是n维数组,类型为tf.Tensor。标量:一个数字 (0阶张量)向量:一维数组 (1阶张量)矩
- 最近在做图片相关的工作,面对各种格式的图片转换,在OpenCV跟Pillow之间来回切换。觉得有必要把这些东西记录下来,以备不时之需。首先介
- 如何实现优惠打折? 代码及说明见下:<%@ LANG
- 递归是以相似的方式重复项目的过程。同样适用于编程语言中,如果一个程序可以让你调用同一个函数被调用的函数,递归调用函数内使用如下。func r
- SQL Server定位于中型的数据库应用,操作较Oracle和MySQL等要相对简便,SQL Server在处理海量数据的效率,后台开发的
- python3的多行输入问题因为在OJ上做编程,要求标准输入,特别是多行输入。特意查了资料,自己验证了可行性。if __name__ ==
- 一、场景描述这里有以四张发票为例(辰哥网上搜的),将发票图片放到pic文件夹下。随便打开一张发票提取目标:金额、名称、纳税人识别号、开票人。
- 本文实例为大家分享了Django下完成文件上传和下载功能的具体代码,供大家参考,具体内容如下一、文件上传Views.pydef upload
- jsp登陆验证,网页登陆验证带验证码校验,登录功能之添加验证码part_1:专门用于生成一个验证码图片的类:VerificationCode
- 所谓网络爬虫,通俗的讲,就是通过向我们需要的URL发出http请求,获取该URL对应的http报文主体内容,之后提取该报文主体中我们所需要的
- 本文实例讲述了Python基于csv模块实现读取与写入csv数据的方法。分享给大家供大家参考,具体如下:通过csv模块可以轻松读取格式为cs