将数据转为tfrecord格式
假设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格式的更多相关文章
- 关于多条数据转为json格式单次传输的问题 2017.05.27
数据形式如下: var mycars = [];//定义数组存放多条数据 for(var i=0;i<2;i++){ var jsonData = {};//定义变量存放单条数据 jsonDat ...
- 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 ...
- excel将百分比数据转为数值格式
由于于原给定的数据是百分比格式的, 所以先在excel中将数据格式改为数值 修改步骤: 单纯更改单元格格式为数值没用,先在空白单元格输入数值格式的1,复制该数字,选中要转换格式的数据, 右键 ---- ...
- 将excel中的数据转为json格式
---恢复内容开始--- 用来总结工作中碰导一些错误,可以让自己在碰到相同错误的时候不至于重新走一遍.... 昨天导入数据的时候,碰到了一个问题是将一个大数组里面的每一个元素中的一些不要的去提出掉,本 ...
- axios——post请求时把对象obj数据转为formdata格式
转载自:https://blog.csdn.net/feizhong_web/article/details/80514436 在调用后台接口的时候,上传报名信息,利用axios 的post请求,发 ...
- .net接收post请求并把数据转为字典格式
public SortedDictionary<string, string> GetRequestPost() { int i = 0; SortedDictionary<stri ...
- 目标检测 的标注数据 .xml 转为 tfrecord 的格式用于 TensorFlow 训练
将目标检测 的标注数据 .xml 转为 tfrecord 的格式用于 TensorFlow 训练. import xml.etree.ElementTree as ET import numpy as ...
- 读取mysql数据库的数据,转为json格式
# coding=utf-8 ''' Created on 2016-10-26 @author: Jennifer Project:读取mysql数据库的数据,转为json格式 ''' import ...
- mha格式的CT体数据转为jpg切片
mha格式的CT体数据转为jpg切片 mha格式 .mha文件是一种体数据的存储格式,由一个描述数据的头和数据组成,一般我们拿到的原始医学影像的数据是.dcm也就是dicom文件,dicom文件很复杂 ...
随机推荐
- p3863 序列
分析 按照时间为下标分块 块内按照大小排序 每次整块整体修改半块暴力重构即可 代码 #include<bits/stdc++.h> using namespace std; #define ...
- [C#菜鸟]C# Hook (一)
转过来的文章,出处已经不知道了,但只这篇步骤比较清晰,就贴出来了. 一.写在最前 本文的内容只想以最通俗的语言说明钩子的使用方法,具体到钩子的详细介绍可以参照下面的网址: http://www.mic ...
- Django信号量
摘自官方文档 使用 信号 Django发送的所有信号的列表.使用该send()方法发送所有内置信号. 参见 有关如何注册和接收信号的信息,请参阅信号调度器上的文档. 用户登录/注销时,身份验证框架会 ...
- Linux_指令杂烩
目录 目录 指令集合 常用于脚本的指令 查看变量的指令 监控命令 除了root用户的其他用户不能login 重定向 grep 过滤文件内容 vim预设定 系统在启动时要依次运行4个脚本 归档压缩文件互 ...
- 阶段2 JavaWeb+黑马旅游网_15-Maven基础_第2节 maven的安装和仓库种类_05仓库的种类和彼此关系
maven工程里面放的是jar包的坐标. 启动项目的时候会根据jar包的坐标到仓库中找对应的坐标 maven的安装目录.conf/settings.xml文件 ${user.home}表示系统盘,用户 ...
- windows7如何用键盘模拟鼠标操作
windows7如何用键盘模拟鼠标操作 https://jingyan.baidu.com/article/6dad5075104907a123e36e38.html 听语音 37453人看了这个视频 ...
- Apache hadoop namenode ha和yarn ha ---HDFS高可用性
HDFS高可用性Hadoop HDFS 的两大问题:NameNode单点:虽然有StandbyNameNode,但是冷备方案,达不到高可用--阶段性的合并edits和fsimage,以缩短集群启动的时 ...
- proteus 与 keil 的安装及联调
proteus 安装 Win10 系统的下载链接可以参考这里:https://tieba.baidu.com/p/5644915130?traceid= 百度网盘地址 链接1: http://pan. ...
- 正则表达式——Unicode
第 7 章 Unicode 7.1 关于编码 通常,英文编码较为统一,都采用ASCII编码或可以兼容ASCII编码(即编码表的前127位与ASCII编码一直,常见的各种编码,包括Unicode编码 ...
- Django框架效率问题的解决方法和总…
由于项目的需要,学习了Django框架,Django框架的MTV很清晰,通过MTV能够很好地了解Django框架的内部机理.但是在使用过程中发现了一个严重的问题,就是当有大量IO(写数据库操作)的时候 ...