首先是生成tfrecords格式的数据,具体代码如下:

#coding:utf-8

import os
import tensorflow as tf
from PIL import Image cwd = os.getcwd() '''
此处我加载的数据目录如下:
bt -- 14018.jpg
14019.jpg
14020.jpg nbt -- 1_ddd.jpg
1_dsdfs.jpg
1_dfd.jpg 这里的bt nbt 就是类别,也就是代码中的classes
''' writer = tf.python_io.TFRecordWriter("train.tfrecords")
classes = ['bt','nbt']
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() #将图片转化为原生bytes
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]))
}))
print "write" + ' ' + str(img_path) + "to train.tfrecords."
writer.write(example.SerializeToString()) #序列化为字符串
writer.close()

然后读取生成的tfrecords数据,并且将tfrecords里面的数据保存成jpg格式的图片。具体代码如下:

#coding:utf-8
import os
import tensorflow as tf
from PIL import Image
cwd = '/media/project/tfLearnning/dataread/pic/'
def read_and_decode(filename):
#根据文件名生成一个队列
filename_queue = tf.train.string_input_producer([filename]) 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),
})
img = tf.decode_raw(features['img_raw'],tf.uint8)
img = tf.reshape(img,[224,224,3])
#img = tf.cast(img,tf.float32) * (1./255) - 0.5 # 将图片变成tensor
#对图片进行归一化操作将【0,255】之间的像素归一化到【-0.5,0.5】,标准化处理可以使得不同的特征具有相同的尺度(Scale)。
#这样,在使用梯度下降法学习参数的时候,不同特征对参数的影响程度就一样了
label = tf.cast(features['label'], tf.int32) #将标签转化tensor
print img
print label
return img, label #read_and_decode('train.tfrecords')
img, label = read_and_decode('train.tfrecords')
#print img.shape, label
img_batch, label_batch = tf.train.shuffle_batch([img,label],batch_size=10,capacity=2000,min_after_dequeue=1000) #形成一个batch的数据,由于使用shuffle,因此每次取batch的时候
#都是随机取的,可以使样本尽可能被充分地训练,保证min_after值小于capacit值 init = tf.global_variables_initializer() with tf.Session() as sess:
sess.run(init)
# 创建一个协调器,管理线程
coord = tf.train.Coordinator()
# 启动QueueRunner, 此时文件名队列已经进队
threads = tf.train.start_queue_runners(sess=sess, coord=coord)
for i in range(10):
example, l = sess.run([img, label]) #从对列中一张一张读取图片和标签
#example, l = sess.run([img_batch,label_batch])
print(example.shape,l) img1=Image.fromarray(example, 'RGB') #将tensor转化成图片格式
img1.save(cwd+str(i)+'_'+'Label_'+str(l)+'.jpg')#save image
# 通知其他线程关闭
coord.request_stop()
# 其他所有线程关闭之后,这一函数才能返回
coord.join(threads)

Tensorflow学习教程------tfrecords数据格式生成与读取的更多相关文章

  1. Tensorflow学习教程------读取数据、建立网络、训练模型,小巧而完整的代码示例

    紧接上篇Tensorflow学习教程------tfrecords数据格式生成与读取,本篇将数据读取.建立网络以及模型训练整理成一个小样例,完整代码如下. #coding:utf-8 import t ...

  2. Tensorflow学习教程------过拟合

    Tensorflow学习教程------过拟合   回归:过拟合情况 / 分类过拟合 防止过拟合的方法有三种: 1 增加数据集 2 添加正则项 3 Dropout,意思就是训练的时候隐层神经元每次随机 ...

  3. Tensorflow学习教程------代价函数

    Tensorflow学习教程------代价函数   二次代价函数(quadratic cost): 其中,C表示代价函数,x表示样本,y表示实际值,a表示输出值,n表示样本的总数.为简单起见,使用一 ...

  4. tensorflow 学习教程

    tensorflow 学习手册 tensorflow 学习手册1:https://cloud.tencent.com/developer/section/1475687 tensorflow 学习手册 ...

  5. Tensorflow学习笔记----模型的保存和读取(4)

    一.模型的保存:tf.train.Saver类中的save TensorFlow提供了一个一个API来保存和还原一个模型,即tf.train.Saver类.以下代码为保存TensorFlow计算图的方 ...

  6. Tensorflow学习教程------lenet多标签分类

    本文在上篇的基础上利用lenet进行多标签分类.五个分类标准,每个标准分两类.实际来说,本文所介绍的多标签分类属于多任务学习中的联合训练,具体代码如下. #coding:utf-8 import te ...

  7. Tensorflow学习教程------创建图启动图

    Tensorflow作为目前最热门的机器学习框架之一,受到了工业界和学界的热门追捧.以下几章教程将记录本人学习tensorflow的一些过程. 在tensorflow这个框架里,可以讲是若数据类型,也 ...

  8. Tensorflow学习教程------非线性回归

    自己搭建神经网络求解非线性回归系数 代码 #coding:utf-8 import tensorflow as tf import numpy as np import matplotlib.pypl ...

  9. Tensorflow学习教程------利用卷积神经网络对mnist数据集进行分类_利用训练好的模型进行分类

    #coding:utf-8 import tensorflow as tf from PIL import Image,ImageFilter from tensorflow.examples.tut ...

随机推荐

  1. composer install、require、update的区别

  2. springmvc(@ResponseBody)无法跳转到对应的jsp页面

    项目框架:spring+springmvc+mybatis 问题描述:Controller返回jsp页面名称后,前端无法跳转到该页面,而是将该jsp名称打印到前端页面 前端异常信息:无 后端异常信息: ...

  3. opencv3.0机器学习算法使用

    //随机树分类Ptr<StatModel> lpmlBtnClassify::buildRtreesClassifier(Mat data, Mat responses, int ntra ...

  4. 通过Request获取客户端的真实IP

    我们在做项目的时候经常需要获取客户端的真实ip去进行判断,为此搜索了相关文章,以下这个讲解的比较明白,直接拿来 https://blog.csdn.net/yin_jw/article/details ...

  5. spark on yarn 安装笔记

    yarn版本:hadoop2.7.0 spark版本:spark1.4.0 0.前期环境准备: jdk 1.8.0_45 hadoop2.7.0 Apache Maven 3.3.3 1.编译spar ...

  6. tensorflow应用于手写数字识别(第二版)

    import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data#载入数据集 mnist = inp ...

  7. python函数-函数进阶

    python函数-函数进阶 一.命名空间和作用域 1.命名空间 内置命名空间 —— python解释器 就是python解释器一启动就可以使用的名字存储在内置命名空间中 内置的名字在启动解释器的时候被 ...

  8. PAT A1018

    A 1018 Public Bike Management 这个题目算是比较典型的一个.我分别用dfs,及dijkstra+dfs实现了一下. dfs实现代码: #include <cstdio ...

  9. hook鼠标键盘记录和回放

    unit Unit1; // download by http://www.codefans.net interface uses Windows, Messages, SysUtils, Class ...

  10. HTML5 可缩放矢量图形(1)—SVG基础

    参考文档1 SVG基础 SVG介绍 概念:SVG 是使用 XML 来描述二维图形和绘图程序的语言.(理解就是一个在网页上使用笔画图的过程) 什么是SVG SVG 指可伸缩矢量图形 (Scalable ...