TensorFlow 制作自己的TFRecord数据集

准备图片数据

网上下载了2类吉他和房子的图片, 全部 resize成64*64大小
如下图, 保存项目下:

现在利用这2 类 共108张图片制作TFRecord文件

制作TFRECORD文件

1 先聊一下tfrecord, 这是一种将图像数据和标签放在一起的二进制文件,能更好的利用内存,在tensorflow中快速的复制,移动,读取,存储 等等…
这里注意,tfrecord会根据你选择输入文件的类,自动给每一类打上同样的标签
如在本例中,只有0,1 两类

import os
import tensorflow as tf
from PIL import Image  #注意Image,后面会用到
import matplotlib.pyplot as plt
import numpy as np
# 制作TFRECORD文件===============================================
cwd='photo'
classes={'guitar','house'} #人为 设定 2 类
writer= tf.python_io.TFRecordWriter("train.tfrecords") #要生成的文件
for index,name in enumerate(classes):print('index:',index)# print('name:',name)# photo的子文件夹class_path=cwd+'/'+name+'/'# print('class_path:',class_path)for img_name in os.listdir(class_path):# print('img_name:',img_name)img_path=class_path+img_name #每一个图片的地址print('img_path:',img_path)img=Image.open(img_path)# print('img:',img)# 调整图片大小img= img.resize((64,64))img_raw=img.tobytes()#将图片转化为二进制字符格式# print('img_raw:',img_raw)# tf.train.Features:#           输入:键,值#                 int64_list:输入:整数#                 bytes_list:输入:字节(二进制数)#           输出:特征# tf.train.Example 协议内存块包含了Features字段# 通过feature将图片的二进制数据和label进行统一封装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()

tf.train.Example 协议内存块包含了Features字段,通过feature将图片的二进制数据和label进行统一封装, 然后将example协议内存块转化为字符串, tf.python_io.TFRecordWriter 写入到TFRecords文件中。

读取TFRECORD文件

在制作完tfrecord文件后, 将该文件读入到数据流中。
代码如下

# 读取TFRECORD文件=======================================================
def read_and_decode(filename): # 读入train.tfrecordsfilename_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取出来
# 注意,feature的属性“label”和“img_raw”名称要和制作时统一 ,返回的img数据和label数据一一对应。img = tf.decode_raw(features['img_raw'], tf.uint8)img = tf.reshape(img, [128, 128, 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数据一一对应。返回的img和label是2个 tf 张量

显示tfrecord格式的图片

有些时候我们希望检查分类是否有误,或者在之后的网络训练过程中可以监视,输出图片,来观察分类等操作的结果,那么我们就可以session回话中,将tfrecord的图片从流中读取出来,再保存。 紧跟着一开始的代码写:

# 显示tfrecord格式的图片=========================================================
# 读入流中
filename_queue = tf.train.string_input_producer(["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, [64, 64, 3])
label = tf.cast(features['label'], tf.int32)
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)# 54副图片for i in range(108):example, l = sess.run([image,label])#在会话中取出image和labelimg=Image.fromarray(example, 'RGB')#这里Image是之前提到的# print('path:',cwd+str(i)+'_''Label_'+str(l)+'.jpg')img.save(cwd+str(i)+'_''Label_'+str(l)+'.jpg')#存下图片# print(example, l)coord.request_stop()coord.join(threads)

代码运行完后, 从tfrecord中取出的文件被保存在photo文件夹了。

总代码如下:

import os
import tensorflow as tf
from PIL import Image  #注意Image,后面会用到
import matplotlib.pyplot as plt
import numpy as np
# 制作TFRECORD文件===============================================
cwd='photo'
classes={'guitar','house'} #人为 设定 2 类
writer= tf.python_io.TFRecordWriter("train.tfrecords") #要生成的文件
for index,name in enumerate(classes):print('index:',index)# print('name:',name)# photo的子文件夹class_path=cwd+'/'+name+'/'# print('class_path:',class_path)for img_name in os.listdir(class_path):# print('img_name:',img_name)img_path=class_path+img_name #每一个图片的地址print('img_path:',img_path)img=Image.open(img_path)# print('img:',img)# 调整图片大小img= img.resize((64,64))img_raw=img.tobytes()#将图片转化为二进制字符格式# print('img_raw:',img_raw)# tf.train.Features:#           输入:键,值#                 int64_list:输入:整数#                 bytes_list:输入:字节(二进制数)#           输出:特征# tf.train.Example 协议内存块包含了Features字段# 通过feature将图片的二进制数据和label进行统一封装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()
# 读取TFRECORD文件=======================================================
def read_and_decode(filename): # 读入train.tfrecordsfilename_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, [128, 128, 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
# 显示tfrecord格式的图片=========================================================
# 读入流中
filename_queue = tf.train.string_input_producer(["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, [64, 64, 3])
label = tf.cast(features['label'], tf.int32)
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)# 54副图片for i in range(108):example, l = sess.run([image,label])#在会话中取出image和labelimg=Image.fromarray(example, 'RGB')#这里Image是之前提到的# print('path:',cwd+str(i)+'_''Label_'+str(l)+'.jpg')img.save(cwd+str(i)+'_''Label_'+str(l)+'.jpg')#存下图片# print(example, l)coord.request_stop()coord.join(threads)

TensorFlow 制作自己的TFRecord数据集相关推荐

  1. TensorFlow 制作自己的TFRecord数据集

    官网的mnist和cifar10数据之后,笔者尝试着制作自己的数据集,并保存,读入,显示. TensorFlow可以支持cifar10的数据格式, 也提供了标准的TFRecord 格式,而关于 ten ...

  2. Tensorflow—tfrecord数据集生成与使用

    参考内容: 数据读取的官方教程:Tensorflow导入数据以及使用数据 tfrecord数据集生成: 数据准备:图片数据+图片目录与label一一对应的的txt 先读取图片信息的txt文件,得到每个 ...

  3. 用Tensorflow处理自己的数据:制作自己的TFRecords数据集

    转载请注明作者和出处: http://blog.csdn.net/wiinter_fdd/article/details/72835939 运行平台: Windows Python版本: Python ...

  4. Tensorflow-制作与使用tfrecord数据集

    引言   本次博文目的是记录下tfrecord数据集的制作与使用方式.(踩了无数坑OTZ)   这里贴上一个数据读取的官方教程:Tensorflow导入数据以及使用数据   接下来举个例子说明怎么用t ...

  5. Tensorflow生成自己的图片数据集TFrecords(支持多标签label)

    Tensorflow生成自己的图片数据集TFrecords 尊重原创,转载请注明出处:https://blog.csdn.net/guyuealian/article/details/80857228 ...

  6. tensorflow yolov3训练自己的数据集,详细教程

    这个教程是我在自己学习的过程中写的,当作一个笔记,写的比较详细 在github上下载yolov3的tensorflow1.0版本: https://github.com/YunYang1994/ten ...

  7. 利用tensorflow训练自己的图片数据集——数据准备

    昨天实现了一个简单的CNN网络.用了MNIST数据集,虽然看来对这个数据集用的很多,但是真正这个数据集是怎么在训练的时候被调用的,以及怎么把它换成自己的数据集都是一脸懵. 直接附上链接:MNIST数据 ...

  8. Tensorflow下用自己的数据集对Faster RCNN进行训练和测试(二)1

    原 Tensorflow下用自己的数据集对Faster RCNN进行训练和测试(二) 2018年08月21日 22:20:38 子季鹰才 阅读数:1811 对于Tensorflow版本的Faster ...

  9. 从零开始制作人脸表情的数据集

    一.背景 人脸表情识别网上已有很多教程,大多基于fer2013数据集展开的.现在的问题就在于fer2013数据集的数量太少,表情的区分度不够明显,大部分基于此数据集的模型,其识别精度仅有70%左右. ...

最新文章

  1. springmvc进阶(5):mvc:default-servlet-handler详解
  2. mac设置计算机用户名,如何更改macbook用户名_高手教你更改macbook用户名的方法-系统城...
  3. 【mysql】mysql优化
  4. J-Rooms及时会议室 v4.5.5333.1104
  5. python是动态语言_Python是动态语言:动态添加或删除属性、方法
  6. RMAN duplicate恢复数据库报错RMAN-06054问题处理
  7. C#重写WebBrowser组件,禁止跳转到IE新窗口、脚本错误
  8. python-判断一个字符串是目录还是文件及批处理方法
  9. delphi cxgrid读取本地image_读取多个(海康\大华)网络摄像头的视频流 (使用opencv-python),解决实时读取延迟问题...
  10. codeblock输出中文乱码问题
  11. 欧拉公式求四面体体积
  12. 从jupyter转换为exe格式
  13. suger BI 创建任务
  14. php 漏洞 怎么解决,php安全漏洞怎么修复?
  15. 如何多人共同编辑_微信编辑器可以多人协作排版吗?
  16. python3+selenium4自动化测试操作启动不同的浏览器-基础篇2
  17. veu中时间转换----element-UI上Date-Picker时间控件
  18. Beyond Compare 相同文件对比结果仍显示红色 解决方案【转存】
  19. 电竞达人最爱五款真无线蓝牙耳机,听声辨位低延迟TWS蓝牙耳机助你《夺冠》
  20. maya导入abc动画_(送给纠结自学3d建模的同学)自学maya,zbrush,substance一个月的感想...

热门文章

  1. python批量jpg转png(顺序排列1.2.3……)、修改文件夹尺寸
  2. mongodb中简单的根据时间过滤进行查询
  3. RDKit | RDKit(2019.09)新增相似性图函数
  4. Machine Learning | (5) Scikit-learn的分类器算法-朴素贝叶斯
  5. python-字符串和文本
  6. Linux绝对权限和相对权限法,Linux基础学习笔记
  7. 新风向标:学术界开始从 Python 转向 Rust
  8. Nature子刊:涵盖20多万个基因组的人体肠道微生物参考基因组集
  9. 一作解读:Microbiome马铃薯疮痂病与土壤微生物组关系新进展
  10. R语言基于自定义函数构建xgboost模型并使用LIME解释器进行模型预测结果解释:基于训练数据以及模型构建LIME解释器解释一个iris数据样本的预测结果、LIME解释器进行模型预测结果解释并可视化