【CV】如何使用Tensorflow提供的Object Detection API --2--数据转换为TFRecord格式
本篇主要讲的是如何将现存的数据变成Tensorflow
记录格式,然后我们就可以用这些数据来进行微调模型,以解决我们关心的问题了。
什么是TFRecord格式
一般使用TF读取数据有四种方式:
- 预先把所有数据加载进内存
- 在每轮训练中使用原生Python代码读取一部分数据,然后使用feed_dict输入到计算图
- 利用Threading和Queues从TFRecord中分批次读取数据
- 使用Dataset API
后面两种都用的是TFRecord
格式。
Tensorflow物体检测API需要训练数据格式是TFRecord
格式。
TFRecord
格式会将所有的标记,比如边界框以及原始图像打包成一个文件,创建TFRecord格式的文件会有一些麻烦,但是一旦建立好以后,使用起来非常方便。
创建单个TFRecord文件
TF给了我们一个样例程序:
def create_tf_example(label_and_data_info):height = Nonewidth = Nonefilename = Noneencoded_image_data = None # encoded image bytesimage_format = None # b'jpeg' or b'png'# 存储标准化以后的数据,一个框一个值xmins = [] xmaxs = []ymins = []ymaxs = []classes_text = [] # 边界框的类别名classes = [] # 边界框的数字编号# TODOtf_label_and_data = tf.train.Example(features=tf.train.Features(feature={'image/height':dataset_util_int64_feature(height),'image/width': dataset_util_int64_feature(width), 'image/filename': dataset_util.bytes_feature(filename), 'image/source_id': dataset_util.bytes_feature(filename),'image/encoded': dataset_util.bytes_feature(encoded_image_data),'image/format': dataset_util.bytes_feature(image_format),'image/object/bbox/xmin': dataset_util.float_list_feature(xmins),'image/object/bbox/xmax': dataset_util.float_list_feature(xmaxs),'image/object/bbox/ymin': dataset_util.float_list_feature(ymins),'image/object/bbox/ymax': dataset_util.float_list_feature(ymaxs),'image/object/class/text': dataset_util.bytes_list_feature(classes_text),'image/object/class/label': dataset_util.int64_list_feature(classes),}))return tf_label_and_data
这个函数就是从单张图片中提取信息,注意到在方框信息和类别信息之外,我们还需要提供编码的图片数据,这个可以使用tf.gfile.GFile()
函数来完成。
创建完整的TFRecord文件
import tensorflow as tf
from object_detection.utils import dataset_utilflags = tf.app.flags
# 设定一个输入命令行参数
flags.DEFINE_string('output_path', '', 'Path to output TFRecord')
FLAGS = flags.FLAGSdef create_tf_example(data_and_label_info):...return tf_data_and_label
def main():writer = tf.python_io.TFRecordWriter(FLAGS.output_path)# TODOfile_loc = Noneall_data_and_label_info = LOAD(file_loc)for data_and_label_info in all_data_and_label_info:tf_example = create_tf_example(data_and_label_info)writer.write(tf_example_SerializeToString())writer.close()
if __name__ == '__main__':tf.app.run()
更具体的,针对Bosch Small Traffic Lights Dataset数据集,看这个老哥的实现,代码我拷贝如下:
import tensorflow as tf
import yaml
import os
from object_detection.utils import dataset_utilflags = tf.app.flags
flags.DEFINE_string('output_path', '', 'Path to output TFRecord')
FLAGS = flags.FLAGSLABEL_DICT = {"Green" : 1,"Red" : 2,"GreenLeft" : 3,"GreenRight" : 4,"RedLeft" : 5,"RedRight" : 6,"Yellow" : 7,"off" : 8,"RedStraight" : 9,"GreenStraight" : 10,"GreenStraightLeft" : 11,"GreenStraightRight" : 12,"RedStraightLeft" : 13,"RedStraightRight" : 14}def create_tf_example(example):# Boschheight = 720 # Image heightwidth = 1280 # Image widthfilename = example['path'] # Filename of the image. Empty if image is not from filefilename = filename.encode()with tf.gfile.GFile(example['path'], 'rb') as fid:encoded_image = fid.read()image_format = 'png'.encode() xmins = [] # List of normalized left x coordinates in bounding box (1 per box)xmaxs = [] # List of normalized right x coordinates in bounding box# (1 per box)ymins = [] # List of normalized top y coordinates in bounding box (1 per box)ymaxs = [] # List of normalized bottom y coordinates in bounding box# (1 per box)classes_text = [] # List of string class name of bounding box (1 per box)classes = [] # List of integer class id of bounding box (1 per box)for box in example['boxes']:#if box['occluded'] is False:#print("adding box")xmins.append(float(box['x_min'] / width))xmaxs.append(float(box['x_max'] / width))ymins.append(float(box['y_min'] / height))ymaxs.append(float(box['y_max'] / height))classes_text.append(box['label'].encode())classes.append(int(LABEL_DICT[box['label']]))tf_example = tf.train.Example(features=tf.train.Features(feature={'image/height': dataset_util.int64_feature(height),'image/width': dataset_util.int64_feature(width),'image/filename': dataset_util.bytes_feature(filename),'image/source_id': dataset_util.bytes_feature(filename),'image/encoded': dataset_util.bytes_feature(encoded_image),'image/format': dataset_util.bytes_feature(image_format),'image/object/bbox/xmin': dataset_util.float_list_feature(xmins),'image/object/bbox/xmax': dataset_util.float_list_feature(xmaxs),'image/object/bbox/ymin': dataset_util.float_list_feature(ymins),'image/object/bbox/ymax': dataset_util.float_list_feature(ymaxs),'image/object/class/text': dataset_util.bytes_list_feature(classes_text),'image/object/class/label': dataset_util.int64_list_feature(classes),}))return tf_exampledef main(_):writer = tf.python_io.TFRecordWriter(FLAGS.output_path)# BOSCHINPUT_YAML = "data/test-bosch/dataset_test_rgb/test.yaml"examples = yaml.load(open(INPUT_YAML, 'rb').read())#examples = examples[:10] # for testinglen_examples = len(examples)print("Loaded ", len(examples), "examples")for i in range(len(examples)):examples[i]['path'] = os.path.abspath(os.path.join(os.path.dirname(INPUT_YAML), examples[i]['path']))counter = 0for example in examples:tf_example = create_tf_example(example)writer.write(tf_example.SerializeToString())if counter % 10 == 0:print("Percent done", (counter/len_examples)*100)counter += 1writer.close()if __name__ == '__main__':tf.app.run()
其中,yaml
文件样式是:
- boxes:- {label: Green, occluded: false, x_max: 582.3417892052, x_min: 573.3726437481,y_max: 276.6271175345, y_min: 256.3114627642}- {label: Green, occluded: false, x_max: 517.6267821724, x_min: 510.0276868266,y_max: 273.164089267, y_min: 256.4279864221}path: ./rgb/train/2015-10-05-16-02-30_bag/720654.png
- boxes: []path: ./rgb/train/2015-10-05-16-02-30_bag/720932.png
写完执行的方式是:
python tf_record.py --output_path training.record
在上面代码中出现的命令行参数使用,下面展开细说一下。
tf.app.flags使用
- tf.app.flags.DEFINE_string函数
- tf.app.flags.FLAGS变量
flags
其实就是对ArgumentParser
的一层浅浅的封装。
使用tf.app.flags.DEFINE_xxx()
就是用来添加命令行的可选参数,使用tf.app.flags.FLAGS
就是用来从对应的命令行参数取出参数。
其中,xxx
可以是:
- string
- float
- int
- bool
等等。
DEFINE_XXX(flag_name, default_value, doctstring)
这个函数调用的是_define_helper函数
。
def _define_helper(flag_name, default_value, docstring, flagtype):_global_parser.add_argument('--' + flag_name,default=default_value,help=docstring, type=flagtype)
使用示例:
import tensorflow as tf
FLAGS = tf.app.flags.FLAGS # 用于提取命令行参数
tf.app.flags.DEFINE_float('FLOAT', 0.01, 'Input a float number')
tf.app.flags.DEFINE_integer('INT',100, 'Input an integer number')
tf.app.flags.DEFINE_boolean('BOOL', True, 'Input a boolean number')# 直接通过FLAGS对象提取命令行参数
print(FLAGS.FLOAT)
print(FLAGS.INT)
print(FLAGS.BOOL)
END.
参考:
https://blog.csdn.net/m0_37041325/article/details/77448971
https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/platform/flags.py
【CV】如何使用Tensorflow提供的Object Detection API --2--数据转换为TFRecord格式相关推荐
- 【CV】如何使用Tensorflow提供的Object Detection API --1--使用预训练模型
Tensorflow的物体检测API是非常强大的工具,它可以使得没有机器学习背景的人都可以快速部署强大的图像识别,物体检测模型.但是,考虑到使用的指导文档不够丰富,具体如何使用成了很多人的门槛. 本篇 ...
- Tensorflow Object Detection API生成自己的tfrecord训练数据集
Object Detection API谷歌 该文章部分参考别的大佬的,由于忘了内容出处,所以没有加转载链接,请谅解,有原创作者看到可以联系我添加. ========转载请注明出处========== ...
- 【CV】如何使用Tensorflow提供的Object Detection API--3--手工标注数据
前面两篇看完,我们已经知道如何选用预训练模型以及将现存的其他数据集变成TFRecord格式的数据了. 但是如果需要用你自己的数据集,该怎么办呢? 本篇主要讲如何创建自己的数据集,并用object_de ...
- 【CV】如何使用Tensorflow提供的Object Detection API--4--开始训练模型
至此已经学习了如何选择预训练模型,将数据集转为TFRecord格式.模型和数据都准备好了,是时候开启训练了. 这些在COCO数据集上的模型都是针对90类进行识别的,如果自己的任务没有这么多类,或者类不 ...
- TensorFlow Object Detection API Custom Object Hangs On
TensorFlow Object Detection API Hangs On - Training and Evaluating using Custom Object Detector *The ...
- 【物体检测快速入门系列 | 01 】基于Tensorflow2.x Object Detection API构建自定义物体检测器
这是机器未来的第1篇文章 原文首发地址:https://blog.csdn.net/RobotFutures/article/details/124745966 CSDN话题挑战赛第1期 活动详情地址 ...
- Tensorflow object detection API 搭建物体识别模型
----------------------------------------------------先把别人博客教程跑通-------------------------------------- ...
- 谷歌开放的TensorFlow Object Detection API 效果如何?对业界有什么影响
? 谷歌开放了一个 Object Detection API: Supercharge your C 写个简单的科普帖吧. 熟悉TensorFlow的人都知道,tf在Github上的主页是:tenso ...
- tensorflow精进之路(二十五)——Object Detection API目标检测(下)(VOC数据集训练自己的模型进行目标检测)
1.概述 上一讲,我们使用了别人根据COCO数据集训练好的模型来做目标检测,这一讲,我们就来训练自己的模型. 2.下载数据集 为了方便学习,我们先使用别人整理好的数据集来训练---VOC 2012数据 ...
最新文章
- 【青少年编程】【二级】绘制图形
- (2006, 'MySQL server has gone away') 错误解决 - dba007的空间 - 51CTO技术博客
- List-ArrayList 使用
- 苹果股价周一下跌4.17% 市值今年首次跌破2万亿美元
- python怎么开发gui程序_第一个GUI程序
- 在linux缓存里写数据,缓存策略
- ImageNet夺冠后转战NLP!卡内基梅隆华人博士提出谷歌搜索引擎核心技术
- 交叉熵和相对熵(KL散度)
- Git基础-git恢复被删除的文件
- 给买车的来点干货——汽车品牌分析
- 【Java练习】图书管理系统【详解篇15+完整代码】
- java web 甘特图_基于Web开发的甘特图控件,支持Java、.Net
- TQ2440之内核3.15.6移植
- 宽带连接已断开 | 宽带拨号上网、连上几分之后自动断开|宽带连上一会儿就断
- 反斗联盟不显示服务器,《反斗联盟》关服公告
- AI三大主义:符号主义、联结主义、行为主义
- 录音实时转写软件哪个好?这三个软件帮你搞定录音如何转文字
- 浙大PAT考试1013~1016(最伤的一次。。)
- docker环境下orientdb的数据库导入与导出
- 2019年区块链技术领域的三个主要冲突
热门文章
- caffe学习日记--lesson7:caffemodel可视化的两种方法
- C++ Primer Plus学习(九)——内存模型和名称空间
- python样本不均衡_三招提拔数据不均衡模子的机能(附python代码)
- maps-api-v3_Android Google Maps API集成
- jsp el 表达式_JSP表达式语言– JSP EL示例教程
- android实例教程_活动之间的Android意向处理示例教程
- 非基元类型数据结构_Java数据类型–基元和二进制文字
- 一文读懂Netty的核心构成块
- 开课吧Java:微服务设计遵循的规约有哪些?
- 产品设计的基本原则是什么