将数据转为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文件很复杂 ...
随机推荐
- flask中request对象获取参数的方法
从当前request获取内容: method: 起始行,元数据 host: 起始行,元数据 path: 起始行,元数据 environ: 其中的 SERVER_PROTOCOL 是起始行,元数据 he ...
- Failed to read artifact descriptor for xxx:jar
在MyEclipse中执行Maven的install命令时,报“Failed to read artifact descriptor for xxx:jar ”的错误.这可能是在下载过程中文件出现错误 ...
- 关于Tomcat重启和关闭后重启session变化
,当页面第一次访问,session的attribute还未赋值,为null 当页面第二次访问时,这时当前的session的attribute有值了! 到了本文章的点题时刻!! 如果我是直接点击serv ...
- CNN中感受野的理解
本文摘自看完还不懂卷积神经网络“感受野”?那你来找我 作者:程序_小白链接:https://www.jianshu.com/p/9305d31962d8 一.到底什么是“感受野”(接受野Recepti ...
- leetcode-mid-math-202. Happy Number-NO
mycode 关键不知道怎么退出循环.............其实只要有一个平方和以前出现过,那么整个计算过程就会重复 参考: class Solution(object): def isHappy( ...
- maven 安装jar包命令
以 spring-context-support-3.1.0.RELEASE.jar 为例,在 @3图中已经给出这个 jar 包的 groupId,artifactId,version信息,手动安装的 ...
- 2019 ccpc 秦皇岛
D 如果1/n是有限小数,不停乘以10,一定在有限次之后成为一个整数. 10的质因子只有2和5,只要保证分母的质因子只有2和5即可 #include <iostream> #include ...
- Delphi XE2 之 FireMonkey 入门(39) - 控件基础: TScrollBox、TVertScrollBox、TFramedScrollBox、TFramedVertScrollBox
Delphi XE2 之 FireMonkey 入门(39) - 控件基础: TScrollBox.TVertScrollBox.TFramedScrollBox.TFramedVertScrollB ...
- spotlight监控linux性能
linux性能监控有很多工具,spotlight只是其中一种 目录 1.安装spotlight 2.参数认识 1.安装spotlight spotlight不仅仅只是监控linux,还可以完成数据库以 ...
- vue入门demo:用户管理3
该入门demo是使用组件的方式实现,不涉及向后端发送请求 说明 把用户列表和添加用户拆分为两个组件,用户列表数据在父组件 获取用户列表:用户列表组件获取父组件的用户列表(父组件向子组件传值)1-1 1 ...