TFRecord 读取图像和标签

 1 #-*- coding:utf-8 -*-
 2 import tensorflow as tf
 3 from PIL import Image
 4 
 5 cwd = 'f:/py/tfrecord/aa/'          # 读取图片后存放的文件路径
 6 filename = tf.train.string_input_producer(['f:/py/tfrecord/train.tfrecords'])
 7 reader = tf.TFRecordReader()          # 建立reader
 8 _,serializer = reader.read(filename)  # 读取文件
 9 
10 # 以下是需要读取的的内容,key与存放时的一致,tf.FixedLenFeature([],tf.string)的tf.string也要与存放时的一致
11 feature = tf.parse_single_example(serializer,features={'label':tf.FixedLenFeature([],tf.string),
12                                                        'img_raw':tf.FixedLenFeature([],tf.string),
13                                                        'img_w': tf.FixedLenFeature([], tf.int64),
14                                                        'img_h': tf.FixedLenFeature([], tf.int64),
15                                                        'img_c': tf.FixedLenFeature([], tf.int64)})
16 
17 '''
18 # img取出的格式是string,需要转换为tf.uint8,这五个参数都只是设定好,还没实际运行。
19 # 如果取出图片是统一的shape,就可以在
20 '''
21 img = tf.decode_raw(feature['img_raw'],tf.uint8)
22 img_w = feature['img_w']    #图像的宽,int
23 img_h = feature['img_h']    #图像的高,int
24 img_c = feature['img_c']    #图像的通道数,int
25 label = feature['label']    #图像的标签,bytes    输出为 b'japandog',所以下面需要decode
26 # img = tf.reshape(img,[256,256,3]) 如果想要固定图片的shape,就可以在这里添加这句,如果要原图的shape,只能在取出img_w,img_h,img_c之后,再使用tf.reshape(),否则会报错。
27 with tf.Session() as sess: #开始一个会话
28     coord=tf.train.Coordinator()
29     threads= tf.train.start_queue_runners(coord=coord)
30     for i in range(10):
31         example,w,h,c,label_out = sess.run([img,img_w,img_h,img_c,label])
32         label_out=label_out.decode('utf-8')
33         img_new = sess.run(tf.reshape(example, [w,h,c])) # tf.reshape需要sess.run()
34         img_show=Image.fromarray(img_new)
35         img_show.save(cwd+str(i)+label_out+'.jpg')
36     coord.request_stop()
37     coord.join(threads)

猜你喜欢

转载自www.cnblogs.com/xinghun85/p/9119858.html