官网的mnist和cifar10数据之后,笔者尝试着制作自己的数据集,并保存,读入,显示。 TensorFlow可以支持cifar10的数据格式, 也提供了标准的TFRecord 格式,而关于 tensorflow 读取数据, 官网提供了3中方法 
1 Feeding: 在tensorflow程序运行的每一步, 用Python代码在线提供数据 
2 Reader : 在一个计算图(tf.graph)的开始前,将文件读入到流(queue)中 
3 在声明tf.variable变量或numpy数组时保存数据。受限于内存大小,适用于数据较小的情况

在本文,主要介绍第二种方法,利用tf.record标准接口来读入文件

准备图片数据

笔者找了2类狗的图片, 哈士奇和吉娃娃, 全部 resize成128 * 128大小 
如下图, 保存地址为/home/molys/Python/data/dog 
 
每类中有10张图片 
 

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

制作TFRECORD文件

1 先聊一下tfrecord, 这是一种将图像数据和标签放在一起的二进制文件,能更好的利用内存,在tensorflow中快速的复制,移动,读取,存储 等等..

这里注意,tfrecord会根据你选择输入文件的类,自动给每一类打上同样的标签 
如在本例中,只有0,1 两类

2 先上“制作TFRecord文件”的代码,注释附详解


import os
import tensorflow as tf
from PIL import Image #注意Image,后面会用到
import matplotlib.pyplot as plt
import numpy as np cwd='/home/molys/Python/data/'
classes={'husky','chihuahua'} #人为 设定 2 类
writer= tf.python_io.TFRecordWriter("dog_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((128,128))
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()

运行完这段代码后,会生成dog_train.tfrecords 文件,如下图 

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

读取TFRECORD文件

在制作完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, [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 张量,print出来 如下图 

显示tfrecord格式的图片

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


filename_queue = tf.train.string_input_producer(["dog_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, [128, 128, 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)
for i in range(20):
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)

代码运行完后, 从tfrecord中取出的文件被保存了。如下图: 

在这里我们可以看到,图片文件名的第一个数字表示在流中的顺序(笔者这里没有用shuffle), 第二个数字则是 每个图片的label,吉娃娃都为0,哈士奇都为1。 由此可见,我们一开始制作tfrecord文件时,图片分类正确。

TensorFlow 制作自己的TFRecord数据集的更多相关文章

  1. 深度学习原理与框架-Tfrecord数据集的制作 1.tf.train.Examples(数据转换为二进制) 3.tf.image.encode_jpeg(解码图片加码成jpeg) 4.tf.train.Coordinator(构建多线程通道) 5.threading.Thread(建立单线程) 6.tf.python_io.TFR(TFR读入器)

    1. 配套使用: tf.train.Examples将数据转换为二进制,提升IO效率和方便管理 对于int类型 : tf.train.Examples(features=tf.train.Featur ...

  2. 深度学习原理与框架-Tfrecord数据集的读取与训练(代码) 1.tf.train.batch(获取batch图片) 2.tf.image.resize_image_with_crop_or_pad(图片压缩) 3.tf.train.per_image_stand..(图片标准化) 4.tf.train.string_input_producer(字符串入队列) 5.tf.TFRecord(读

    1.tf.train.batch(image, batch_size=batch_size, num_threads=1) # 获取一个batch的数据 参数说明:image表示输入图片,batch_ ...

  3. Tensorflow创建和读取17flowers数据集

    http://blog.csdn.net/sinat_16823063/article/details/53946549 Tensorflow创建和读取17flowers数据集 标签: tensorf ...

  4. 在C#下使用TensorFlow.NET训练自己的数据集

    在C#下使用TensorFlow.NET训练自己的数据集 今天,我结合代码来详细介绍如何使用 SciSharp STACK 的 TensorFlow.NET 来训练CNN模型,该模型主要实现 图像的分 ...

  5. TensorFlow从0到1之TensorFlow逻辑回归处理MNIST数据集(17)

    本节基于回归学习对 MNIST 数据集进行处理,但将添加一些 TensorBoard 总结以便更好地理解 MNIST 数据集. MNIST由https://www.tensorflow.org/get ...

  6. 将本地图片数据制作成内存对象数据集|tensorflow|手写数字制作成内存对象数据集|tf队列|线程

      样本说明: tensorflow经典实例之手写数字识别.MNIST数据集. 数据集dir名称 每个文件夹代表一个标签label,每个label中有820个手写数字的图片 标签label为0的文件夹 ...

  7. tensorflow制作tfrecord格式数据

    tf.Example msg tensorflow提供了一种统一的格式.tfrecord来存储图像数据.用的是自家的google protobuf.就是把图像数据序列化成自定义格式的二进制数据. To ...

  8. tensorflow 使用tfrecords创建自己数据集

    直接采用矩阵方式建立数据集见:https://www.cnblogs.com/WSX1994/p/10128338.html 制作自己的数据集(使用tfrecords) 为什么采用这个格式? TFRe ...

  9. 制作voc2007数据格式的数据集

    最近按照博主分享的流程操作,将自己遇到的难题记录下来,附上原博文链接:https://blog.csdn.net/jx232515/article/details/78680724 使用SSD训练自己 ...

随机推荐

  1. [cocos2dx笔记012]一定简易的UI配置类

    使用cocostudio能够装载编辑好的UI,可是过于复杂.特别是在加截UI后,发现触屏事件有些问题. 假设直接使用程序写死载入UI又过于麻烦.花点时间,添加了一个基于ini的UI配置类,眼下仅仅实现 ...

  2. python使用pytest+pytest报告

    需要安装pytest和pytest-html pip3 install -U pytest pip3 install -U pytest-html

  3. Oracle 数据块损坏与恢复具体解释

    1.什么是块损坏: 所谓损坏的数据块,是指块没有採用可识别的 Oracle 格式,或者其内容在内部不一致. 通常情况下,损坏是由硬件故障或操作系统问题引起的.Oracle 数据库将损坏的块标识为&qu ...

  4. 查找python项目依赖并生成requirements.txt——pipreqs 真是很好用啊

    查找python项目依赖并生成requirements.txt 转自:http://blog.csdn.net/orangleliu/article/details/60958525 一起开发项目的时 ...

  5. iOS开发中UIDatePicker控件的使用方法简介

    iOS上的选择时间日期的控件是这样的,左边是时间和日期混合,右边是单纯的日期模式. 您可以选择自己需要的模式,Time, Date,Date and Time  , Count Down Timer四 ...

  6. C#操作Mysql类

    using System;using System.Collections.Generic;using System.Text;using System.Data;using System.Text. ...

  7. DataTable和List相互转换的类

    DataTable与List相互转换 .NET后台数据处理,从数据库中的捞出的数据格式一般是List和DataTable的格式.现在将两种格式相互转换的心得记录下来以便以后查找(直接上代码). pub ...

  8. Android Studio ( Linux) 创建模拟器报错

    Linux下Android studio创建模拟器最后一步报错 报错:An error occurred while creating the AVD. See idea.log for detail ...

  9. ES5:深入解析如何js定义类或对象。

    1.原始方式 var oCar = new  Object; oCar.color = "blue"; oCar.showColor = function(){alert(this ...

  10. (转)RabbitMQ学习之路由(java)

    http://blog.csdn.net/zhu_tianwei/article/details/40887755 参考:http://blog.csdn.NET/lmj623565791/artic ...