基于Tensorflow批量数据的输入实现方式


Posted in Python onFebruary 05, 2020

基于Tensorflow下的批量数据的输入处理:

1.Tensor TFrecords格式

2.h5py的库的数组方法

在tensorflow的框架下写CNN代码,我在书写过程中,感觉不是框架内容难写, 更多的是我在对图像的预处理和输入这部分花了很多精神。

使用了两种方法:

方法一:

Tensor 以Tfrecords的格式存储数据,如果对数据进行标签,可以同时做到数据打标签。

①创建TFrecords文件

orig_image = '/home/images/train_image/'
gen_image = '/home/images/image_train.tfrecords'
def create_record():
  writer = tf.python_io.TFRecordWriter(gen_image)
  class_path = orig_image
  for img_name in os.listdir(class_path): #读取每一幅图像
    img_path = class_path + img_name 
    img = Image.open(img_path) #读取图像
    #img = img.resize((256, 256)) #设置图片大小, 在这里可以对图像进行处理
    img_raw = img.tobytes() #将图片转化为原声bytes 
    example = tf.train.Example(
         features=tf.train.Features(feature={
             'label': tf.train.Feature(int64_list=tf.train.Int64List(value=[0])), #打标签
             'img_raw': tf.train.Feature(bytes_list=tf.train.BytesList(value=[img_raw]))#存储数据
             }))
    writer.write(example.SerializeToString())
  writer.close()

②读取TFrecords文件

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)})
  label = features['label']
  img = features['img_raw']
  img = tf.decode_raw(img, tf.uint8) #tf.float32
  img = tf.image.convert_image_dtype(img, dtype=tf.float32)
  img = tf.reshape(img, [256, 256, 1])
  label = tf.cast(label, tf.int32)
  return img, label

③批量读取数据,使用tf.train.batch

min_after_dequeue = 10000
capacity = min_after_dequeue + 3 * batch_size
num_samples= len(os.listdir(orig_image))
create_record()
img, label = read_and_decode(gen_image)
total_batch = int(num_samples/batch_size)
image_batch, label_batch = tf.train.batch([img, label], batch_size=batch_size,
                      num_threads=32, capacity=capacity) 
init_op = tf.group(tf.global_variables_initializer(), tf.local_variables_initializer())
with tf.Session() as sess:
  sess.run(init_op)
  coord = tf.train.Coordinator()
  threads = tf.train.start_queue_runners(coord=coord)
  for i in range(total_batch):
     cur_image_batch, cur_label_batch = sess.run([image_batch, label_batch])
  coord.request_stop()
  coord.join(threads)

方法二:

使用h5py就是使用数组的格式来存储数据

这个方法比较好,在CNN的过程中,会使用到多个数据类存储,比较好用, 比如一个数据进行了两种以上的变化,并且分类存储,我认为这个方法会比较好用。

import os
import h5py
import matplotlib.pyplot as plt
import numpy as np
import random
from scipy.interpolate import griddata
from skimage import img_as_float
import matplotlib.pyplot as plt
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
class_path = '/home/awen/Juanjuan/Python Project/train_BSDS/test_gray_0_1/'
for img_name in os.listdir(class_path):
  img_path = class_path + img_name
  img = io.imread(img_path)
  m1 = img_as_float(img)
  m2, m3 = sample_inter1(m1) #一个数据处理的函数
  m1 = m1.reshape([256, 256, 1])
  m2 = m2.reshape([256, 256, 1])
  m3 = m3.reshape([256, 256, 1])
  orig_image.append(m1)
  sample_near.append(m2)
  sample_line.append(m3)

arrorig_image = np.asarray(orig_image) # [?, 256, 256, 1]
arrlsample_near = np.asarray(sample_near) # [?, 256, 256, 1] 
arrlsample_line = np.asarray(sample_line) # [?, 256, 256, 1] 

save_path = '/home/awen/Juanjuan/Python Project/train_BSDS/test_sample/train.h5'
def make_data(path):
  with h5py.File(save_path, 'w') as hf:
     hf.create_dataset('orig_image', data=arrorig_image)
     hf.create_dataset('sample_near', data=arrlsample_near)
     hf.create_dataset('sample_line', data=arrlsample_line)

def read_data(path):
  with h5py.File(path, 'r') as hf:
     orig_image = np.array(hf.get('orig_image')) #一定要对清楚上边的标签名orig_image;
     sample_near = np.array(hf.get('sample_near'))
     sample_line = np.array(hf.get('sample_line'))
  return orig_image, sample_near, sample_line
make_data(save_path)
orig_image1, sample_near1, sample_line1 = read_data(save_path)
total_number = len(orig_image1)
batch_size = 20
batch_index = total_number/batch_size
for i in range(batch_index):
  batch_orig = orig_image1[i*batch_size:(i+1)*batch_size]
  batch_sample_near = sample_near1[i*batch_size:(i+1)*batch_size]
  batch_sample_line = sample_line1[i*batch_size:(i+1)*batch_size]

在使用h5py的时候,生成的文件巨大的时候,读取数据显示错误:ioerror: unable to open file (bad object header version number)

基本就是这个生成的文件不能使用,适当的减少存储的数据,即可。

以上这篇基于Tensorflow批量数据的输入实现方式就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持三水点靠木。

Python 相关文章推荐
Python中的引用和拷贝浅析
Nov 22 Python
python和bash统计CPU利用率的方法
Jul 10 Python
python3 发送任意文件邮件的实例
Jan 23 Python
python 利用栈和队列模拟递归的过程
May 29 Python
Python操作json的方法实例分析
Dec 06 Python
使用Python 正则匹配两个特定字符之间的字符方法
Dec 24 Python
详解python爬虫系列之初识爬虫
Apr 06 Python
python 代码运行时间获取方式详解
Sep 18 Python
python对批量WAV音频进行等长分割的方法实现
Sep 25 Python
Python中用xlwt制作表格实例讲解
Nov 05 Python
Python3中的tuple函数知识点讲解
Jan 03 Python
python模板入门教程之flask Jinja
Apr 11 Python
Python操作注册表详细步骤介绍
Feb 05 #Python
Python类继承和多态原理解析
Feb 05 #Python
Python模块 _winreg操作注册表
Feb 05 #Python
python3操作注册表的方法(Url protocol)
Feb 05 #Python
Python tkinter模版代码实例
Feb 05 #Python
Python Scrapy框架第一个入门程序示例
Feb 05 #Python
python lambda函数及三个常用的高阶函数
Feb 05 #Python
You might like
PHP多线程抓取网页实现代码
2010/07/22 PHP
ThinkPHP中redirect用法分析
2014/12/05 PHP
php+mysql数据库查询实例
2015/01/21 PHP
php实现的单一入口应用程序实例分析
2015/09/23 PHP
php生成条形码的图片的实例详解
2017/09/13 PHP
JavaScript和ActionScript的交互实现代码
2010/08/01 Javascript
Jquery 的扩展方法总结
2011/10/01 Javascript
js中arguments,caller,callee,apply的用法小结
2014/01/28 Javascript
JavaScript插件化开发教程 (一)
2015/01/27 Javascript
jQuery实现复选框批量选择与反选的方法
2015/06/17 Javascript
Node.js的Koa框架上手及MySQL操作指南
2016/06/13 Javascript
基于JQuery实现分隔条的功能
2016/06/17 Javascript
vuex实现简易计数器
2016/10/27 Javascript
js实现弹窗暗层效果
2017/01/16 Javascript
bootstrap table之通用方法( 时间控件,导出,动态下拉框, 表单验证 ,选中与获取信息)代码分享
2017/01/24 Javascript
vue中SPA单页面应用程序详解
2017/11/07 Javascript
JavaScript中的一些隐式转换和总结(推荐)
2017/12/22 Javascript
Vue用v-for给循环标签自身属性添加属性值的方法
2018/10/18 Javascript
深入学习JavaScript 高阶函数
2019/06/11 Javascript
vue中在vuex的actions中请求数据实例
2019/11/08 Javascript
15分钟学会vue项目改造成SSR(小白教程)
2019/12/17 Javascript
python 判断参数为Nonetype类型或空的实例
2018/10/30 Python
Python 读取串口数据,动态绘图的示例
2019/07/02 Python
利用scikitlearn画ROC曲线实例
2020/07/02 Python
使用OpenCV去除面积较小的连通域
2020/07/05 Python
Matlab中plot基本用法的具体使用
2020/07/17 Python
德国运动营养和健身网上商店:Myprotein.de
2018/07/18 全球购物
美国最大最全的亚洲购物网站:美国亚米网(Yamibuy)
2020/05/05 全球购物
软件专业毕业生个人自我鉴定
2014/04/17 职场文书
社区爱国卫生月活动总结
2014/06/30 职场文书
入党积极分子学习优秀共产党员先进事迹思想汇报
2014/09/13 职场文书
医院护士工作检讨书
2014/10/26 职场文书
先进基层党组织材料
2014/12/25 职场文书
业务员年终工作总结2015
2015/05/28 职场文书
酒会开场白大全
2015/06/01 职场文书
个人工作决心书
2015/09/22 职场文书