方法一:直接使用tensorflow提供的函數image = tf.gfile.FastGFile('PATH')來讀取一副圖片:
import matplotlib.pyplot as plt; import tensorflow as tf; % matplotlib inline #將matplotlib繪制的圖像直接輸出到當前交互式的框架下 image_raw_data_jpg = tf.gfile.FastGFile('home/ubuntu-mm/TensorFlow/Learning/D-TestJupyter/image/Train/Pic.jpg', 'r').read() with tf.Session() as sess: img_data_jpg = tf.image.decode_jpeg(image_raw_data_jpg) #圖像解碼 img_data_jpg = tf.image.convert_image_dtype(img_data_jpg, dtype=tf.uint8) #改變圖像數據的類型 plt.figure(1) #圖像顯示 plt.imshow(img_data_jpg.eval())
print sess.run(img_data_jpg)
我用的是基於Ubuntu16.04操作系統下的Jupyter來編寫的程序,CPU版本(記得加% matplotlib inline就能顯示出圖像了)

實驗的結果如下所示:

方法二:將圖像加載到創建好的隊列中使用tf.train.string_input_producer(),然后再加載到變量當中:
import tensorflow as tf; import matplotlib.pyplot as plt path = '/home/ubuntu-mm/TesorFlow/Learning/D-TestJupyter/images/Train/Pic.jpg' file_queue = tf.train.string_input_producer([path]) #創建輸入隊列 image_reader = tf.WholeFileReader() _, image = image_reader.read(file_queue) image = tf.image.decode_jpeg(image) with tf.Session() as sess: coord = tf.train.Coordinator() #協同啟動的線程 threads = tf.train.start_queue_runners(sess=sess, coord=coord) #啟動線程運行隊列 print sess.run(image) coord.request_stop() #停止所有的線程 coord.join(threads) image_uint8 = tf.image.convert_image_dtype(image, dtype = tf.uint8) plt.imshow(image_uint8.eval())

實驗結果如下所示:

