Tfrecord文件是tensorflow专门设计的一种训练样本储存格式,将训练样本打包成tfrecord格式后能够加快文件的读取效率。所以训练网络的第一步就是将自己的训练集样本打包生成tfrecord格式。本文主要介绍两种tfrecord打包方式,这两种方式的主要区别在于生成的tfrecord文件大小不同。

方式一:利用常用图像处理库读取图像并解码,转换成二进制文件进行存储,网络上找到的基本上都是这种方式。

写入tfrecord文件

def data_to_tfrecord(images, labels, filename):  # images中存储的是所有图像路径的一个列表""" Save data into TFRecord """              # labels是images中每个图像对应的标签if os.path.isfile(filename):                 # filename是tfrecord文件名称print("%s exists" % filename)returnprint("Converting data into %s ..." % filename)writer = tf.python_io.TFRecordWriter(filename)for index, img_file in zip(labels, images):img1 = Image.open(img_file)   # 通过PIL包中的Images函数读取、解码图片width, height = img1.size   # 获取图像的宽、高参数img_raw = img1.tobytes()   # 将图像转换成二进制序列label = int(index)   # 图片对应的标签example = tf.train.Example(features=tf.train.Features(feature={'label': tf.train.Feature(int64_list=tf.train.Int64List(value=[label])),    # 保存标签'img_raw': tf.train.Feature(bytes_list=tf.train.BytesList(value=[img_raw])),  # 保存二进制序列'img_width': tf.train.Feature(int64_list=tf.train.Int64List(value=[width])),  # 保存图像的宽度'img_height': tf.train.Feature(int64_list=tf.train.Int64List(value=[height]))  # 保存图像的高}))writer.write(example.SerializeToString())  # Serialize To Stringwriter.close()

读取tfrecord文件

