首先是生成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. Node.js NPM Package.json

    章节 Node.js NPM 介绍 Node.js NPM 作用 Node.js NPM 包(Package) Node.js NPM 管理包 Node.js NPM Package.json Nod ...

  2. spring源码 BeanFactory根接口

    /* * Copyright 2002-2016 the original author or authors. * * Licensed under the Apache License, Vers ...

  3. 【Vue中的坑】路由相同参数不同无法触发路由

    场景: vue实现导航栏,二级导航栏跳转到相同页面,通过参数来实现到该页面后,根据参数来滚动到对应到位置 网上的解决方法: 通常情况下我们喜欢设置keepAlive 包裹 router-view &l ...

  4. 13 —— node 获取文件属性 —— 加载第三方模块

    以加载第三方时间处理模块( moment )为例 : 一,加载 npm install moment 二,使用介绍 1,点击进入npm官网 https://www.npmjs.com/ 2,搜索 mo ...

  5. 大数据高可用集群环境安装与配置(06)——安装Hadoop高可用集群

    下载Hadoop安装包 登录 https://mirrors.tuna.tsinghua.edu.cn/apache/hadoop/common/ 镜像站,找到我们要安装的版本,点击进去复制下载链接 ...

  6. java集合对象区别二

    集合包是Java中最常用的包,它最常用的有Collection和Map两个接口的实现类,Collection用于存放多个单对象,Map用于存放Key-Value形式的键值对. Collection中常 ...

  7. hiho1482出勤记录II(string类字符串中查找字符串,库函数的应用)

    string类中有很多好用的函数,这里介绍在string类字符串中查找字符串的函数. string类字符串中查找字符串一般可以用: 1.s.find(s1)函数,从前往后查找与目标字符串匹配的第一个位 ...

  8. PAT Advanced 1143 Lowest Common Ancestor (30) [二叉查找树 LCA]

    题目 The lowest common ancestor (LCA) of two nodes U and V in a tree is the deepest node that has both ...

  9. 寒假day25

    今天解决了部分数据爬取不下来的问题,同时进行了面试的准备

  10. PAT 2019 秋

    考试的还行.不过略微有点遗憾,但是没想到第一题会直接上排序和dfs,感觉这次的题目难度好像是倒着的一样.哈哈哈哈. 第一题实在是搞崩心态,这道题给我的感觉是,可以做,但事实上总是差点啥. 第二题,第三 ...