Tensorflow學習教程------tfrecords數據格式生成與讀取


首先是生成tfrecords格式的數據,具體代碼如下:

#coding:utf-8

import os
import tensorflow as tf 
from PIL import Image

cwd = os.getcwd() 

'''
此處我加載的數據目錄如下:
bt -- 14018.jpg
      14019.jpg
      14020.jpg

nbt -- 1_ddd.jpg
       1_dsdfs.jpg
       1_dfd.jpg

這里的bt nbt 就是類別,也就是代碼中的classes 
'''

writer = tf.python_io.TFRecordWriter("train.tfrecords")
classes = ['bt','nbt']
for index, name in enumerate(classes):
    class_path = cwd + '/'+ name +'/' #每一類圖片的目錄地址
    for img_name in os.listdir(class_path):
        img_path = class_path + img_name #每一張圖片的路徑
        img = Image.open(img_path)
        img = img.resize((224,224)) 
        img_raw = img.tobytes()   #將圖片轉化為原生bytes
        example = tf.train.Example(features = tf.train.Features(feature={
            'label':tf.train.Feature(int64_list = tf.train.Int64List(value=[index])),
            'img_raw':tf.train.Feature(bytes_list = tf.train.BytesList(value=[img_raw]))
     }))
        print "write" + ' ' + str(img_path) + "to train.tfrecords."
        writer.write(example.SerializeToString()) #序列化為字符串
writer.close()

然后讀取生成的tfrecords數據,並且將tfrecords里面的數據保存成jpg格式的圖片。具體代碼如下:

#coding:utf-8
import os 
import tensorflow as tf
from PIL import Image 
cwd = '/media/project/tfLearnning/dataread/pic/'
def read_and_decode(filename):
    #根據文件名生成一個隊列
    filename_queue = tf.train.string_input_producer([filename])

    reader = tf.TFRecordReader()
    _, serialized_example = reader.read(filename_queue) #返回文件名和文件
    
    features = tf.parse_single_example(serialized_example,
                                       features={
                                       'label':tf.FixedLenFeature([],tf.int64),
                                       'img_raw':tf.FixedLenFeature([],tf.string),
                                       })
    img = tf.decode_raw(features['img_raw'],tf.uint8)
    img = tf.reshape(img,[224,224,3])
    #img = tf.cast(img,tf.float32) * (1./255) - 0.5 # 將圖片變成tensor
                                                   #對圖片進行歸一化操作將【0,255】之間的像素歸一化到【-0.5,0.5】,標准化處理可以使得不同的特征具有相同的尺度(Scale)。
                                                   #這樣,在使用梯度下降法學習參數的時候,不同特征對參數的影響程度就一樣了
    label = tf.cast(features['label'], tf.int32) #將標簽轉化tensor
    print img
    print label
    return img, label

#read_and_decode('train.tfrecords')
img, label = read_and_decode('train.tfrecords')
#print img.shape, label
img_batch, label_batch = tf.train.shuffle_batch([img,label],batch_size=10,capacity=2000,min_after_dequeue=1000) #形成一個batch的數據,由於使用shuffle,因此每次取batch的時候
                                                                                                                #都是隨機取的,可以使樣本盡可能被充分地訓練,保證min_after值小於capacit值

init = tf.global_variables_initializer()

with tf.Session() as sess:
    sess.run(init)
    # 創建一個協調器,管理線程
    coord = tf.train.Coordinator()
    # 啟動QueueRunner, 此時文件名隊列已經進隊
    threads = tf.train.start_queue_runners(sess=sess, coord=coord)
    for i in range(10):
        example, l = sess.run([img, label]) #從對列中一張一張讀取圖片和標簽
        #example, l = sess.run([img_batch,label_batch])
        print(example.shape,l)
        
        img1=Image.fromarray(example, 'RGB') #將tensor轉化成圖片格式
        img1.save(cwd+str(i)+'_'+'Label_'+str(l)+'.jpg')#save image
    # 通知其他線程關閉
    coord.request_stop()
    # 其他所有線程關閉之后,這一函數才能返回
    coord.join(threads)

 


免責聲明!

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



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