TensorFlow------讀取圖片實例:
import tensorflow as tf import os def readpic(filelist): ''' 讀取人物圖片並轉換成張量 :param filelist: 文件路徑+名字列表 :return: 每張圖片的張量 ''' # 1. 構建文件隊列 file_queue = tf.train.string_input_producer(filelist) # 2. 構建閱讀器去讀取圖片內容(默認讀取一張圖片) reader = tf.WholeFileReader() key, value = reader.read(file_queue) print(value) # 3. 對讀取的圖片進行數據解碼 image = tf.image.decode_jpeg(value) print(image) # 4. 處理圖片的大小(統一大小) image_resize = tf.image.resize_images(image,[200,200]) # 注意:一定要把樣本的形狀固定 [200,200,3],在批處理的時候要求所有數據形狀必須定義 image_resize.set_shape([200,200,3]) print(image_resize) # 5. 進行批處理 image_batch = tf.train.batch([image_resize],batch_size=10,num_threads=1,capacity=20) print(image_batch) return image_batch if __name__ == '__main__': # 找到文件,構建列表 filename = os.listdir('./images/pic/') # 拼接路徑 重新組成列表 filelist = [os.path.join('./images/pic/',file) for file in filename] # 調用函數傳參 image_batch = readpic(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)
