基于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字符串编码识别模块chardet简单应用
Jun 15 Python
详解Python编程中对Monkey Patch猴子补丁开发方式的运用
May 27 Python
Python中音频处理库pydub的使用教程
Jun 07 Python
python 文件操作删除某行的实例
Sep 04 Python
详解Python 函数如何重载?
Apr 23 Python
PyCharm+Qt Designer+PyUIC安装配置教程详解
Jun 13 Python
python卸载后再次安装遇到的问题解决
Jul 10 Python
利用Python进行图像的加法,图像混合(附代码)
Jul 14 Python
对python中UDP,socket的使用详解
Aug 22 Python
PyQt5+Caffe+Opencv搭建人脸识别登录界面
Aug 28 Python
如何理解python面向对象编程
Jun 01 Python
Python实现Appium端口检测与释放的实现
Dec 31 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中利用XML技术构造远程服务(下)
2006/10/09 PHP
PHP 数组遍历方法大全(foreach,list,each)
2010/06/30 PHP
PHP的autoload自动加载机制使用说明
2010/12/28 PHP
php 解决旧系统 查出所有数据分页的类
2012/08/27 PHP
PHP中使用addslashes函数转义的安全性原理分析
2014/11/03 PHP
PHP获取数组中指定的一列实例
2017/12/27 PHP
通过ifame指向的页面高度调整iframe的高度
2006/10/05 Javascript
js检测客户端不是firefox则提示下载
2007/04/07 Javascript
DOM Scripting中的图片切换[兼容Firefox]
2010/06/12 Javascript
Function.prototype.call.apply结合用法分析示例
2013/07/03 Javascript
JavaScript程序员应该知道的45个实用技巧
2014/03/04 Javascript
js实现ArrayList功能附实例代码
2014/10/29 Javascript
jQuery animate和CSS3相结合实现缓动追逐效果附源码下载
2016/04/18 Javascript
Bootstrap CSS组件之按钮组(btn-group)
2016/12/17 Javascript
利用Angularjs中模块ui-route管理状态的方法
2016/12/27 Javascript
js模拟微博发布消息
2017/02/23 Javascript
vue组件中的数据传递方法
2018/05/14 Javascript
微信小程序中使用wxss加载图片并实现动画效果
2018/08/13 Javascript
微信小程序canvas拖拽、截图组件功能
2018/09/04 Javascript
解决vue 引入子组件报错的问题
2018/09/06 Javascript
vue基于viewer实现的图片查看器功能
2019/04/12 Javascript
vue实现随机验证码功能的实例代码
2019/04/30 Javascript
python中enumerate的用法实例解析
2014/08/18 Python
python实现微信接口(itchat)详细介绍
2017/10/23 Python
python3利用Dlib19.7实现人脸68个特征点标定
2018/02/26 Python
Python图像处理之颜色的定义与使用分析
2019/01/03 Python
python 求1-100之间的奇数或者偶数之和的实例
2019/06/11 Python
解决webdriver.Chrome()报错:Message:'chromedriver' executable needs to be in Path
2019/06/12 Python
简单了解Python3 bytes和str类型的区别和联系
2019/12/19 Python
Python 测试框架unittest和pytest的优劣
2020/09/26 Python
临床医学系毕业生推荐信
2013/11/09 职场文书
小摄影师教学反思
2014/04/27 职场文书
单身证明范本
2015/06/15 职场文书
2019同学聚会主持词
2019/05/06 职场文书
IDEA使用SpringAssistant插件创建SpringCloud项目
2021/06/23 Java/Android
MySQL表类型 存储引擎 的选择
2021/11/11 MySQL