一、数据集介绍
点击打开链接17_Category_Flower 是一个不同种类鲜花的图像数据,包含 17 不同种类的鲜花,每类 80 张该类鲜花的图片,鲜花种类是英国地区常见鲜花。下载数据后解压文件,然后将不同的花剪切到对应的文件夹,如下图所示:
每个文件夹下面有80个图片文件。
二、使用的工具
首先是在tensorflow框架下,然后介绍一下用到的两个库,一个是os,一个是PIL。PIL(Python Imaging Library)是 Python 中最常用的图像处理库,而Image类又是 PIL库中一个非常重要的类,通过这个类来创建实例可以有直接载入图像文件,读取处理过的图像和通过抓取的方法得到的图像这三种方法。
三、代码实现
我们是通过TFRecords来创建数据集的,TFRecords其实是一种二进制文件,虽然它不如其他格式好理解,但是它能更好的利用内存,更方便复制和移动,并且不需要单独的标签文件(label)。
1、制作TFRecords文件
import osimport tensorflow as tffrom PIL import Image # 注意Image,后面会用到import matplotlib.pyplot as pltimport numpy as np cwd = 'D:/PyCharm Community Edition 2017.2.3/Work/google_net/jpg//'classes = {'daffodil', 'snowdrop', 'lilyvalley', 'bluebell', 'crocus', 'iris', 'tigerlily', 'tulip', 'fritiuary', 'sunflower', 'daisy', 'coltsfoot', 'dandelion', 'cowslip', 'buttercup', 'windflower', 'pansy'} # 花为 设定 17 类writer = tf.python_io.TFRecordWriter("flower_train.tfrecords") # 要生成的文件 for index, name in enumerate(classes): class_path = cwd + name + '//' for img_name in os.listdir(class_path): img_path = class_path + img_name # 每一个图片的地址 img = Image.open(img_path) img = img.resize((224, 224)) img_raw = img.tobytes() # 将图片转化为二进制格式 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])) })) # example对象对label和image数据进行封装 writer.write(example.SerializeToString()) # 序列化为字符串writer.close()
首先将文件移动到对应的路径:
D:/PyCharm Community Edition 2017.2.3/Work/google_net/jpg
然后对每个文件下的图片进行读写和相应的大小惊醒改变,具体过程是使用tf.train.Example来定义我们要填入的数据格式,其中label即为标签,也就是最外层的文件夹名字,img_raw为易经理二进制化的图片。然后使用tf.python_io.TFRecordWriter来写入。基本的,一个Example中包含Features,Features里包含Feature(这里没s)的字典。最后,Feature里包含有一个 FloatList, 或者ByteList,或者Int64List。就这样,我们把相关的信息都存到了一个文件中,所以前面才说不用单独的label文件。而且读取也很方便。
新闻热点
疑难解答