TensorFlow------读取图片实例

TensorFlow------读取图片实例:

import tensorflow as tf
import os


def readpic(filelist):
    '''
    读取人物图片并转换成张量
    :param filelist: 文件路径+名字列表
    :return: 每张图片的张量
    '''
    # 1. 构建文件队列
    file_queue = tf.train.string_input_producer(filelist)

    # 2. 构建阅读器去读取图片内容(默认读取一张图片)
    reader = tf.WholeFileReader()

    key, value = reader.read(file_queue)

    print(value)
    # 3. 对读取的图片进行数据解码
    image = tf.image.decode_jpeg(value)

    print(image)

    # 4. 处理图片的大小(统一大小)
    image_resize = tf.image.resize_images(image,[200,200])

    # 注意:一定要把样本的形状固定 [200,200,3],在批处理的时候要求所有数据形状必须定义
    image_resize.set_shape([200,200,3])

    print(image_resize)

    # 5. 进行批处理
    image_batch = tf.train.batch([image_resize],batch_size=10,num_threads=1,capacity=20)

    print(image_batch)
    return image_batch


if __name__ == '__main__':
    # 找到文件,构建列表
    filename = os.listdir('./images/pic/')

    # 拼接路径 重新组成列表
    filelist = [os.path.join('./images/pic/',file) for file in filename]

    # 调用函数传参
    image_batch = readpic(filelist)

    # 开启会话
    with tf.Session() as sess:
        # 定义一个线程协调器
        coord = tf.train.Coordinator()

        # 开启读文件的线程
        threads = tf.train.start_queue_runners(sess,coord=coord)

        # 打印读取的内容
        print(sess.run([image_batch]))


        # 回收子线程
        coord.request_stop()

        coord.join(threads)
原文地址:https://www.cnblogs.com/fwl8888/p/9762461.html