假设emo文件夹下,有1,2,3,4等文件夹,每个文件夹代表一个类别

 import tensorflow as tf
from PIL import Image
from glob import glob
import os
import progressbar
import time class TFRecord():
def __init__(self, path=None, tfrecord_file=None):
self.path = path
self.tfrecord_file = tfrecord_file def _convert_image(self, idx, img_path, is_training=True):
label = idx with tf.gfile.FastGFile(img_path, 'rb') as fid:
img_str = fid.read() # img_data = Image.open(img_path)
# img_data = img_data.resize((224, 224))
# img_str = img_data.tobytes() file_name = img_path if is_training:
feature_key_value_pair = {
'file_name': tf.train.Feature(bytes_list=tf.train.BytesList(
value=[file_name.encode()])),
'img': tf.train.Feature(bytes_list=tf.train.BytesList(
value=[img_str])),
'label': tf.train.Feature(int64_list=tf.train.Int64List(
value=[label]))
}
else:
feature_key_value_pair = {
'file_name': tf.train.Feature(bytes_list=tf.train.BytesList(
value=[file_name.encode()])),
'img': tf.train.Feature(bytes_list=tf.train.BytesList(
value=[img_str])),
'label': tf.train.Feature(int64_list=tf.train.Int64List(
value=[-1]))
} feature = tf.train.Features(feature=feature_key_value_pair)
example = tf.train.Example(features=feature)
return example def convert_img_folder(self): folder_path = self.path
tfrecord_path = self.tfrecord_file
img_paths = []
for file in os.listdir(folder_path):
for img_path in os.listdir(os.path.join(folder_path, file)):
img_paths.append(os.path.join(folder_path, file, img_path)) with tf.python_io.TFRecordWriter(tfrecord_path) as tfwrite:
widgets = ['[INFO] write image to tfrecord: ', progressbar.Percentage(), " ",
progressbar.Bar(), " ", progressbar.ETA()]
pbar = progressbar.ProgressBar(maxval=len(img_paths), widgets=widgets).start() cate = [folder_path + '/' + x for x in os.listdir(folder_path) if
os.path.isdir(folder_path + '/' + x)] i = 0
for idx, folder in enumerate(cate):
for img_path in glob(folder + '/*.jpg'):
example = self._convert_image(idx, img_path)
tfwrite.write(example.SerializeToString())
pbar.update(i)
i += 1 pbar.finish() def _extract_fn(self, tfrecord):
feautres = {
'file_name': tf.FixedLenFeature([], tf.string),
'img': tf.FixedLenFeature([], tf.string),
'label': tf.FixedLenFeature([], tf.int64)
}
sample = tf.parse_single_example(tfrecord, feautres)
img = tf.image.decode_jpeg(sample['img'])
img = tf.image.resize_images(img, (224, 224), method=1)
label = sample['label']
file_name = sample['file_name']
return [img, label, file_name] def extract_image(self, shuffle_size, batch_size):
dataset = tf.data.TFRecordDataset([self.tfrecord_file])
dataset = dataset.map(self._extract_fn)
dataset = dataset.shuffle(shuffle_size).batch(batch_size)
print("---------", type(dataset))
return dataset if __name__=='__main__': # start = time.time()
# t = GenerateTFRecord('/')
# t.convert_img_folder('/media/xia/Data/emo', '/media/xia/Data/emo.tfrecord')
# print("Took %f seconds." % (time.time() - start)) t =TFRecord('/media/xia/Data/emo', '/media/xia/Data/emo.tfrecord')
t.convert_img_folder()
dataset = t.extract_image(100, 64)
for(batch, batch_data) in enumerate(dataset):
data, label, _ = batch_data
print(label)
print(data.shape)

ps: tf.enable_eager_execution()

tf.__version__==1.8.0

参考:https://zhuanlan.zhihu.com/p/30751039

https://lonepatient.top/2018/06/01/tensorflow_tfrecord.html

https://zhuanlan.zhihu.com/p/51186668

