经过上一节数据增强,我们来说说数据预处理吧。首先我们要知道图片进入网络训练都是要统一大小格式的,所以我们需要对训练集和验证集的图片进行裁剪,让他们大小统一,注意测试集不用裁剪!!!我选择裁剪成了64*
64的,没改源码的裁剪大小,其实图片大些识别率听说会高些,因为裁剪中会丢失一些信息。但是我没有试过,大家可以试试128*128的看看。下面是统一大小的代码:
记得修改成你自己的路径
# 将原始图片转换成需要的大小,并将其保存
# ========================================================================================
import os
import tensorflow as tf
from PIL import Image
import warnings
warnings.filterwarnings('ignore')
# 原始图片的存储位置
orig_picture = 'D:/flower_photos/train'
# 生成图片的存储位置
gen_picture = 'D:/flower_photos/input_data/train'
# 需要的识别类型
classes = { 'roses','tulips','dandelion','sunflowers','daisy'}
# 生成图片数目(训练集7000)验证集是500
num_samples = 7000
# 制作TFRecords数据
def create_record():
writer = tf.python_io.TFRecordWriter("flower_train.tfrecords")
for index, name in enumerate(classes):
class_path = orig_picture + "/" + name + "/"
for img_name in os.listdir(class_path):
img_path = class_path + img_name
img = Image.open(img_path)
img = img.resize((64, 64)) # 设置需要转换的图片大小
img_raw = img.tobytes() # 将图片转化为原生bytes
print(index, img_raw)
example = tf.train.Example(
features=tf.train.Features(feature={
"label": tf.train.Feature(int64_list=tf.train.Int64List(value=[index])),
'img_raw': tf.train.Feature(bytes_list=tf.train.BytesList(value=[img_raw]))
}))
writer.write(example.SerializeToString())
writer.close()
# =======================================================================================
def read_and_decode(filename):
# 创建文件队列,不限读取的数量
filename_queue = tf.train.string_input_producer([filename])
# create a reader from file queue
reader = tf.TFRecordReader()
# reader从文件队列中读入一个序列化的样本
_, serialized_example = reader.read(filename_queue)
# get feature from serialized example
# 解析符号化的样本
features = tf.parse_single_example(
serialized_example,
features={
'label': tf.FixedLenFeature([], tf.int64),
'img_raw': tf.FixedLenFeature([], tf.string)
})
label = features['label']
img = features['img_raw']
img = tf.decode_raw(img, tf.uint8)
img = tf.reshape(img, [64, 64, 3])
# img = tf.cast(img, tf.float32) * (1. / 255) - 0.5
label = tf.cast(label, tf.int32)
return img, label
# =======================================================================================
if __name__ == '__main__':
create_record()
batch = read_and_decode('flower_train.tfrecords')
init_op = tf.group(tf.global_variables_initializer(), tf.local_variables_initializer())
with tf.Session() as sess: # 开始一个会话
sess.run(init_op)
coord = tf.train.Coordinator()
threads = tf.train.start_queue_runners(coord=coord)
for i in range(num_samples):
example, lab = sess.run(batch) # 在会话中取出image和label
img = Image.fromarray(example, 'RGB') # 这里Image是之前提到的
img.save(gen_picture + '/' + str(i) + 'samples' + str(lab) + '.jpg') # 存下图片;注意cwd后边加上‘/’
print(example, lab)
coord.request_stop()
coord.join(threads)
sess.close()
裁剪后的图像识放在同一个文件夹里的,所以需要自己手动分类,就把它们放到他们类别的文件夹就行,其实也很简单,因为我这里是每个类别500张,每个类别的图片都是在一起的,或者你看图片名samples后面的编号就能看出。这个代码要运行两次,一次裁剪训练集,一次裁剪验证集。裁剪完后,我们可以看到,大小都是一样的。