tensorflow圖像處理函數(1)
阿新 • • 發佈:2018-03-07
沒有 fas div img OS session gpo 數據 blog
1、tensorflow中對jpeg格式圖像的編碼/解碼函數:
import matplotlib.pyplot as plt import tensorflow as tf image_raw_data=tf.gfile.FastGFile(‘/Users/jk/Downloads/timg.jpeg‘,‘rb‘).read() with tf.Session() as sess: img_data=tf.image.decode_jpeg(image_raw_data) #通過tf.img.decode_jpeg函數對jpeg格式的圖像進行解碼,解碼後的結果為一個張量 print(img_data.eval()) #輸出解碼後的三維矩陣 plt.imshow(img_data.eval()) plt.show() img_data=tf.image.convert_image_dtype(img_data,dtype=tf.uint8) encode_image=tf.image.encode_jpeg(img_data) #將圖像的三維矩陣重新按照jpeg格式編碼存入文件,打開該圖像可以得到和原始圖像一樣的圖像 with tf.gfile.GFile(‘/Users/jk/Downloads/output‘,‘wb‘) as f: #將文件寫入目標路徑,生成圖像文件 f.write(encode_image.eval())
2、圖像大小調整(和上面的類似,僅多了圖像大小調整的部分,下面的例子將類似):
import matplotlib.pyplot as plt import tensorflow as tf image_raw_data=tf.gfile.FastGFile(‘/Users/jk/Downloads/timg.jpeg‘,‘rb‘).read() with tf.Session() as sess: img_data=tf.image.decode_jpeg(image_raw_data)print(img_data.eval()) plt.imshow(img_data.eval()) plt.show() img_data=tf.image.convert_image_dtype(img_data,dtype=tf.uint8) resized=tf.image.resize_images(img_data,size=[300,300],method=1) #將圖像大小轉為[300,300],圖像深度在沒有明確設置前會是?, print(resized.get_shape()) resized=tf.image.convert_image_dtype(resized,dtype=tf.uint8) #數據預處理時候會把dtype轉為tf.float32,因此需要手動轉回tf.uint8 encode_image=tf.image.encode_jpeg(resized) with tf.gfile.GFile(‘/Users/jk/Downloads/output‘,‘wb‘) as f: #返回調整大小後的圖像 f.write(encode_image.eval())
tensorflow圖像處理函數(1)