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)