对python制作自己的数据集实例讲解


Posted in Python onDecember 12, 2018

一、数据集介绍

点击打开链接17_Category_Flower 是一个不同种类鲜花的图像数据,包含 17 不同种类的鲜花,每类 80 张该类鲜花的图片,鲜花种类是英国地区常见鲜花。下载数据后解压文件,然后将不同的花剪切到对应的文件夹,如下图所示:

对python制作自己的数据集实例讲解

每个文件夹下面有80个图片文件。

二、使用的工具

首先是在tensorflow框架下,然后介绍一下用到的两个库,一个是os,一个是PIL。PIL(Python Imaging Library)是 Python 中最常用的图像处理库,而Image类又是 PIL库中一个非常重要的类,通过这个类来创建实例可以有直接载入图像文件,读取处理过的图像和通过抓取的方法得到的图像这三种方法。

三、代码实现

我们是通过TFRecords来创建数据集的,TFRecords其实是一种二进制文件,虽然它不如其他格式好理解,但是它能更好的利用内存,更方便复制和移动,并且不需要单独的标签文件(label)。

1、制作TFRecords文件

import os
import tensorflow as tf
from PIL import Image # 注意Image,后面会用到
import matplotlib.pyplot as plt
import 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()

对python制作自己的数据集实例讲解

首先将文件移动到对应的路径:

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文件。而且读取也很方便。

执行完以上代码就会出现如下图所示的TF文件

对python制作自己的数据集实例讲解

2、读取TFRECORD文件

制作完文件后,将该文件读入到数据流中,具体代码如下:

def read_and_decode(filename): # 读入dog_train.tfrecords
 filename_queue = tf.train.string_input_producer([filename]) # 生成一个queue队列
 reader = tf.TFRecordReader()
 _, serialized_example = reader.read(filename_queue) # 返回文件名和文件
 features = tf.parse_single_example(serialized_example,
     features={
      'label': tf.FixedLenFeature([], tf.int64),
      'img_raw': tf.FixedLenFeature([], tf.string),
     }) # 将image数据和label取出来
 
 img = tf.decode_raw(features['img_raw'], tf.uint8)
 img = tf.reshape(img, [224, 224, 3]) # reshape为128*128的3通道图片
 img = tf.cast(img, tf.float32) * (1. / 255) - 0.5 # 在流中抛出img张量
 label = tf.cast(features['label'], tf.int32) # 在流中抛出label张量
 return img, label

注意,feature的属性“label”和“img_raw”名称要和制作时统一 ,返回的img数据和label数据一一对应。

3、显示tfrecord格式的图片

为了知道TF 文件的具体内容,或者是怕图片对应的label出错,可以将数据流以图片的形式读出来并保存以便查看,具体的代码如下:

filename_queue = tf.train.string_input_producer(["flower_train.tfrecords"]) # 读入流中
reader = tf.TFRecordReader()
_, serialized_example = reader.read(filename_queue) # 返回文件名和文件
features = tf.parse_single_example(serialized_example,
     features={
     'label': tf.FixedLenFeature([], tf.int64),
     'img_raw': tf.FixedLenFeature([], tf.string),
     }) # 取出包含image和label的feature对象
image = tf.decode_raw(features['img_raw'], tf.uint8)
image = tf.reshape(image, [224, 224, 3])
label = tf.cast(features['label'], tf.int32)
label = tf.one_hot(label, 17, 1, 0)
with tf.Session() as sess: # 开始一个会话
 init_op = tf.initialize_all_variables()
 sess.run(init_op)
 coord = tf.train.Coordinator()
 threads = tf.train.start_queue_runners(coord=coord)
 for i in range(100):
 example, l = sess.run([image, label]) # 在会话中取出image和label
 img = Image.fromarray(example, 'RGB') # 这里Image是之前提到的
 img.save(cwd + str(i) + '_''Label_' + str(l) + '.jpg') # 存下图片
 print(example, l)
 coord.request_stop()
 coord.join(threads)

执行以上代码后,当前项目对应的文件夹下会生成100张图片,还有对应的label,如下图所示:

对python制作自己的数据集实例讲解

在这里我们可以看到,前80个图片文件的label是1,后20个图片的label是2。 由此可见,我们一开始制作tfrecord文件时,图片分类正确。

完整代码如下:

import os
import tensorflow as tf
from PIL import Image # 注意Image,后面会用到
import matplotlib.pyplot as plt
import 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()
 
 
def read_and_decode(filename): # 读入dog_train.tfrecords
 filename_queue = tf.train.string_input_producer([filename]) # 生成一个queue队列
 reader = tf.TFRecordReader()
 _, serialized_example = reader.read(filename_queue) # 返回文件名和文件
 features = tf.parse_single_example(serialized_example,
     features={
      'label': tf.FixedLenFeature([], tf.int64),
      'img_raw': tf.FixedLenFeature([], tf.string),
     }) # 将image数据和label取出来
 
 img = tf.decode_raw(features['img_raw'], tf.uint8)
 img = tf.reshape(img, [224, 224, 3]) # reshape为128*128的3通道图片
 img = tf.cast(img, tf.float32) * (1. / 255) - 0.5 # 在流中抛出img张量
 label = tf.cast(features['label'], tf.int32) # 在流中抛出label张量
 return img, label
 
 
