Tensorflow—tfrecord数据集生成与使用
生活随笔
收集整理的這篇文章主要介紹了
Tensorflow—tfrecord数据集生成与使用
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
參考內容:
數據讀取的官方教程:Tensorflow導入數據以及使用數據?
tfrecord數據集生成:
數據準備:圖片數據+圖片目錄與label一一對應的的txt
先讀取圖片信息的txt文件,得到每個圖片的路徑以及它們的標簽,然后對這個圖片作一些預處理,最后將圖片以及它對應的標簽序列化,并建立圖片和標簽的索引(即以下代碼的”img_raw”, “label”)。詳見代碼。?
import random import tensorflow as tf from PIL import Imagedef create_record(records_path, data_path, img_txt):# 聲明一個TFRecordWriterwriter = tf.python_io.TFRecordWriter(records_path)# 讀取圖片信息,并且將讀入的圖片順序打亂img_list = []with open(img_txt, 'r') as fr:img_list = fr.readlines()random.shuffle(img_list)cnt = 0# 遍歷每一張圖片信息for img_info in img_list:# 圖片相對路徑img_name = img_info.split(' ')[0]# 圖片類別img_cls = int(img_info.split(' ')[1])img_path = data_path + img_nameimg = Image.open(img_path)# 對圖片進行預處理(縮放,減去均值,二值化等等)img = img.resize((128, 128))img_raw = img.tobytes()# 聲明將要寫入tfrecord的key值(即圖片,標簽)example = tf.train.Example(features=tf.train.Features(feature={"label": tf.train.Feature(int64_list=tf.train.Int64List(value=[img_cls])),'img_raw': tf.train.Feature(bytes_list=tf.train.BytesList(value=[img_raw]))}))# 將信息寫入指定路徑writer.write(example.SerializeToString())# 打印一些提示信息~cnt += 1if cnt % 1000 == 0:print "processed %d images" % cntwriter.close()# 指定你想要生成tfrecord名稱,圖片文件夾路徑,含有圖片信息的txt文件 records_path = '/the/name/of/your/haha.tfrecords' data_path = '/the/root/of/your/image_folder/' img_txt = '/image/labels/list.txt' create_record(records_path, data_path, img_txt)?tfrecord數據集使用:
目前為止,使用TFrecord最方便的方式是用TensorFlow的Dataset ApI。在這里,勸大家千萬千萬不要用queue的方式讀取數據(麻煩且已經過時)。?
??首先,我們定義好_parse_function,這個函數是用來指定TFrecord中索引的(即上文中的”img_raw”, “label”)。然后我們定義一個TFRecordDataset,并借助_parse_function來讀取數據。最后,為了得到每一輪的訓練數據,我們只需要再額外聲明一個iterator,每次調用get_next()就可以啦。
?
?
總結
以上是生活随笔為你收集整理的Tensorflow—tfrecord数据集生成与使用的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: linux安装cv2踩坑
- 下一篇: resnet50训练imagenet记录