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)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM