赞
踩
在初涉tensorflow的时候,一般采用公开数据集进行训练,对于数据集的格式以及读取很不清楚,所以这里给出tensorflow直接读取图像序列的方法,自己进行数据集的构建。下面给出集中可以参考的方法。
一、单张图片读取
1.tensorflow的gfile读取图像,matplotlib用于可视化
使用tensorflow里面给出了一个函数用来读取图像,tf.gfile.FastGFile(‘path’, ‘rb’).read()。读取结果是最原始的图像,没有经过解码。如果要显示读入的图像,则学要解码,tf.image.decode_jepg和tf.image.decode_png分别用于解码jpg格式和png格式的图像,得到图像的像素值,这个像素值可以用于显示图像。
import matplotlib.pyplot as plt
import tensorflow as tf
import numpy as np
image_raw = tf.gfile.FastGFile('00000011.jpg','rb').read() #bytes,相对路径,实验中发现只能是相对路径,绝对路径会bug
img = tf.image.decode_jpeg(image_raw) #Tensor
with tf.Session() as sess:
print(type(image_raw)) # bytes
print(type(img)) # Tensor
print(type(img.eval())) # ndarray
print(img.eval().shape)#(240,320,3)
print(img.eval().dtype)#uint8
plt.figure(1)
plt.imshow(img.eval())
plt.show()
结果:decode输出是Tensor,eval后是ndarray
<class 'bytes'>
<class 'tensorflow.python.framework.ops.Tensor'>
<class 'numpy.ndarray'>
(240, 320, 3)
uint8
图1 读取显示的结果
2.tensorflow的WholeFileReader输入queue
在之前的文章中也使用到了队列读取(http://blog.csdn.net/xuan_zizizi/article/details/78400839),差别在于读取队列的reader不一样,这里首先创建图像的输入队列,然后定义reader,读取序列,读取的进行解码,再得到ndaarry。
import matplotlib.pyplot as plt
import tensorflow as tf
import numpy as np
path = '/home/zcm/tensorf/00000011.jpg'#绝对路径
file_queue = tf.train.string_input_producer([path]) #创建输入队列
image_reader = tf.WholeFileReader() #reader
_, image = image_reader.read(file_queue) #reader读取序列
image = tf.image.decode_jpeg(image) #解码,tensor
with tf.Session() as sess:
coord = tf.train.Coordinator() #协同启动的线程
threads = tf.train.start_queue_runners(sess=sess, coord=coord) #启动线程运行队列
sess.run(image)
print(type(image))#tensor
coord.request_stop() #停止所有的线程
coord.join(threads)
print(type(image.eval()))#ndarray
print(image.eval().shape)#240×320×3
print(image.eval().dtype)#uint8
plt.figure(1)
plt.imshow(image.eval())
plt.show()

结果:decode输出是Tensor,eval后是ndarray,显示图和图1一样,略
<class 'tensorflow.python.framework.ops.Tensor'>
<class 'numpy.ndarray'>
(240, 320, 3)
uint8
3.tensorflow的read_file,decode输出是Tensor,eval后是ndarray
与方法1的gfile读取差别不大,只是换了一个函数read_file
import matplotlib.pyplot as plt
import tensorflow as tf
import numpy as np
image_value = tf.read_file('00000011.jpg')#相对路径,读取
img = tf.image.decode_jpeg(image_value)#解码
with tf.Session() as sess:
print(type(image_value)) #tensor
print(type(img)) # Tensor
print(type(img.eval())) # ndarray
print(img.eval().shape)
print(img.eval().dtype)
plt.figure(1)
plt.imshow(img.eval())
plt.show()
结果:decode输出是Tensor,eval后是ndarray,显示图和图1一样,略
<class 'tensorflow.python.framework.ops.Tensor'>
<class 'tensorflow.python.framework.ops.Tensor'>
<class 'numpy.ndarray'>
(240, 320, 3)
uint8
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。