filename_queue = tf.train.string_input_producer(["flower_train.tfrecords"]) # 读入流中
reader = tf.TFRecordReader()
_, serialized_example = reader.read(filename_queue) # 返回文件名和文件
features = tf.parse_single_example(serialized_example,
     features={
     'label': tf.FixedLenFeature([], tf.int64),
     'img_raw': tf.FixedLenFeature([], tf.string),
     }) # 取出包含image和label的feature对象
image = tf.decode_raw(features['img_raw'], tf.uint8)
image = tf.reshape(image, [224, 224, 3])
label = tf.cast(features['label'], tf.int32)
label = tf.one_hot(label, 17, 1, 0)
with tf.Session() as sess: # 开始一个会话
 init_op = tf.initialize_all_variables()
 sess.run(init_op)
 coord = tf.train.Coordinator()
 threads = tf.train.start_queue_runners(coord=coord)
 for i in range(100):
 example, l = sess.run([image, label]) # 在会话中取出image和label
 img = Image.fromarray(example, 'RGB') # 这里Image是之前提到的
 img.save(cwd + str(i) + '_''Label_' + str(l) + '.jpg') # 存下图片
 print(example, l)
 coord.request_stop()
 coord.join(threads)

本人也是刚刚学习深度学习,能力有限,不足之处请见谅,欢迎大牛一起讨论,共同进步!

以上这篇对python制作自己的数据集实例讲解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持三水点靠木。

Python 相关文章推荐
python获取外网ip地址的方法总结
Jul 02 Python
Python中文件I/O高效操作处理的技巧分享
Feb 04 Python
解决Python安装后pip不能用的问题
Jun 12 Python
python 修改本地网络配置的方法
Aug 14 Python
python 浅谈serial与stm32通信的编码问题
Dec 18 Python
python实现局域网内实时通信代码
Dec 22 Python
python对数组进行排序,并输出排序后对应的索引值方式
Feb 28 Python
Python如何省略括号方法详解
Mar 21 Python
全网首秀之Pycharm十大实用技巧(推荐)
Apr 27 Python
Python爬虫之Selenium中frame/iframe表单嵌套页面
Dec 04 Python
Python字符串的15个基本操作(小结)
Feb 03 Python
Python 数据可视化神器Pyecharts绘制图像练习
Feb 28 Python
Python3爬虫学习之爬虫利器Beautiful Soup用法分析
Dec 12 #Python
Python解决线性代数问题之矩阵的初等变换方法
Dec 12 #Python
对python数据切割归并算法的实例讲解
Dec 12 #Python
python实现文本界面网络聊天室
Dec 12 #Python
Python3爬虫学习之应对网站反爬虫机制的方法分析
Dec 12 #Python
python实现简单多人聊天室
Dec 11 #Python
在python中利用KNN实现对iris进行分类的方法
Dec 11 #Python
You might like
洪恩在线成语词典小偷程序php版
2012/04/20 PHP
php生成随机密码自定义函数代码(简单快速)
2014/05/10 PHP
php用户密码加密算法分析【Discuz加密算法】
2016/10/12 PHP
Yii框架实现记录日志到自定义文件的方法
2017/05/23 PHP
PHP的mysqli_sqlstate()函数讲解
2019/01/23 PHP
JS面向对象编程之对象使用分析
2010/08/19 Javascript
根据选择不同的下拉值出现相对应的文本输入框
2013/08/01 Javascript
js使浏览器窗口最大化实现代码(适用于IE)
2013/08/07 Javascript
详解JavaScript中的异常处理方法
2015/06/16 Javascript
基于jQuery的ajax方法封装
2016/07/14 Javascript
JavaScript利用正则表达式替换字符串中的内容
2016/12/12 Javascript
jquery表单验证实例仿Toast提示效果
2017/03/03 Javascript
如何使用angularJs
2017/05/08 Javascript
基于 Bootstrap Datetimepicker 联动
2017/08/03 Javascript
js实现canvas图片与img图片的相互转换的示例
2017/08/31 Javascript
引入JavaScript时alert弹出框显示中文乱码问题
2017/09/16 Javascript
Vue侧滑菜单组件——DrawerLayout
2017/12/18 Javascript
Node.js之删除文件夹(含递归删除)代码实例
2019/09/09 Javascript
Echarts实现多条折线可拖拽效果
2019/12/19 Javascript
VSCode 配置uni-app的方法
2020/07/11 Javascript
js实现头像上传并且可预览提交
2020/12/25 Javascript
pygame 精灵的行走及二段跳的实现方法(必看篇)
2017/07/10 Python
一道python走迷宫算法题
2018/01/22 Python
利用Python将每日一句定时推送至微信的实现方法
2018/08/13 Python
Python面向对象之反射/自省机制实例分析
2018/08/24 Python
python中append实例用法总结
2019/07/30 Python
Python检查 云备份进程是否正常运行代码实例
2019/08/22 Python
基于Django集成CAS实现流程详解
2020/11/28 Python
html5 div布局与table布局详解
2016/11/16 HTML / CSS
AT&T Wireless:手机、无限数据计划和配件
2018/06/03 全球购物
打架检讨书400字
2014/01/17 职场文书
高三学生评语大全
2014/04/25 职场文书
高考诚信考试承诺书
2015/04/29 职场文书
导游词范文之颐和园/重庆/云台山
2019/09/10 职场文书
gateway与spring-boot-starter-web冲突问题的解决
2021/07/16 Java/Android
Win11 25163.1010更新补丁KB5016904推送,测试服务验证管道(附更新修复汇总)
2022/07/23 数码科技