tensorflow中几种读取图片文件并显示方法

版权声明:本文为博主原创文章,转载请注明出处。 https://blog.csdn.net/dcrmg/article/details/82422999


方式一:通过tf.gfile.FastGFile()读取图像文件

tf.gfile模块提供了tensorflow中通用的文件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()


方法二: 通过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()


方法三: 通过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()

方法四:通过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()

猜你喜欢

转载自blog.csdn.net/dcrmg/article/details/82422999