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


方式一:通过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()

  • 10
    点赞
  • 76
    收藏
    觉得还不错? 一键收藏
  • 4
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值