基于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 相关文章推荐
Django中间件工作流程及写法实例代码
Feb 06 Python
python实现最长公共子序列
May 22 Python
Python将文本去空格并保存到txt文件中的实例
Jul 24 Python
python3.6.3转化为win-exe文件发布的方法
Oct 31 Python
Python告诉你木马程序的键盘记录原理
Feb 02 Python
django之使用celery-把耗时程序放到celery里面执行的方法
Jul 12 Python
Python的几种主动结束程序方式
Nov 22 Python
Python实现i人事自动打卡的示例代码
Jan 09 Python
Python 2种方法求某个范围内的所有素数(质数)
Jan 31 Python
TensorFlow实现自定义Op方式
Feb 04 Python
Python中的None与 NULL(即空字符)的区别详解
Sep 24 Python
python接口测试返回数据为字典取值方式
Feb 12 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
mayfish 数据入库验证代码
2010/04/30 PHP
php函数指定默认值方法的小例子
2013/12/04 PHP
IIS下PHP的三种配置方式对比
2014/11/20 PHP
js库Modernizr的介绍和使用
2015/05/07 Javascript
JavaScript图片轮播代码分享
2015/07/31 Javascript
JavaScript数组各种常见用法实例分析
2015/08/04 Javascript
基于jQuery实现的双11天猫拆红包抽奖效果
2015/12/01 Javascript
探析浏览器执行JavaScript脚本加载与代码执行顺序
2016/01/12 Javascript
创建一个类Person的简单实例
2016/05/17 Javascript
BootStrap中Datetimepicker和uploadify插件应用实例小结
2016/05/26 Javascript
JavaScript对象创建模式实例汇总
2016/10/03 Javascript
基于JavaScript实现无缝滚动效果
2017/07/21 Javascript
微信小程序实现多宫格抽奖活动
2020/04/15 Javascript
详解npm 配置项registry修改为淘宝镜像
2018/09/07 Javascript
小程序绑定用户方案优化小结
2019/05/15 Javascript
vue elementUI table 自定义表头和行合并的实例代码
2019/05/22 Javascript
JavaScript原型继承和原型链原理详解
2020/02/04 Javascript
浅谈vue中$event理解和框架中在包含默认值外传参
2020/08/07 Javascript
[02:31]2014DOTA2国际邀请赛2009专访:干爹表现出乎意料 看好DK杀回决赛
2014/07/20 DOTA
Python实现爬取知乎神回复简单爬虫代码分享
2015/01/04 Python
Python2中的raw_input() 与 input()
2015/06/12 Python
python实现简单购物商城
2016/05/21 Python
Python虚拟环境项目实例
2017/11/20 Python
Python读取txt内容写入xls格式excel中的方法
2018/10/11 Python
redis数据库及与python交互用法简单示例
2019/11/01 Python
Python中的四种交换数值的方法解析
2019/11/18 Python
python基于celery实现异步任务周期任务定时任务
2019/12/30 Python
Pytorch通过保存为ONNX模型转TensorRT5的实现
2020/05/25 Python
css 如何让背景图片拉伸填充避免重复显示
2013/07/11 HTML / CSS
HTML5表单验证特性(知识点小结)
2020/03/10 HTML / CSS
利物浦足球俱乐部官方网上商店:Liverpool FC Official Store
2018/01/13 全球购物
团组织关系介绍信
2014/01/12 职场文书
上班玩手机检讨书
2014/02/17 职场文书
一年级学生评语
2014/04/23 职场文书
个人政治思想总结
2015/03/05 职场文书
MySQL约束超详解
2021/09/04 MySQL