tensorflow分类任务——TFRecord制作自己的数据集
制作数据集的前菜——打乱数组
x, y = imageNumpyData()state = np.random.get_state()np.random.shuffle(x)np.random.set_state(state)np.random.shuffle(y)# 打乱之后的x,y作为训练数据x = np.array(x)y = np.array(y)
- 代码运行之前,x是一个list,y是一个array
- 使用随机数的方式打乱数据
- 如果x和y的数据样本数不一样,容易出现错误
- 打乱之后全部变成array
制作数据集的正餐
数据集的流程:
- 先读取输入,并把数据保存成固定通道,固定维数。
- 保存成numpy的形式,之后打乱数据集
- 数据集一张一张写入TFRecord中
注意事项:
- Data里面存放数据
- record里面存放制作成功的数据集
- 需要提前准备好了record这个文件夹,不然容易报错,如果要自动创建文件夹请看我另一篇博客,这个不做赘述
- 我的图片格式是JPEG,我在代码中写了判断,同时也可以制作BMP和PNG类型的图片
- 我的图片是灰度图,所以是单通道,读者若是彩色图片,相应更改代码,我在下面的解释中有说明
所有代码
import numpy as np
import tensorflow as tf
import os
from PIL import Image
import base64
import matplotlib.pyplot as pltdef imageNumpyData():# the classification file root pathrootFilePath = './Data/'rootAbsPath = os.path.abspath(rootFilePath)node1FloderPath = os.listdir(rootAbsPath)node1Path = [os.path.join(rootAbsPath, nodePath) for nodePath in node1FloderPath]label = 0imageLabel = []imageData = []for imagePath in node1Path:display = 0image = os.listdir(imagePath)image = [os.path.join(imagePath, file) for file in image]# 使用tensorflowwith tf.Session() as sess:for image_raw in image:try:img = Image.open(image_raw)if img.format == "BMP":image_raw_data = tf.gfile.FastGFile(image_raw, 'rb').read()image_data = tf.image.decode_bmp(image_raw_data)if img.format == "JPEG":image_raw_data = tf.gfile.FastGFile(image_raw, 'rb').read()image_data = tf.image.decode_jpeg(image_raw_data)if img.format == "PNG":image_raw_data = tf.gfile.FastGFile(image_raw, 'rb').read()image_data = tf.image.decode_png(image_raw_data)if image_data.dtype != tf.float32:image_data = tf.image.convert_image_dtype(image_data, dtype=tf.float32)image_data = tf.image.resize_images(image_data, [224, 224])image_temp = np.array(sess.run(image_data))if image_temp.shape[2] == 1:imageData.append(image_temp)imageLabel.append(label)display = display + 1print(str(label) + ':' + str(display))except:print(image_raw + '读取失败')# os.remove(image_raw)label = label + 1one_hot = tf.one_hot(imageLabel, label)with tf.Session() as sess:sess.run(tf.global_variables_initializer())imageLabel = sess.run(one_hot)return imageData, imageLabeldef tfRecordWrite(filename):# 生成整数的属性def _int64_feature(value):return tf.train.Feature(int64_list=tf.train.Int64List(value=[value]))# 生成字符串型的属性def _bytes_feature(value):return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))# filename = 'record/Imageoutput.tfrecords'writer = tf.python_io.TFRecordWriter(filename)x, y = imageNumpyData()state = np.random.get_state()np.random.shuffle(x)np.random.set_state(state)np.random.shuffle(y)# 打乱之后的x,y作为训练数据x = np.array(x)y = np.array(y)# 将每张图片都转为一个Exampleheight = x.shape[1]width = x.shape[2]channels = x.shape[3]n_class = y.shape[1]x = x.reshape([-1, height, width, channels])division = int(x.shape[0] * 0.9)x_train = x[:division]y_train = y[:division]x_test = x[division:]y_test = y[division:]np.savez('testData.npz', test_X=x_test, test_Y=y_test, height=height, width=width, channels=channels,n_class=n_class)del x_test, y_testfor i in range(x_train.shape[0]):image = x_train[i].tostring() # 将图像转为字符串example = tf.train.Example(features=tf.train.Features(feature={'image': _bytes_feature(image),'label': _int64_feature(np.argmax(y_train[i]))}))writer.write(example.SerializeToString()) # 将Example写入TFRecord文件writer.close()return height, width, channels, n_classfilename = r'./record\Imageoutput.tfrecords'
height, width, channels, n_class = tfRecordWrite(filename)
print(height, width, channels, n_class)
print('data processing success')
关键代码解释
try:img = Image.open(image_raw)if img.format == "BMP":image_raw_data = tf.gfile.FastGFile(image_raw, 'rb').read()image_data = tf.image.decode_bmp(image_raw_data)if img.format == "JPEG":image_raw_data = tf.gfile.FastGFile(image_raw, 'rb').read()image_data = tf.image.decode_jpeg(image_raw_data)if img.format == "PNG":image_raw_data = tf.gfile.FastGFile(image_raw, 'rb').read()image_data = tf.image.decode_png(image_raw_data)
解释:尝试打开图片,并且图片格式是JPEG,BMP或PNG, tf.gfile.FastGFile的这个地方必须要‘rb’,我看一些书上仅仅是写了一个‘r’,这样并不对。
if image_data.dtype != tf.float32:image_data = tf.image.convert_image_dtype(image_data, dtype=tf.float32)
解释:我做CNN的中,需要float32,这里必须转格式
image_data = tf.image.resize_images(image_data, [224, 224])
解释:把图片更改大小
if image_temp.shape[2] == 1:imageData.append(image_temp)imageLabel.append(label)
解释:我的是灰度图,所以这里**‘’==1‘’,若是三通道,则‘==3’**
one_hot = tf.one_hot(imageLabel, label)with tf.Session() as sess:sess.run(tf.global_variables_initializer())imageLabel = sess.run(one_hot)
解释:把得到的label,转换成one-hot形式
x = x.reshape([-1, height, width, channels])division = int(x.shape[0] * 0.9)x_train = x[:division]y_train = y[:division]x_test = x[division:]y_test = y[division:]np.savez('testData.npz', test_X=x_test, test_Y=y_test, height=height, width=width, channels=channels,n_class=n_class)del x_test, y_test
解释:这里是我拿出一部分数据保存成‘npz’的形式作为我的测试集,因为我用tfrecord格式的数据作为训练集
# 生成整数的属性def _int64_feature(value):return tf.train.Feature(int64_list=tf.train.Int64List(value=[value]))# 生成字符串型的属性def _bytes_feature(value):return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))
解释:这是我们必须遵从的规则,用整数属性写入label,用字符串形式写入图像数据
# filename = 'record/Imageoutput.tfrecords'writer = tf.python_io.TFRecordWriter(filename)
解释:开始写入,并生成文件
for i in range(x_train.shape[0]):image = x_train[i].tostring() # 将图像转为字符串example = tf.train.Example(features=tf.train.Features(feature={'image': _bytes_feature(image),'label': _int64_feature(np.argmax(y_train[i]))}))writer.write(example.SerializeToString()) # 将Example写入TFRecord文件writer.close()
解释:根据数据集大小,一个一个的写入
数据集地址:
链接:https://pan.baidu.com/s/1aIHzKsxUb67sJZAFrGH1ZQ
提取码:lvjp
工程地址:
链接:https://pan.baidu.com/s/1XGAA6UQ0JByhvDYQ__my4g
提取码:dxpn
结束语
希望大家积极学习,有不懂的地方可以加我的微信:ChaofeiLi
tensorflow分类任务——TFRecord制作自己的数据集相关推荐
- tensorflow分类任务——TFRecord读取自己制作的数据集
一.TensorFlow的数据读取机制 注意:这个地址是TensorFlow的数据读取机制,如果了解请跳过. 原博客地址:https://zhuanlan.zhihu.com/p/27238630 建 ...
- TF之GD:基于tensorflow框架搭建GD算法利用Fashion-MNIST数据集实现多分类预测(92%)
TF之GD:基于tensorflow框架搭建GD算法利用Fashion-MNIST数据集实现多分类预测(92%) 目录 输出结果 实现代码 输出结果 Successfully downloaded t ...
- TensorFlow 2.0 - TFRecord存储数据集、@tf.function图执行模式、tf.TensorArray、tf.config分配GPU
文章目录 1. TFRecord 格式存储 2. tf.function 高性能 3. tf.TensorArray 支持计算图特性 4. tf.config 分配GPU 学习于:简单粗暴 Tenso ...
- TensorFlow最出色的30个机器学习数据集
字幕组双语原文:TensorFlow最出色的30个机器学习数据集 英语原文:30 Largest TensorFlow Datasets for Machine Learning 翻译:雷锋字幕组(c ...
- yolo v3制作自己的数据_【手把手AI项目】五、自己制作图像VOC数据集--Objection Detection(目标检测)...
文章首发于我的个人博客 [手把手AI项目]五.自己制作图像VOC数据集--用于Objection Detection(目标检测)blog.csdn.net 喜欢手机观看的朋友也可以在我的个人公号: ...
- Tensorflow中的TFRecord、Queue和多线程
Queues, Threads, and Reading Data 输入管线 如果训练数据量较小,Tesnsorflow会把数据一次性加载到内存当中.如果数据过于庞大,Tesorflow需要把存储到硬 ...
- 巧用PPOCRLabel制作DOC-VQA格式数据集
1. 项目背景 最近涉及到多模态"OCR" + "DOC-VQA"相关内容,一直使用XFUND数据集,但实际项目中需要训练真实数据才能达到更好的效果,那么如何制 ...
- TensorFlow基础1(波士顿房价/鸢尾花数据集可视化)
记录TensorFlow听课笔记 文章目录 记录TensorFlow听课笔记 一,波士顿房价数据集可视化 1.1介绍波士顿房价数据集 1.2波士顿房价数据集加载 1.3将平均房间数与房价之间的关系可视 ...
- FCN制作自己的数据集、训练和测试 caffe
原文:http://blog.csdn.net/zoro_lov3/article/details/74550735 FCN制作自己的数据集.训练和测试全流程 花了两三周的时间,在导师的催促下,把FC ...
最新文章
- 【运筹学】线性规划数学模型 ( 单纯形法 | 最优解判定原则 | 单纯形表 | 系数计算方法 | 根据系数是否小于等于 0 判定最优解 )
- 码农口述:AI创业两年,积蓄花光,重回职场敲代码
- 记住,你现在的操作是什么
- 树莓派 rtl8188eu 芯片wifi驱动
- n分频器 verilog_基于Verilog的分频器实现
- Xampp里Mysql服务启动不起来,错误1067
- php email,两种PHP邮件发送的方式
- qemu-img创建qcow2虚拟磁盘的预分配策略
- python io多路复用框架_python之IO多路复用
- 美团试水机器人送外卖;苹果向第三方提供 iPhone 维修零件;GoLand 2019.2.1 发布 | 极客头条...
- c++写入二进制、TXT文件,读取二进制、TXT文件,切分字符串(入数组)
- Python打造一款属于自己的翻译词典
- pycharm 软件详细使用教程,新手必看篇
- TypeScript学习-类class
- DBA的工作职责是什么?
- python中成语接龙游戏_Python实现成语接龙
- 利用slf4j+log4j将日志写入指定的文件中
- h5 登录页面_鲁班H5作者:@小小鲁班
- 浅谈web前端常用的三大主流框架
- win7虚拟机上安装visual studio2017社区版的相关问题以及解决办法