侯体宗的博客
  • 首页
  • Hyperf版
  • beego仿版
  • 人生(杂谈)
  • 技术
  • 关于我
  • 更多分类
    • 文件下载
    • 文字修仙
    • 中国象棋ai
    • 群聊
    • 九宫格抽奖
    • 拼图
    • 消消乐
    • 相册

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

Python  /  管理员 发布于 7年前   186

一、数据集介绍

点击打开链接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文件。而且读取也很方便。

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

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,如下图所示:

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

完整代码如下:

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()  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制作自己的数据集实例讲解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。


  • 上一条:
    Python3爬虫学习之将爬取的信息保存到本地的方法详解
    下一条:
    Python3爬虫学习之爬虫利器Beautiful Soup用法分析
  • 昵称:

    邮箱:

    0条评论 (评论内容有缓存机制,请悉知!)
    最新最热
    • 分类目录
    • 人生(杂谈)
    • 技术
    • linux
    • Java
    • php
    • 框架(架构)
    • 前端
    • ThinkPHP
    • 数据库
    • 微信(小程序)
    • Laravel
    • Redis
    • Docker
    • Go
    • swoole
    • Windows
    • Python
    • 苹果(mac/ios)
    • 相关文章
    • 在python语言中Flask框架的学习及简单功能示例(0个评论)
    • 在Python语言中实现GUI全屏倒计时代码示例(0个评论)
    • Python + zipfile库实现zip文件解压自动化脚本示例(0个评论)
    • python爬虫BeautifulSoup快速抓取网站图片(1个评论)
    • vscode 配置 python3开发环境的方法(0个评论)
    • 近期文章
    • 智能合约Solidity学习CryptoZombie第三课:组建僵尸军队(高级Solidity理论)(0个评论)
    • 智能合约Solidity学习CryptoZombie第二课:让你的僵尸猎食(0个评论)
    • 智能合约Solidity学习CryptoZombie第一课:生成一只你的僵尸(0个评论)
    • 在go中实现一个常用的先进先出的缓存淘汰算法示例代码(0个评论)
    • 在go+gin中使用"github.com/skip2/go-qrcode"实现url转二维码功能(0个评论)
    • 在go语言中使用api.geonames.org接口实现根据国际邮政编码获取地址信息功能(1个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf分页文件功能(0个评论)
    • gmail发邮件报错:534 5.7.9 Application-specific password required...解决方案(0个评论)
    • 欧盟关于强迫劳动的规定的官方举报渠道及官方举报网站(0个评论)
    • 在go语言中使用github.com/signintech/gopdf实现生成pdf文件功能(0个评论)
    • 近期评论
    • 122 在

      学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..
    • 123 在

      Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..
    • 原梓番博客 在

      在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..
    • 博主 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..
    • 1111 在

      佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
    • 2016-10
    • 2016-11
    • 2018-04
    • 2020-03
    • 2020-04
    • 2020-05
    • 2020-06
    • 2022-01
    • 2023-07
    • 2023-10
    Top

    Copyright·© 2019 侯体宗版权所有· 粤ICP备20027696号 PHP交流群

    侯体宗的博客