将数据转为tfrecord格式的更多相关文章

  1. 关于多条数据转为json格式单次传输的问题 2017.05.27

    数据形式如下: var mycars = [];//定义数组存放多条数据 for(var i=0;i<2;i++){ var jsonData = {};//定义变量存放单条数据 jsonDat ...

  2. C# -- HttpWebRequest 和 HttpWebResponse 的使用 C#编写扫雷游戏 使用IIS调试ASP.NET网站程序 WCF入门教程 ASP.Net Core开发(踩坑)指南 ASP.Net Core Razor+AdminLTE 小试牛刀 webservice创建、部署和调用 .net接收post请求并把数据转为字典格式

    C# -- HttpWebRequest 和 HttpWebResponse 的使用 C# -- HttpWebRequest 和 HttpWebResponse 的使用 结合使用HttpWebReq ...

  3. excel将百分比数据转为数值格式

    由于于原给定的数据是百分比格式的, 所以先在excel中将数据格式改为数值 修改步骤: 单纯更改单元格格式为数值没用,先在空白单元格输入数值格式的1,复制该数字,选中要转换格式的数据, 右键 ---- ...

  4. 将excel中的数据转为json格式

    ---恢复内容开始--- 用来总结工作中碰导一些错误,可以让自己在碰到相同错误的时候不至于重新走一遍.... 昨天导入数据的时候,碰到了一个问题是将一个大数组里面的每一个元素中的一些不要的去提出掉,本 ...

  5. axios——post请求时把对象obj数据转为formdata格式

    转载自:https://blog.csdn.net/feizhong_web/article/details/80514436  在调用后台接口的时候,上传报名信息,利用axios 的post请求,发 ...

  6. .net接收post请求并把数据转为字典格式

    public SortedDictionary<string, string> GetRequestPost() { int i = 0; SortedDictionary<stri ...

  7. 目标检测 的标注数据 .xml 转为 tfrecord 的格式用于 TensorFlow 训练

    将目标检测 的标注数据 .xml 转为 tfrecord 的格式用于 TensorFlow 训练. import xml.etree.ElementTree as ET import numpy as ...

  8. 读取mysql数据库的数据,转为json格式

    # coding=utf-8 ''' Created on 2016-10-26 @author: Jennifer Project:读取mysql数据库的数据,转为json格式 ''' import ...

  9. mha格式的CT体数据转为jpg切片

    mha格式的CT体数据转为jpg切片 mha格式 .mha文件是一种体数据的存储格式,由一个描述数据的头和数据组成,一般我们拿到的原始医学影像的数据是.dcm也就是dicom文件,dicom文件很复杂 ...

随机推荐

  1. 2018-2019-2 20165235《网络对抗技术》Exp7 网络欺诈防范

    2018-2019-2 20165235<网络对抗技术>Exp7 网络欺诈防范 实验目的 本实践的目标理解常用网络欺诈背后的原理,以提高防范意识,并提出具体防范方法 实验内容 (1)简单应 ...

  2. tihuantupian

  3. spring boot shiro redis整合基于角色和权限的安全管理-Java编程

    一.概述 本博客主要讲解spring boot整合Apache的shiro框架,实现基于角色的安全访问控制或者基于权限的访问安全控制,其中还使用到分布式缓存redis进行用户认证信息的缓存,减少数据库 ...

  4. sql 查询每天数据

    一 表 内数据存的是 ‘2017-09-08 15:13:59’这样格式 表 customer_mate_follow 时间字段 created_at   1, SELECT ,) as day, C ...

  5. HDU6534 Chika and Friendly Pairs(莫队,树状数组)

    HDU6534 Chika and Friendly Pairs 莫队,树状数组的简单题 #include<bits/stdc++.h> using namespace std; cons ...

  6. 【洛谷P2016战略游戏】

    树形dp的经典例题 题目描述 Bob喜欢玩电脑游戏,特别是战略游戏.但是他经常无法找到快速玩过游戏的办法.现在他有个问题. 他要建立一个古城堡,城堡中的路形成一棵树.他要在这棵树的结点上放置最少数目的 ...

  7. Windows下开发环境搭建

    安装Make: https://sourceforge.net/projects/gnuwin32/ 安装G++:https://sourceforge.net/projects/mingw/

  8. WPF DevExpress Chart控件多Y轴,指定数据参考的Y轴

    当Chart中有两个及以上的Y轴时,我们就要指明图表中的柱子或折线对应的是哪个Y轴了,这时候需要指明柱子或者折线的dxc:XYDiagram2D.SeriesAxisY属性,来设置对应的Y轴(dxc: ...

  9. 将html转化为canvas图片(清晰度高)的方法

    var copyDom = document.querySelector('.fenxiang1'); var width = copyDom.offsetWidth;//dom宽 var heigh ...

  10. Python实现比较两个列表(list)范围

    Python实现比较两个列表(list)范围 有一道题: 比较两个列表范围,如果包含的话,返回TRUE,否则FALSE. 详细题目如下: Create a function, this functio ...