当前位置:
首页
文章
前端
详情

tensorflow 使用队列读取图像文件

读取指定文件夹中的图像文件,使用多进程将文件读取到一个队列中,然后再取

参考

https://blog.csdn.net/dcrmg/article/details/79776876?utm_source=blogxgwz0

def slice_input_producer(tensor_list, num_epochs=None, shuffle=True, seed=None,
                         capacity=32, shared_name=None, name=None):



    input_queue = tf.train.slice_input_producer([images, labels])

    label = input_queue[1]
    image_contents = tf.read_file(input_queue[0])

第一个参数 tensor_list:包含一系列tensor的列表,表中tensor的第一维度的值必须相等,即个数必须相等,有多少个图像,就应该有多少个对应的标签。
第二个参数num_epochs: 可选参数,是一个整数值,代表迭代的次数,如果设置 num_epochs=None,生成器可以无限次遍历tensor列表,如果设置为 num_epochs=N,生成器只能遍历tensor列表N次。
第三个参数shuffle: bool类型,设置是否打乱样本的顺序。一般情况下,如果shuffle=True,生成的样本顺序就被打乱了,在批处理的时候不需要再次打乱样本,使用 tf.train.batch函数就可以了;如果shuffle=False,就需要在批处理时候使用 tf.train.shuffle_batch函数打乱样本。
第四个参数seed: 可选的整数,是生成随机数的种子,在第三个参数设置为shuffle=True的情况下才有用。
第五个参数capacity:设置tensor列表的容量。
第六个参数shared_name:可选参数,如果设置一个‘shared_name’,则在不同的上下文环境(Session)中可以通过这个名字共享生成的tensor。
第七个参数name:可选,设置操作的名称。  

def batch(tensors, batch_size, num_threads=1, capacity=32,
          enqueue_many=False, shapes=None, dynamic_pad=False,
          allow_smaller_final_batch=False, shared_name=None, name=None):

第一个参数tensors:tensor序列或tensor字典,可以是含有单个样本的序列;
第二个参数batch_size: 生成的batch的大小;
第三个参数num_threads:执行tensor入队操作的线程数量,可以设置使用多个线程同时并行执行,提高运行效率,但也不是数量越多越好;
第四个参数capacity: 定义生成的tensor序列的最大容量;
第五个参数enqueue_many: 定义第一个传入参数tensors是多个tensor组成的序列,还是单个tensor;
第六个参数shapes: 可选参数,默认是推测出的传入的tensor的形状;
第七个参数dynamic_pad: 定义是否允许输入的tensors具有不同的形状,设置为True,会把输入的具有不同形状的tensor归一化到相同的形状;
第八个参数allow_smaller_final_batch: 设置为True,表示在tensor队列中剩下的tensor数量不够一个batch_size的情况下,允许最后一个batch的数量少于batch_size, 设置为False,则不管什么情况下,生成的batch都拥有batch_size个样本;
第九个参数shared_name: 可选参数,设置生成的tensor序列在不同的Session中的共享名称;
第十个参数name: 操作的名称;  

读取1000*16 张图片结果,可以看到4或8个线程效果最好

由于tfrecord文件应该是一次性读入内存,所以相比起文件名方式读取快很多,但是如果图片数目太多无法一次读取的话

可以使用这种方式

1 197.51526355743408

2 98.29292130470276

4 67.14434576034546

8 64.94005250930786

16 66.47089147567749

import tensorflow as tf
import os
import time

# 样本个数
sample_num = 5
# 设置迭代次数
epoch_num = 1000
# 设置一个批次中包含样本个数
batch_size = 16
# 图像目录
IMAGE_DIR = "D:/data/17flowers/jpg"


# 生成4个数据和标签
def generate_data(sample_num=sample_num):
    labels = [name for name in os.listdir(IMAGE_DIR)]
    images = [os.path.join(IMAGE_DIR, name) for name in os.listdir(IMAGE_DIR)]

    return images, labels


def get_batch_data(batch_size=32, num_threads=1):
    images, labels = generate_data()
    images = tf.cast(images, tf.string)
    labels = tf.cast(labels, tf.string)

    input_queue = tf.train.slice_input_producer([images, labels])

    label = input_queue[1]
    image_contents = tf.read_file(input_queue[0])
    image = tf.image.decode_jpeg(image_contents, channels=3)
    # image = tf.image.resize_image_with_crop_or_pad(image, 224, 224)
    image = tf.image.resize_images(image, (512, 512))

    image_batch, label_batch = tf.train.batch([image, label],
                                              batch_size=batch_size,
                                              num_threads=num_threads,
                                              capacity=128)

    return image_batch, label_batch


def start(num_threads=1):
    image_batch, label_batch = get_batch_data(batch_size=batch_size, num_threads=num_threads)

    with tf.Session() as sess:
        coord = tf.train.Coordinator()
        threads = tf.train.start_queue_runners(sess, coord)
        try:
            for i in range(epoch_num):  # 每一轮迭代
                image_batch_v, label_batch_v = sess.run([image_batch, label_batch])
                # print(image_batch_v.shape, label_batch_v)
        except tf.errors.OutOfRangeError:
            print("done")
        finally:
            coord.request_stop()
        coord.join(threads)


if __name__ == '__main__':
    print('st---')
    st = time.time()
    start(num_threads=1)
    print('ed---', time.time() - st)

    print('st---')
    st = time.time()
    start(num_threads=2)
    print('ed---', time.time() - st)

    print('st---')
    st = time.time()
    start(num_threads=4)
    print('ed---', time.time() - st)

    print('st---')
    st = time.time()
    start(num_threads=8)
    print('ed---', time.time() - st)

    print('st---')
    st = time.time()
    start(num_threads=16)
    print('ed---', time.time() - st)

免责申明:本站发布的内容(图片、视频和文字)以转载和分享为主,文章观点不代表本站立场,如涉及侵权请联系站长邮箱:xbc-online@qq.com进行反馈,一经查实,将立刻删除涉嫌侵权内容。