文章目录

  • 写入/序列化
  • 读取/反序列化
  • tf.train.Feature
  • 具体实现

TFrecord 是 tensorflow 中的数据集存储格式,它的写入和读取相当于序列化和反序列化的过程。

下面内容都是基于 tf2 版本来说明,两个版本中 tfrecord 的核心并没有改变,即序列化和反序列化。但是个人认为 tf2 里面对于读取 tfrecords 文件建立 Dataset 直接用于训练的支持更方便好用了,比如 batch、shuffle、repeat 等方面,所以在这点上基本摒弃了 tf1。

写入/序列化

(1)将数据读到内存,并转换为 tf.train.Example 对象,每个对象由若干个 tf.train.Feature 的字典组成。
(2)将 tf.train.Example 对象序列化为字符串,写入 TFRecord 文件。

读取/反序列化

(1)通过 tf.data.TFRecordDataset 读入原始的 TFRecord 文件,获得一个 tf.data.Dataset 的数据集对象。(tf1 中是要创建一个 reader 来读取 tfrecords 文件中的样例)
(2)通过 Dataset.map 对数据集对象中每个序列化的 tf.train.Example 字符串执行 tf.io.parse_single_example 实现反序列化。
*:map 过程中,无法在 parse 内部进行某些处理,只能 parse 之后在 dataset 中迭代器“拿”出数据之后进行一些转换。

tf.train.Feature

上面多次提到的 tf.train.Feature 支持 3 种数据格式,因此对于各种各样的数据,必须处理成对应这三种格式,才能顺利写入/读取。

3 种格式如下:
tf.train.BytesList: 字符串或原始 Byte 文件,通过 bytes_list 传入。以图片或者数组等类型数据为例,需要转为字符串类型的再传入 BytesList,后面会有例子。
tf.train.FloatList:浮点数,通过 float_list 传入。
tf.train.Int64List:整数,通过 int64_list 传入。

具体实现

#-*-coding:utf-8-*-
import tensorflow as tf
from tensorflow.python.platform import gfile
import cv2# write
def _int64_feature(value):return tf.train.Feature(int64_list=tf.train.Int64List(value=[value]))def _bytes_feature(value):return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))img_path = 'path/to/read/img'
tfrd_path = 'path/to/save/tfrecords'image = cv2.imread(img_path)
h, w, c = image.shape
image_raw_data = gfile.FastGFile(img_path, 'rb').read()
label = 1tfrd_writer = tf.io.TFRecordWriter(tfrd_path)
feature = {'image': _bytes_feature(image_raw_data),'label': _int64_feature(label),'imgH': _int64_feature(h),'imgW': _int64_feature(w),'imgC': _int64_feature(c)}
example = tf.train.Example(features=tf.train.Features(feature=feature))
tfrd_writer.write(example.SerializeToString())
tfrd_writer.close()# read
raw_dataset = tf.data.TFRecordDataset(tfrd_path)
feature_description = {'image': tf.io.FixedLenFeature([], tf.string),'label': tf.io.FixedLenFeature([], tf.int64),'imgH': tf.io.FixedLenFeature([], tf.int64),'imgW': tf.io.FixedLenFeature([], tf.int64),'imgC': tf.io.FixedLenFeature([], tf.int64)}def parse(record):features = tf.io.parse_single_example(record, feature_description)images = tf.io.decode_jpeg(features['image'])labels = features['label']imgH, imgW, imgC = features['imgH'], features['imgW'], features['imgC']shape = [imgH, imgW, imgC]return images, labels, shapedataset = raw_dataset.map(parse)for image, label, shape in dataset:print(label)cv2.imshow('img', image.numpy())cv2.waitKey()

如果遇到需要将 numpy 写入 tfrecord,可以先将 numpy 转为字符串,然后写入;读取的时候再转为 numpy 即可,注意 dtype 的对应。

import numpy as np
gt_row_np = np.array([0, 0, 1, 0], dtype=np.uint8)
gt_row_str = gt_row_np.tostring()
gt_row = np.frombuffer(gt_row_str, dtype=np.uint8)
print('gt_row_np type: {}, dtype: {}, value: {}'.format(type(gt_row_np), gt_row_np.dtype, gt_row_np))
print('gt_row_str type: {}, value: {}'.format(type(gt_row_str), gt_row_str))
print('gt_row type: {}, dtype: {}, value: {}'.format(type(gt_row), gt_row.dtype, gt_row))# output
gt_row_np type: <class 'numpy.ndarray'>, dtype: uint8, value: [0 0 1 0]
gt_row_str type: <class 'bytes'>, value: b'\x00\x00\x01\x00'
gt_row type: <class 'numpy.ndarray'>, dtype: uint8, value: [0 0 1 0]

