基于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 相关文章推荐
精确查找PHP WEBSHELL木马的方法(1)
Apr 12 Python
python多线程threading.Lock锁用法实例
Nov 01 Python
基于数据归一化以及Python实现方式
Jul 11 Python
对python中dict和json的区别详解
Dec 18 Python
在python带权重的列表中随机取值的方法
Jan 23 Python
10款最好的Python开发编辑器
Jul 03 Python
Python Django模板之模板过滤器与自定义模板过滤器示例
Oct 18 Python
Centos7 下安装最新的python3.8
Oct 28 Python
Python Sympy计算梯度、散度和旋度的实例
Dec 06 Python
如何基于Python爬取隐秘的角落评论
Jul 02 Python
浅析Django接口版本控制
Jun 26 Python
python单向链表实例详解
May 25 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 flush类输出缓冲剖析
2008/10/19 PHP
PHP实现支持SSL连接的SMTP邮件发送类
2015/03/05 PHP
PHP页面间传递值和保持值的方法
2016/08/24 PHP
PHP7 mongoDB扩展使用的方法分享
2019/05/02 PHP
B/S开发中常用javaScript技术与代码
2007/03/09 Javascript
ie下jquery.getJSON的缓存问题的处理方法
2013/03/29 Javascript
Json和Jsonp理论实例代码详解
2013/11/15 Javascript
js简单实现竖向tab选项卡的方法
2015/05/04 Javascript
jQuery表格行上移下移和置顶的实现方法
2015/10/08 Javascript
AngularJS中实现用户访问的身份认证和表单验证功能
2016/04/21 Javascript
Vue.JS入门教程之处理表单
2016/12/01 Javascript
jQuery插件echarts实现的多折线图效果示例【附demo源码下载】
2017/03/04 Javascript
JS中LocalStorage与SessionStorage五种循序渐进的使用方法
2017/07/12 Javascript
seajs模块压缩问题与解决方法实例分析
2017/10/10 Javascript
js form表单input框限制20个字符,10个汉字代码实例
2019/04/12 Javascript
js实现超级玛丽小游戏
2020/03/18 Javascript
[01:51]2014DOTA2国际邀请赛 这个赛场没有失败者VGTi5再见
2014/07/23 DOTA
[59:30]完美世界DOTA2联赛PWL S3 access vs LBZS 第二场 12.20
2020/12/23 DOTA
Python使用Mechanize模块编写爬虫的要点解析
2016/03/31 Python
Python 文本文件内容批量抽取实例
2018/12/10 Python
python wav模块获取采样率 采样点声道量化位数(实例代码)
2020/01/22 Python
给Python学习者的文件读写指南(含基础与进阶)
2020/01/29 Python
Python 动态变量名定义与调用方法
2020/02/09 Python
Python实现AI换脸功能
2020/04/10 Python
python 解决selenium 中的 .clear()方法失效问题
2020/09/01 Python
猫咪家具:CatsPlay
2018/11/03 全球购物
Theo + George官方网站:都柏林时尚品牌
2019/04/08 全球购物
财务会计专业毕业生自荐信
2013/10/19 职场文书
实习自我鉴定范文
2013/10/30 职场文书
团委书记的竞聘演讲稿
2014/04/24 职场文书
教师三严三实心得体会
2014/10/11 职场文书
社区工作者个人总结
2015/02/28 职场文书
退货证明模板
2015/06/23 职场文书
元旦联欢晚会主持词
2015/07/01 职场文书
Python基础 括号()[]{}的详解
2021/11/07 Python
python opencv将多个图放在一个窗口的实例详解
2022/02/28 Python