1. 程式人生 > 實用技巧 >tensorflow 讀取圖片的方式

tensorflow 讀取圖片的方式

1、string_input_producer(filelist)#將資料夾內的圖片組成batch

import tensorflow as tf
import os


def picread(filelist):
    """
    讀取狗的圖片並轉換成張量
    :param filelist: 檔案路f徑+名字的列表
    :return: 每張圖片的張量
    """
    # 1.構造檔案的佇列
    file_queue = tf.train.string_input_producer(filelist)

    # 2.構造閱讀器去讀取圖片內容(預設讀取一張圖片)
reader = tf.WholeFileReader() key,value = reader.read(file_queue) # 3.對讀取的圖片進行解碼 image = tf.image.decode_jpeg(value) # 4.處理圖片的大小(統一大小) image_resize = tf.image.resize_images(image,[200,200]) # 注意:一定要把樣本的形狀固定,在批處理中要求所有資料的形狀必須固定 image_resize.set_shape([200,200,3]) # 5.進行批處理
image_resize_batch = tf.train.batch([image_resize],batch_size=3,num_threads=1,capacity=3) return image_resize #批處理大小,跟佇列,資料的數量沒有影響,只決定 這批次處理多少資料 if __name__ == "__main__": # 1.找到檔案,放入列表 路徑+名字 ->列表當中 file_name = os.listdir("./data/dogpic/") filelist = [os.path.join("./data/dogpic/
",file) for file in file_name ] image_batch= picread(filelist) #開啟會話執行結果 with tf.Session() as sess: #定義一個執行緒協調器 coord = tf.train.Coordinator() #開啟讀檔案的執行緒 threads = tf.train.start_queue_runners(sess,coord=coord) #列印讀取的內容 print(sess.run([image_batch])) #回收子執行緒 coord.request_stop() coord.join(threads)