import numpy as np
import tensorflow as tf
import tensorlayer as tldef read_and_decode(filename):""" Return tensor to read from TFRecord """filename_queue = tf.train.string_input_producer([filename])reader = tf.TFRecordReader()_, serialized_example = reader.read(filename_queue)features = tf.parse_single_example(serialized_example, features={'label': tf.FixedLenFeature([], tf.int64),   # 从tfrecord文件中读取各种信息'img_raw': tf.FixedLenFeature([], tf.string),'img_width': tf.FixedLenFeature([], tf.int64),'img_height': tf.FixedLenFeature([], tf.int64)})# You can do more image distortion here for training datawidth = tf.cast(features['img_width'], tf.int32)    # 转型height = tf.cast(features['img_height'], tf.int32)img = tf.decode_raw(features['img_raw'], tf.uint8)   # 从二进制文件转成uint8img = tf.reshape(img, [height, width, 3])   # 对图像进行reshape,注意在tfrecord文件中存储的是一序列,并没有形状img = tf.image.resize_images(img, [32, 32])   # 将图像统一到同一尺寸# img = tf.cast(img, tf.float32) #* (1. / 255) - 0.5label = tf.cast(features['label'], tf.int32)return img, label# Example to visualize data
img, label = read_and_decode("train.tfrecord")
img_batch, label_batch = tf.train.shuffle_batch([img, label],batch_size=4,capacity=5000,min_after_dequeue=100,num_threads=1)
print("img_batch   : %s" % img_batch._shape)
print("label_batch : %s" % label_batch._shape)init = tf.initialize_all_variables()
with tf.Session() as sess:sess.run(init)coord = tf.train.Coordinator()threads = tf.train.start_queue_runners(sess=sess, coord=coord)for i in range(3):  # number of mini-batch (step)print("Step %d" % i)val, l = sess.run([img_batch, label_batch])# exit()print(val.shape, l)tl.visualize.images2d(val, second=1, saveable=False, name='batch'+str(i), dtype=np.uint8, fig_idx=2020121)coord.request_stop()coord.join(threads)sess.close()

方式二:利用tf.gfile.FastGFile读取图像信息(貌似并没有解码),转换成二进制文件存储。

这个方法是我在看tensorflow在github的slim框架中的生成tfrecord文件所使用的方法。

写入tfrecord文件

def data_to_tfrecord(images, labels, filename):""" Save data into TFRecord """if os.path.isfile(filename):print("%s exists" % filename)returnprint("Converting data into %s ..." % filename)writer = tf.python_io.TFRecordWriter(filename)for index, img_file in zip(labels, images):img1 = Image.open(img_file)width, height = img1.size# img_raw = img1.tobytes()img_raw = tf.gfile.FastGFile(img_file, 'rb').read()  # 与方式一不同的是使用的FastGFile函数label = int(index)example = tf.train.Example(features=tf.train.Features(feature={'label': tf.train.Feature(int64_list=tf.train.Int64List(value=[label])),'img_raw': tf.train.Feature(bytes_list=tf.train.BytesList(value=[img_raw])),'img_width': tf.train.Feature(int64_list=tf.train.Int64List(value=[width])),'img_height': tf.train.Feature(int64_list=tf.train.Int64List(value=[height]))}))writer.write(example.SerializeToString())  # Serialize To Stringwriter.close()

读取tfrecord文件

import numpy as np
import tensorflow as tf
import tensorlayer as tldef read_and_decode(filename):""" Return tensor to read from TFRecord """filename_queue = tf.train.string_input_producer([filename])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),'img_width': tf.FixedLenFeature([], tf.int64),'img_height': tf.FixedLenFeature([], tf.int64)})# You can do more image distortion here for training datawidth = tf.cast(features['img_width'], tf.int32)height = tf.cast(features['img_height'], tf.int32)# img = tf.decode_raw(features['img_raw'], tf.uint8)img = tf.image.decode_jpeg(features['img_raw'])  # 与方式一的不同点在于需要用decode_jpeg解码img = tf.reshape(img, [height, width, 3])img = tf.image.resize_images(img, [32, 32])# img = tf.cast(img, tf.float32) #* (1. / 255) - 0.5label = tf.cast(features['label'], tf.int32)return img, label# Example to visualize data
img, label = read_and_decode("train")
img_batch, label_batch = tf.train.shuffle_batch([img, label],batch_size=4,capacity=5000,min_after_dequeue=100,num_threads=1)
print("img_batch   : %s" % img_batch._shape)
print("label_batch : %s" % label_batch._shape)init = tf.initialize_all_variables()
with tf.Session() as sess:sess.run(init)coord = tf.train.Coordinator()threads = tf.train.start_queue_runners(sess=sess, coord=coord)for i in range(3):  # number of mini-batch (step)print("Step %d" % i)val, l = sess.run([img_batch, label_batch])# exit()print(val.shape, l)tl.visualize.images2d(val, second=1, saveable=False, name='batch'+str(i), dtype=np.uint8, fig_idx=2020121)coord.request_stop()coord.join(threads)sess.close()

两种方式的区别

两种方式虽然在代码上就那么一两行的区别,当对于生成的tfrecord文件还是有很大的区别的。我用的同样的图像样本集,约200M左右,用方式一生成的tfrecord文件约900M,用方式二生成的tfrecord文件约200M。很明显在占用内存方面有着很大的区别。据我个人猜测,方案一将图像解码后在转成二进制文件的,方案二并没有解码而是直接转成二进制文件进行存储,所以在读取时需要进行图像解码。这仅是我个人猜测,如果有懂的大神,还望赐教。

