在使用tensorflow的时候有时候需要对自己的图片进行读取,并处理。
在此写一个脚本方便自己学习和巩固。(代码基于Python3)
图片文件的储存路径如下所示:
`` ROOT_FOLDER |-------- SUBFOLDER (CLASS 0) | | | | ----- image1.jpg | | ----- image2.jpg | | ----- etc... | |-------- SUBFOLDER (CLASS 1) | | | | ----- image1.jpg | | ----- image2.jpg | | ----- etc... ```
在根目录下,创建各个类别的文件夹,并把各自类别的图片放置到对应的文件夹下
import tensorflow as tf
import os
# 根目录
Root_path = './'
# 设置图像类别,高度,宽度和通道数等数值
NUM_CLASS = 2
IMAGE_HEIGHT = 28
IMAGE_WIDTH = 28
IMAGE_CHANNELS = 3 # 彩色=3,灰白=1
def read_iamge(Root_path, batch_size):
imagepaths = []
labels = []
label = 0
classes = sorted(os.walk(Root_path).__next__()[1])
for c in classes:
c_dir = os.path.join(Root_path, c)
walk = os.walk(c_dir).__next__()[2]
for sample in walk:
if sample.endswith('.jpg') and sample.endswith('.jpeg'):
imagepaths.append(os.path.join(c_dir, sample))
labels.append(label)
label += 1
# 将iamgepaths 和 labels 转换为tf可以处理的格式
imagepaths = tf.convert_to_tensor(imagepaths, tf.string)
labels = tf.convert_to_tensor(labels, tf.int32)
# 建立 Queue
imagepath, label = tf.train.slice_input_producer([imagepaths, labels], shuffle=True)
# 读取图片,并进行解码
image = tf.read_file(imagepath)
image = tf.image.decode_jpeg(image, channels=IMAGE_CHANNELS)
# 对图片进行裁剪和正则化(将数值[0,255]转化为[-1,1])
image = tf.image.resize_images(image, size=[IMAGE_HEIGHT, IMAGE_WIDTH])
image = image*1.0/127.5 - 1.0
# 创建 batch
X, Y = tf.train.batch([image, label], batch_size=batch_size, num_threads=4, capacity=batch_size*8)
return X, Y
其中 tf.train.slice_input_producer() 函数会从tensorlist中随机选取一个tensor
而 tf.train.batch() 函数会创建一个符合设计要求的batch
-----> 由于tf.train.batch() 是基于Queue实现的,所以在使用的时候必须执行启动Queue操作 tf.train.start_queue_runners()