Tensorflow读取图片并转换成张量

使用神经网络对图片文件进行训练时,需要将图片信息转换为张量,这里介绍如何将图片信息转化为Tensorflow的张量信息。

本文完整代码:https://github.com/iapcoder/TensorflowReadIMG


一 步骤

1、构造文件队列

file_queue = tf.train.string_input_producer(file_list, shuffle=True) #file_list:图片路径列表,shuffle: True表示随机打乱顺序,返回一个队列

2、构造图像阅读器读取图片内容(默认只读取一张图片)

reader = tf.WholeFileReader()
key, value = reader.read(file_queue) # key:文件名 value:文件内容

3、对读取的数据进行解码(不同的图片格式有不同的解码方式),以jpeg格式为例

image = tf.image.decode_jpeg(value)

4、处理图片的大小、使得每个样本的height、weight一样,方便后续处理

image_resize = tf.image.resize_image(image, [100,100]) # 将图片处理成100*100像素

5、固定样本形状[height, weight, channels],批处理时要求形状固定

image_resize.set_shape([100,100,3])

6、批处理文件

image_batch = tf.train.batch([image_resize], batch_size=4, num_threads=1, capacity=4) # batch_size:批处理多少个样本 num_thrads:指定线程数 capacity:队列容量

7、开启会话运行

with tf.Session() as sess:
    coord = tf.train.coordinator() # 定义线程协调器
    threads = tf.train.start_queue_runner(sess, coord=coord) # 开启线程
    image_data = sess.run([image_batch])
    coord.request_stop() #请求关闭线程
    coord.join(threads) #等待线程终止

二 实例

假设文件中有四张图片

将四张图片转换为100*100*3的张量

猜你喜欢

转载自blog.csdn.net/qq_41689620/article/details/88778790