1、知識點
""" 1、圖片讀取流程與API: 1、構造圖片文件隊列 文件隊列API: a)tf.train.string_input_producer(string_tensor,,shuffle=True) 將輸出字符串(例如文件名)輸入到管道隊列 參數: string_tensor 含有文件名的1階張量 num_epochs:過幾遍數據,默認無限過數據 return:具有輸出字符串的隊列 2、構造圖片閱讀器 圖像讀取API:tf.WholeFileReader 圖像讀取器,將文件的全部內容作為值輸出的讀取器 return:讀取器實例 方法:read(file_queue):輸出將是一個文件名(key)和該文件的內容(值) 3、讀取圖片數據(解碼過程) 圖像解碼器 1、tf.image.decode_jpeg(contents) 將JPEG編碼的圖像解碼為uint8張量 return:uint8張量,3-D形狀[height, width, channels] 2、tf.image.decode_png(contents)將PNG編碼的圖像解碼為uint8或uint16張量 return:張量類型,3-D形狀[height, width, channels] 4、處理圖片數據,固定圖像形狀 縮放圖片:tf.image.resize_images(images, size) 參數: images:4-D形狀[batch, height, width, channels]或3-D形狀的張量[height, width, channels]的圖片數據 size:1-D int32張量:new_height, new_width,圖像的新尺寸 返回4-D格式或者3-D格式圖片 5、進行批處理 1、tf.train.batch(tensors,batch_size,num_threads = 1,capacity = 32,name=None) 讀取指定大小(個數)的張量 參數: tensors:可以是包含張量的列表 batch_size:從隊列中讀取的批處理大小 num_threads:進入隊列的線程數 capacity:整數,隊列中元素的最大數量 return:tensors 2、tf.train.shuffle_batch(tensors,batch_size,capacity,min_after_dequeue,num_threads=1,) 亂序讀取指定大小(個數)的張量 參數: min_after_dequeue:留下隊列里的張量個數,能夠保持隨機打亂 6、線程協調器: tf.train.Coordinator() 線程協調員,實現一個簡單的機制來協調一組線程的終止 方法: request_stop() 請求停止 should_stop() 檢查是否要求停止 join(threads=None, stop_grace_period_secs=120) 等待線程終止 return:線程協調員實例 7、開啟線程操作 tf.train.start_queue_runners(sess=None,coord=None) 收集所有圖中的隊列線程,並啟動線程 參數與返回值: sess:所在的會話中 coord:線程協調器 return:返回所有線程隊列 2、圖像知識 黑白圖(又稱單通道圖):灰度值[0-255] , 一個像素點只有一個值 彩色圖(又稱三通道圖):RGB ,一個像素點有三個值 圖像數字化三要素:長度、寬度、通道數 [height,width,channels] ,[200,200,1] 特征:對於圖片,一個像素表示一個特征 圖像樣本:每一個樣本必須保證特征值數量一樣 圖片二階張量:[100,200*200*1],表示100張40000個特征的黑白圖 圖片三階張量:[200,200,1],表示一張200*200的黑白圖 圖片四階張量:[100,200,200,1]表示100張200*200的黑色圖片 圖片的存儲數據類型:uint8(節約空間) 矩陣計算:float32(提高精度) 3、報錯: 1、Invalid argument: Shape mismatch in tuple component 0. Expected [200,200,3], got [200,200,4] 解決方法:表示數據不匹配,定義為3通道,但是圖片本身是4通道,因此需將定義的3通道改為4通道 """
2、代碼
# coding = utf-8 import tensorflow as tf import os def readPic(filelist): """ 讀取圖片 :param filelist: 文件路徑+名字列表名 :return:每張圖片的張量 """ #1、構造文件隊列 file_queue = tf.train.string_input_producer(file_list) #2、構造閱讀器去讀取圖片內容(默認讀取一張圖片) reader = tf.WholeFileReader() key , value = reader.read(file_queue) #3、對讀取的圖片進行解碼 image = tf.image.decode_jpeg(value) #4、處理圖像大小 image_size = tf.image.resize_images(image,[200,200]) #print(image_size) #注意:一定要把樣本的形狀固定 [200,200,3],在批處理的時候要求所有圖像形狀固定且一致 image_size.set_shape([200,200,3]) #print(image_size) #5、進行批處理 image_batch = tf.train.batch([image_size], batch_size=20, num_threads=1, capacity=20) print(image_batch) return image_batch if __name__ == '__main__': file_name = os.listdir("./pic") file_list = [os.path.join("./pic",file) for file in file_name] image_batch = readPic(file_list) #print(image_batch) #開啟會話 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)