TFRecord 的写入和读取(序列化和反序列化)相关推荐

  1. python-函数读取内置函数序列化与反序列化

    函数: #!/usr/bin/env python # -*- coding:utf-8 -*- # Author:Vergil Fu#函数 def func1():print('in the fun ...

  2. 【Java-IO】File、搜索删除剪切、字符集、字符编码、字节流、将内存中的数据写入文件、字符流、缓冲流、Scanner、格式化输出、数据流、对象流、序列化与反序列化、Files工具类

    IO 文章目录 IO 简介 File 分隔符.大小写 常用方法 练习:搜索.删除.剪切 字符集(Character Set) 字符编码(Character Encoding) 字符编码比较 乱码 字节 ...

  3. C#对象序列化、反序列化、保存、读取、对象直接保存、读取

    基于WindowForm应用程序C#语言通过实际案例实现将对象保存到文件及从已保存的文件中读取对象(直接保存与读取.通过序列化与反序列化方式进行对象保存与读取) 添加Student类: using S ...

  4. hive serde 序列化与反序列化 - 一行数据写入hive表

    Hive-0.5中SerDe概述 一.背景 1.当进程在进行远程通信时,彼此可以发送各种类型的数据,无论是什么类型的数据都会以二进制序列的形式在网络上传送.发送方需要把对象转化为字节序列才可在网络上传 ...

  5. tfrecord文件生成与读取

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

  6. 十三、序列化和反序列化(部分转载)

    json和pickle序列化和反序列化 json是用来实现不同程序之间的文件交互,由于不同程序之间需要进行文件信息交互,由于用python写的代码可能要与其他语言写的代码进行数据传输,json支持所有 ...

  7. php中序列化与反序列化

    http://www.cnblogs.com/A-Song/archive/2011/12/13/2285619.html 转自:http://qing.weibo.com/tag/unseriali ...

  8. 对象的序列化和反序列化

    为了把对象的成员属性和成员方法进行持久化的保存,需要把对象转换为字节序列,以便于存储,这个过程就叫序列化. 反之,反序列化就是把字节序列恢复成对象. 实现序列化的对象需要实现一个标记接口,并且给这个添 ...

  9. 序列化和反序列化(转)

    转载:http://kb.cnblogs.com/page/515982/ 摘要 序列化和反序列化几乎是工程师们每天都要面对的事情,但是要精确掌握这两个概念并不容易:一方面,它们往往作为框架的一部分出 ...

最新文章

  1. 一文把Redis主从复制、哨兵、Cluster三种模式摸透
  2. 新 IDE 出现,程序员迎来危机?
  3. nyoj 1261 音痴又音痴的LT(离散化+树状数组求K小数)
  4. 【机器视觉】 if算子
  5. react日期格式化实例
  6. mysql单表索引个数_MySQL性能:多个表与单个表和分区上的索引
  7. jsp 如何动态给图片赋值_在Excel表格中你知道如何动态引用图片吗?
  8. Detected that PyTorch and torch_sparse were compiled with different CUDA versions. PyTorch has CUDA
  9. 前端周刊第58期:送你 3 道面试题
  10. java 例子一对小兔子,Java解决标题:有一对兔子,从出生第三个月起每个月都生一对兔子,小兔子长到第三个月后,每个月又生一对兔子。...
  11. 中南大学 10科学计算和 MATLAB 语言 矩阵变换
  12. 上海道宁联合德国think-cell,为您提供更便捷高效的PowerPoint插件
  13. php获取银行logo,PHP实现根据银行卡号判断银行
  14. 计算机是好是坏英语作文,电脑游戏是好还是坏英语作文
  15. 质因子分解算法c语言prime,分解质因数的算法
  16. Y400电脑键帽扣下来和安装上去
  17. eclipse 显示 空格 .回车符号,去掉相应的符号
  18. 程序人生 - 变脸的原理
  19. java谐音,那位有If I were a boy 谐音啊?!
  20. 成员函数和友原函数和一般函数的区别

热门文章

  1. Windows版Sketch软件也太好用了吧!
  2. 一旦出现趋势大阳K线的股票,你就能买在起爆点
  3. 前端手写(二十二)——手写图片懒加载
  4. 二极管反向恢复时间电脑程控测试系统(智能识别示波器曲线)
  5. PageHelper分页插件使用教程
  6. linux运行U盘,构建运行在U盘上的LINUX系统
  7. 云端创建MySQL数据库
  8. 【软件测试】三角形测试用例自动生成工具
  9. python函数:pd.Series()
  10. Python和Stata的数据交互