1. 通过tf.gfile.FastGFile()读取图像文件
tf.Gfile模块提供了tf中通用的文件 I/O 操作。
tf.Gfile.FastGFile(filename,mode)函数用于获取文件操作句柄,类似于python中的文本操作open()函数。
第一个参数filename数文件路径,第二个参数mode是文件编码方式("r": UTF-8编码; "rb":非UTF-8编码)。
# coding: utf-8
import matplotlib.pyplot as plt
import tensorflow as tf
# 读入二进制文件
image_raw = tf.gfile.FastGFile('test.jpg','rb').read()
# 解码为tf中的图像格式
img = tf.image.decode_jpeg(image_raw) #Tensor
with tf.Session() as sess:
img_ = img.eval()
print(img_.shape)
plt.figure(1)
plt.imshow(img_)
plt.show()
2. 通过tf.train.string_input_producer()+tf.WholeFileReader().read()读入图片文件
tf.train.string_input_producer()方法把所有数据打包成一个自动维护的内部队列,tf每次从这个序列中读取一部分数据,这个方法适用于读取的图片数据过多,无法一次性读入内存的情况。
tf.WholeFileReader().read()是跟tf中的队列机制配合使用的文件阅读器。
# coding: utf-8
import matplotlib.pyplot as plt
import tensorflow as tf
file_list = ['./test.jpg'] # 所有图片的列表
# 创建输入队列,默认顺序打乱
file_queue = tf.train.string_input_producer(file_list, shuffle=True, num_epochs=2)
key, image = tf.WholeFileReader().read(file_queue)
image = tf.image.decode_jpeg(image) #解码成tf中图像格式
with tf.Session() as sess:
tf.local_variables_initializer().run()
threads = tf.train.start_queue_runners(sess=sess)
for _ in file_list:
img = image.eval() # 执行
plt.figure(1)
plt.imshow(img)
plt.show()
3. 通过tf.read_file()读入图片文件
# coding: utf-8
import matplotlib.pyplot as plt
import tensorflow as tf
image_value = tf.read_file('test.jpg')
img = tf.image.decode_jpeg(image_value, channels=3)
with tf.Session() as sess:
img_ = img.eval()
print(img_.shape)
print(img_.dtype)
plt.figure(1)
plt.imshow(img_)
plt.show()
4. 通过scipy.misc.imread()函数读入图片文件
另一种tf程序中经常用到的工具是scipy(Python中的库)。Scipy库构建于Numpy之上,提供了一个用于在Python中进行科学计算的工具集,如数值计算的算法和一些功能函数,可以方便的处理数据。
# coding: utf-8
import matplotlib.pyplot as plt
import tensorflow as tf
import scipy.misc
img = scipy.misc.imread('test.jpg',mode='RGB')
print(img.shape)
plt.figure(1)
plt.imshow(img)
plt.show()