TFRecord 使用总结

TFRecord

  1. 简介
    TFrecord 是TensorFlow使用的一种数据格式,他可以把多个训练的图片许多信息压缩在一个文件中,用特殊的方式存储和读取,通过tf.dataset 这个API进行快速的读取和写入。具体使用官方教材,参考官方文档,里面有具体的使用方法,最近又出了高阶的使用方法,等流程跑通了再继续优化,Tensflow公众号-tf.data API,构建高性能 TensorFlow 输入管道

  2. 读取图片时使用tf.gfile.GFile()

#使用GFile读取图片会快,而且文件会压缩,如果用opencv读取,文件会特别大
  with tf.gfile.GFile(img_path, 'rb') as fid:
        encoded_png = fid.read()
  1. 文件的压缩和解压
#我这里加了压缩的选项,到时候读取时也要添加解压选项
   writer_options = tf.python_io.TFRecordOptions(
        tf.python_io.TFRecordCompressionType.ZLIB)
    writer = tf.python_io.TFRecordWriter(
        path=save_path, options=writer_options)

#在读取的时候,也要用ZLIB方式解压
#读取到dataset里
dataset = tf.data.TFRecordDataset(filenames, compression_type='ZLIB')

4.图片解码时最好定义好通道类型

#解码是  最好定义好channel,我默认读取图片后,有的会解码为 1通道的,影响后面的reshape
image = tf.image.decode_image(parsed["img"],channels=3)
#还原会原来的形状,对了,图片集一定要提前检查好图像的大小是否一致,要不解码也会出问题
image = tf.reshape(image, [32,32,3])
#转为灰度图,放入训练集
gray = tf.image.rgb_to_grayscale(image)
  1. 中文要加encode(‘utf-8’)
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]))


def img_to_feature(img_path, index, label):
    with tf.gfile.GFile(img_path, 'rb') as fid:
        encoded_png = fid.read()
    image_format = img_path.split('.')[-1]

    feature = tf.train.Features(feature={
        'img': _bytes_feature(encoded_png),
        'index':  _int64_feature(index),
        'img_path':  _bytes_feature(img_path.encode('utf8'))

    })
    return feature

#解码的时候,再需要转码回来
with tf.Session() as sess:
    sess.run(iterator.initializer)
    while True:
        try:
            label,img_path,image=sess.run(next_element)
            print(img_path.decode('utf-8'))
        except tf.errors.OutOfRangeError:
            break
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值