创建和读取tfrecords

创建和读取tfrecords

创建tfrecords

# create tfrecords
import tensorflow as tf 
import numpy as np 

tfrecords_filename = './data/train.tfrecords'
writer = tf.python_io.TFRecordWriter(tfrecords_filename) # 创建.tfrecord文件,准备写入

for i in range(100):
    img_raw = np.random.random_integers(0,255,size=(7,30)) # 创建7*30,取值在0-255之间随机数组
    img_raw = img_raw.tostring()
    example = tf.train.Example(features=tf.train.Features(
            feature={
            'label': tf.train.Feature(float_list = tf.train.FloatList(value=[i])),     
            'img_raw':tf.train.Feature(bytes_list = tf.train.BytesList(value=[img_raw]))
            }))
    writer.write(example.SerializeToString())
    print(i) 
 
writer.close()

读取tfrecords

# read tfrecords
import tensorflow as tf 

if __name__=='__main__':
    tfrecords_filename = "./data/train.tfrecords"
    #test_write_to_tfrecords(tfrecords_filename)
    filename_queue = tf.train.string_input_producer([tfrecords_filename],) #读入流中
    reader = tf.TFRecordReader()
    _, serialized_example = reader.read(filename_queue)   #返回文件名和文件
    features = tf.parse_single_example(serialized_example,
                                       features={
                                           'label': tf.FixedLenFeature([], tf.float32),
                                           'img_raw' : tf.FixedLenFeature([], tf.string),
                                       })  #取出包含image和label的feature对象
    image = tf.decode_raw(features['img_raw'],tf.int64)
    image = tf.reshape(image, [7,30])
    label = tf.cast(features['label'], tf.float32)
    with tf.Session() as sess: #开始一个会话
        init_op = tf.initialize_all_variables()
        sess.run(init_op)
        coord=tf.train.Coordinator()
        threads= tf.train.start_queue_runners(coord=coord)
        for i in range(3):
            example, l = sess.run([image,label])#在会话中取出image和label
            #img=Image.fromarray(example, 'RGB')#这里Image是之前提到的
            #img.save('./'+str(i)+'_''Label_'+str(l)+'.jpg')#存下图片
            print(example, l)
 
        coord.request_stop()
        coord.join(threads)


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值