TensorFlow讀取資料

來源:互聯網
上載者:User

本文介紹如何使用TensorFlow來讀取圖片資料,主要介紹寫入TFRecord檔案再讀取和直接使用隊列來讀取兩種方式。假設我們圖片目錄結構如下:

|---a|   |---1.jpg|   |---2.jpg|   |---3.jpg||---b|   |---1.jpg|   |---2.jpg|   |---3.jpg||---c|   |---1.jpg|   |---2.jpg|   |---3.jpg
1 使用TFRecoder

思路:思路:使用TFRecod主要是把每張圖片及其對應的label寫入到一個tfrecode檔案中。tfrecode以二進位形式儲存,其中內部使用了protobuf定義協議,即定義格式序列化為二進位。我們可以使用tf提供的tf.train.Example來指定序列化格式。將a目錄中所有的檔案的label指定為a,另外兩個目錄b、c同理。

代碼如下:

def build_data(dir,file_str,map_str):    '''    :param dir: 根目錄,dir下所有子目錄名稱為label    :param file_str: 匯出的tfrecorde檔案    :param map_str: 數字序號0~n與label映射關係儲存路徑    :return:    '''    files=os.listdir(dir);    writer = tf.python_io.TFRecordWriter(file_str)  # 要產生的檔案    # 由於tf.train.Feature只能取float、int和bytes,因此需要將label映射到int,儲存到檔案    map_file = open(map_str,'w')    for index,label in enumerate(files):     #遍曆檔案夾        data_dir = os.path.join(dir,label)        map_file.write(str(index) + ":" + label + "\n")        for img_name in os.listdir(data_dir):  #遍曆圖片            img_path=os.path.join(data_dir,img_name)            img = Image.open(img_path)         #讀取圖片            img = img.resize((256, 256))       #將圖片寬高轉為256*256            img_raw=img.tobytes()              #圖片轉為位元組            example=tf.train.Example(features=tf.train.Features(feature={                'label': tf.train.Feature(int64_list=tf.train.Int64List(value=[index])),                'img': tf.train.Feature(bytes_list=tf.train.BytesList(value=[img_raw]))            }))            writer.write(example.SerializeToString())  # 序列化為字串並寫入檔案    writer.close()    map_file.close();

接下來是讀取tfrecord檔案。注意讀取時label、img名稱及類型要一致:

def read_data(file_str):    # 根據檔案名稱產生一個隊列    file_path_queue = tf.train.string_input_producer([file_str])    reader = tf.TFRecordReader()    _, serialized_example = reader.read(file_path_queue)  # 返迴文件名和檔案    features = tf.parse_single_example(serialized_example,                                       features={                                           'label': tf.FixedLenFeature([], tf.int64),                                           'img': tf.FixedLenFeature([], tf.string),                                       })    label = tf.cast(features['label'], tf.int64)       # 讀取label    img = tf.decode_raw(features['img'], tf.uint8)    img = tf.reshape(img, [256, 256, 3])               #將維度轉為256*256的3通道    img = tf.cast(img, tf.float32) * (1. / 255) - 0.5  #將圖片中的資料轉為[-0.5,0.5]    return img, label

接下來看看如何使用:

build_data("D:/test","D:/data/tf.tfrecorde","D:/data/map.txt")img, label =read_data("D:/data/tf.tfrecorde")#使用shuffle_batch可以隨機打亂輸入img_batch, label_batch = tf.train.shuffle_batch([img, label],                                                batch_size=30, capacity=2000,                                                min_after_dequeue=1000)init = tf.initialize_all_variables()with tf.Session() as sess:    sess.run(init)    threads = tf.train.start_queue_runners(sess=sess)    for i in range(3):        imgs, labels= sess.run([img_batch, label_batch])        #我們也可以根據需要對val, l進行處理         print(imgs.shape, labels)

運行結果如下:

(30, 256, 256, 3) [1 2 2 1 1 2 2 1 0 1 0 1 0 0 2 0 0 0 2 1 1 1 1 0 0 1 2 1 2 0](30, 256, 256, 3) [2 1 1 0 0 1 1 0 2 2 2 0 0 0 0 2 1 0 0 2 0 0 2 2 2 1 0 1 0 2](30, 256, 256, 3) [2 0 2 0 1 2 1 2 2 1 0 2 0 0 2 2 2 1 1 1 1 1 0 0 2 0 2 2 0 0]

從結果可以看出,雖然我們提供的圖片只有9張。每一類各3張,但是能讀取30*30*30張出來,這主要是通過迴圈讀取得到的。也就是說數量上雖然增加了,但實際上也就是那9張圖片。 2 不使用TFRecord

TFRecord適合將標籤、圖片資料等其他相關的資料一起封裝到一個對象,然後逐個讀取。有時候,我們並不需要標籤,只需要對圖片讀取。那麼可以考慮之間從路徑隊列中讀取,而不需要轉到TFRecord檔案。

直接上代碼:

def read_data(dir ):    '''    :param dir: 圖片根目錄    '''    input_paths = glob.glob(os.path.join(dir, "*.jpg"))    decode = tf.image.decode_jpeg    if len(input_paths) == 0:    #如果不存在jpg圖片,則遍曆png圖片        input_paths = glob.glob(os.path.join(dir, "*.png"))        decode = tf.image.decode_png    if len(input_paths) == 0:    #如果png圖片不存在,拋出異常        raise Exception("input_dir contains no image files")    #產生檔案路徑隊列,並且打亂順序    path_queue = tf.train.string_input_producer(input_paths, shuffle=True)    reader = tf.WholeFileReader()   #建立讀取檔案對象    paths, contents = reader.read(path_queue) #從隊列中讀取    img_raw = decode(contents)    # 將圖片縮小到256*256,如果在此之前對圖片預先處理(放縮),那麼這一步可省略    img_raw = tf.image.resize_images(img_raw, [256, 256])    img_raw = tf.image.convert_image_dtype(img_raw, dtype=tf.float32)    img_raw.set_shape([256, 256, 3])#設定shape    return img_raw

接下來看看如何使用:

img = read_data("D:/test/*" )img_batch = tf.train.batch([img], batch_size=30)init = tf.initialize_all_variables()with tf.Session() as sess:    sess.run(init)    threads = tf.train.start_queue_runners(sess=sess)    for i in range(3):        imgs = sess.run( img_batch )        print(imgs.shape )

看看運行結果:

(30, 256, 256, 3)(30, 256, 256, 3)(30, 256, 256, 3)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.