python-tensorflow批量读取图像

其实最根本的就是

1、利用

filenames_queue=tf.train.string_input_producer(data_names,num_epochs=5,shuffle=False,capacity=512)

2、读取了文件名,放在了文件名队列中,filenames_queue就是一个FIFOQueue,

3、然后出队列利用reader=tf.WholeFileReader()去读取文件,转换等等

4、再获取batch

这些都在构建文件名队列,构建文件队列的时候讲过了,唯一多的就是多了从文件名队列中获取文件名,到放入文件队列过程多了读取图像

import os
import tensorflow as tf
import matplotlib.pylab as plt

data_file = '.\\testdata'
data_names=[os.path.join(data_file,k) for k in os.listdir(data_file)]

#这个num_epochs函数在整个Graph是local Variable,所以在sess.run全局变量的时候也要加上局部变量。  
filenames_queue=tf.train.string_input_producer(data_names,num_epochs=5,shuffle=False,capacity=512)

##文件读取与转换
reader=tf.WholeFileReader()
_,img_bytes=reader.read(filenames_queue)
image=tf.image.decode_png(img_bytes,channels=1)    #读取的是什么格式,就decode什么格式,此时还不知道图像大小
#解码成单通道的,并且获得的结果的shape是[?, ?,1],也就是Graph不知道图像的大小,需要set_shape
image.set_shape([800,800,1])   #set到原本已知图像的大小。或者直接通过tf.image.resize_images,tf.reshape()
image=tf.image.convert_image_dtype(image,tf.uint8)

##获取batch图像
image_batch = tf.train.batch([image],batch_size=4,num_threads=4,capacity=32)

with tf.Session() as sess:
    init=[tf.global_variables_initializer(),tf.local_variables_initializer()]
    sess.run(init)
    coord = tf.train.Coordinator()
    threads = tf.train.start_queue_runners(sess=sess,coord=coord)
    for _ in range(5):
        # while not coord.should_stop():
        img = sess.run(image_batch)
        plt.imshow(img[0,:,:,0],cmap='gray')
        plt.show()

    coord.request_stop()
    coord.join(threads)

输出了5张图像 

数据如下放在文件夹中

留一张图测试用

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值