打包tfrecord文件,并读取相关推荐

  1. python如何读取tfrecord文件_TFRecord读取数据

    TFRecord 这篇文章基于一个生成tfrecord和解析tfrecord的代码,对TFRecord进行了详细的解析. 一. 什么是TFRecord? Tensorflow的文档中说: " ...

  2. tfrecord文件生成与读取

    参考博客--tensorflow-TFRecord 文件详解 1. 生成tfrecord文件 代码 #1.创建tfrecord对象 tf_record=tf.python_io.TFRecordWri ...

  3. 打包部署后无法读取jar包里的文件(实测可行,Java中读取jar包中的文件)

    打包部署后无法读取jar包里的文件 Java中读取jar包中的文件 linux中无法读取jar包中的内容(windows可以的!),如何解决 一.背景 项目中免不了需要读取文件,如果文件用绝对路径读取 ...

  4. Tensorflow—TFRecord文件生成与读取

    Tensorflow-TFRecord文件生成与读取 微信公众号:幼儿园的学霸 个人的学习笔记,关于OpenCV,关于机器学习, -.问题或建议,请公众号留言; 目录 文章目录 Tensorflow- ...

  5. springboot打包后jar itext读取字体文件处理

    springboot打包后jar itext读取字体文件处理 springboot打包后无法读取文件 通过 InputStream stream = Thread.currentThread().ge ...

  6. python如何读取tfrecord文件_tensorflow-TFRecord 文件详解

    TFRecord 是 tensorflow 内置的文件格式,它是一种二进制文件,具有以下优点: 1. 统一各种输入文件的操作 2. 更好的利用内存,方便复制和移动 3. 将二进制数据和标签(label ...

  7. 求助,在使用TensorFlow进行花朵图片分类时,想把数据集的图片转化为tfrecord文件,但是程序运行后没有反应,不知道问题出在哪里

    求助,在使用TensorFlow进行花朵图片分类时,想把数据集的图片转化为tfrecord文件,但是程序运行后没有反应,一直显示服务空闲,不知道问题出在哪里,一下是我的程序,希望可以指点我一下哪里出了 ...

  8. springboot读取linux文件_SpringBoot读取Resource下文件的几种方式

    最近在项目中涉及到Excle的导入功能,通常是我们定义完模板供用户下载,用户按照模板填写完后上传:这里待下载模板位置为resource/excelTemplate/test.xlsx,尝试了四种读取方 ...

  9. java读取系统中指定的文件_java读取jar中指定的文件

    Java 档案 (Java Archive, JAR) 文件是基于 Java 技术的打包方案.它们允许开发人员把所有相关的内容 (.class.图片.声音和支持文件等) 打包到一个单一的文件中.JAR ...

最新文章

  1. Vue 监听路由变化的三种方式
  2. 二十五、redis主从复制
  3. 第六十六篇、OC_Sqlite数据库操作
  4. ModelAndView学习笔记
  5. Win7系统下共享文件夹后共享文件夹上的小锁图标取消方法
  6. 工作51:后端vue学习地址
  7. 易语言调用大漠插件判断游戏是否在线
  8. Jquery项目练习-狂拍灰太狼
  9. 胖男孩麦克正如我们所知的_正如我们所知,智能合约将如何改变网络?
  10. 2022智源大会议程公开 | 人工智能新基建论坛
  11. 60所大学计算机具有博士点,全国具有测绘科学与技术学科博士点、硕士点的高校及科研院所名单...
  12. 荧光定量PCR的优点和检测方法盘点
  13. 机械秒表的使用方法_浪琴 L683、L688自动上弦机械计时秒表设置方法
  14. docker运行portainer
  15. 用容器类实现事件坚挺器接口的示例
  16. 【关于机器学习人工智能,人类长生遐想】纯属个人遐想,欢迎各位大神提出意见
  17. 关于一些不为人知的小秘密
  18. C语言五子棋人人对弈学习笔记
  19. 从线性分类器到卷积神经网络
  20. Vue2项目引入vant报错问题解决export ‘isVNode‘ (imported as ‘isVNode‘)

热门文章

  1. 图解物联网场景,百度云天工带你玩转物可视
  2. java搜索引擎mysql_用Java MySQL PHP轻松构建跨平台的搜索引擎
  3. 六顶帽子思考法的要求与好处
  4. C++新特性篇 - Lambada表达式
  5. 长链接转短链接的一次尝试
  6. Erlang NIF的使用
  7. js比较2个时间先后
  8. 如何使用python批量修改txt文档
  9. 动手搭建第一个小程序音视频Demo
  10. 算法技巧-坐标问题-1926圈地运动