Fork版本项目地址:SSD

一、数据格式介绍

数据文件夹命名为VOC2012,内部有5个子文件夹,如下,

我们的检测任务中使用JPEGImages文件夹和Annotations文件夹。

JPEGImages文件夹中包含了PASCAL VOC所提供的所有的图片信息,包括了训练图片和测试图片。

这些图像都是以“年份_编号.jpg”格式命名的。
图片的像素尺寸大小不一,但是横向图的尺寸大约在500*375左右,纵向图的尺寸大约在375*500左右,基本不会偏差超过100。(在之后的训练中,第一步就是将这些图片都resize到300*300或是500*500,所有原始图片不能离这个标准过远。)
这些图像就是用来进行训练和测试验证的图像数据。
Annotations文件夹中存放的是xml格式的标签文件,每一个xml文件都对应于JPEGImages文件夹中的一张图片。

xml文件的具体格式如下:(对于2007_000392.jpg)

  1. <annotation>
  2. <folder>VOC2012</folder>
  3. <filename>2007_000392.jpg</filename> //文件名
  4. <source> //图像来源(不重要)
  5. <database>The VOC2007 Database</database>
  6. <annotation>PASCAL VOC2007</annotation>
  7. <image>flickr</image>
  8. </source>
  9. <size> //图像尺寸(长宽以及通道数)
  10. <width>500</width>
  11. <height>332</height>
  12. <depth>3</depth>
  13. </size>
  14. <segmented>1</segmented> //是否用于分割(在图像物体识别中01无所谓)
  15. <object> //检测目标
  16. <name>horse</name> //物体类别
  17. <pose>Right</pose> //拍摄角度
  18. <truncated>0</truncated> //是否被截断(0表示完整)
  19. <difficult>0</difficult> //目标是否难以识别(0表示容易识别)
  20. <bndbox> //bounding-box(包含左上角和右下角xy坐标)
  21. <xmin>100</xmin>
  22. <ymin>96</ymin>
  23. <xmax>355</xmax>
  24. <ymax>324</ymax>
  25. </bndbox>
  26. </object>
  27. <object> //多检测目标
  28. <name>person</name>
  29. <pose>Unspecified</pose>
  30. <truncated>0</truncated>
  31. <difficult>0</difficult>
  32. <bndbox>
  33. <xmin>198</xmin>
  34. <ymin>58</ymin>
  35. <xmax>286</xmax>
  36. <ymax>197</ymax>
  37. </bndbox>
  38. </object>
  39. </annotation>

二、TFR数据生成流程

为了加快数据的读取,框架将数据及标签预先读取并写入tfrecord中,这一部分独立于网络或者说训练结构之外,我们单独介绍这一部分。

启动命令如下,注意需要提前建好OUTPUT_DIR文件夹否则会报错(运行命令时去掉注释),

  1. DATASET_DIR=./VOC2012/
  2. OUTPUT_DIR=./tfrecords
  3. python tf_convert_data.py \
  4. --dataset_name=pascalvoc \ # 数据集名称,实际作者就实现了这一个数据集的预处理方法
  5. --dataset_dir=${DATASET_DIR} \
  6. --output_name=voc_2012_train # tfr文件名,为了兼容后面的程序,命名格式较为固定
  7. --output_dir=${OUTPUT_DIR}

脚本tf_convert_data.py

这个脚本主要用于和命令行交互,核心功能就一句调用命令:

  1. # './VOC2012/' './tfrecords' 'voc2012_tfr'
  2. pascalvoc_to_tfrecords.run(FLAGS.dataset_dir, FLAGS.output_dir, FLAGS.output_name)

脚本datasets.pascalvoc_to_tfrecords.py

run函数是tfr书写的核心函数,在这个函数中,我们确定具体的每一个tfr文件名,循环的读取图片和标签数据名称,按照指定的容量取书写到每一个tfr文件。

  1. def run(dataset_dir, output_dir, name='voc_train', shuffling=False):
  2. """Runs the conversion operation.
  3. Args:
  4. dataset_dir: The dataset directory where the dataset is stored.
  5. output_dir: Output directory.
  6. """
  7. if not tf.gfile.Exists(dataset_dir):
  8. tf.gfile.MakeDirs(dataset_dir)
  9.  
  10. # Dataset filenames, and shuffling.
  11. # './VOC2012/' 'Annotations/'
  12. path = os.path.join(dataset_dir, DIRECTORY_ANNOTATIONS)
  13. filenames = sorted(os.listdir(path)) # 无路径文件名
  14. if shuffling:
  15. random.seed(RANDOM_SEED)
  16. random.shuffle(filenames)
  17.  
  18. # Process dataset files.
  19. i = 0
  20. fidx = 0
  21. while i < len(filenames): # 循环文件名
  22. # Open new TFRecord file.
  23. tf_filename = _get_output_filename(output_dir, name, fidx) # 获取输出文件名
  24. with tf.python_io.TFRecordWriter(tf_filename) as tfrecord_writer:
  25. j = 0
  26. while i < len(filenames) and j < SAMPLES_PER_FILES: # 一个文件200张图
  27. sys.stdout.write('\r>> Converting image %d/%d' % (i+1, len(filenames)))
  28. sys.stdout.flush() # 这两句的输出不会生成多行报告,而是在同一行不断更新数字
  29.  
  30. filename = filenames[i]
  31. img_name = filename[:-4] # 图片名称,去掉字符'.jpg'
  32. _add_to_tfrecord(dataset_dir, img_name, tfrecord_writer) # 获取数据并书写
  33. i += 1
  34. j += 1
  35. fidx += 1
  36.  
  37. # Finally, write the labels file:
  38. # labels_to_class_names = dict(zip(range(len(_CLASS_NAMES)), _CLASS_NAMES))
  39. # dataset_utils.write_label_file(labels_to_class_names, dataset_dir)
  40. print('\nFinished converting the Pascal VOC dataset!')

这其中,确定具体的每一个tfr文件名函数_get_output_filename很简单,而由文件名读取数据并书写进tfr函数也就分为读文件和写文件两步骤,都很直观,

  1. def _add_to_tfrecord(dataset_dir, name, tfrecord_writer):
  2. """Loads data from image and annotations files and add them to a TFRecord.
  3.  
  4. Args:
  5. dataset_dir: Dataset directory;
  6. name: Image name to add to the TFRecord;
  7. tfrecord_writer: The TFRecord writer to use for writing.
  8. """
  9. image_data, shape, bboxes, labels, labels_text, difficult, truncated = \
  10. _process_image(dataset_dir, name) # 由文件名读取数据
  11. example = _convert_to_example(image_data, labels, labels_text,
  12. bboxes, shape, difficult, truncated) # 书写tfr
  13. tfrecord_writer.write(example.SerializeToString())
  14.  
  15. def _get_output_filename(output_dir, name, idx):
  16. return '%s/%s_%03d.tfrecord' % (output_dir, name, idx)

下面是读取图片、标签数据以及书写example的两个函数,实际工作中就是这样每次读取一个图片文件及其对应的标注文件并处理,

  1. def _process_image(directory, name):
  2. """
  3. 将图片数据存储为bytes,
  4. :param directory: voc文件夹
  5. :param name: 图片名
  6. :return: 需要写入tfr的数据
  7. """
  8. # Read the image file.
  9. # DIRECTORY_IMAGES = 'JPEGImages/'
  10. filename = directory + DIRECTORY_IMAGES + name + '.jpg'
  11. image_data = tf.gfile.FastGFile(filename, 'rb').read() # 源码中'rb'错写成'r'
  12.  
  13. # Read the XML annotation file.
  14. filename = os.path.join(directory, DIRECTORY_ANNOTATIONS, name + '.xml')
  15. tree = ET.parse(filename)
  16. root = tree.getroot()
  17.  
  18. # Image shape.
  19. size = root.find('size')
  20. shape = [int(size.find('height').text),
  21. int(size.find('width').text),
  22. int(size.find('depth').text)]
  23. # Find annotations.
  24. bboxes = []
  25. labels = []
  26. labels_text = []
  27. difficult = []
  28. truncated = []
  29. for obj in root.findall('object'):
  30. label = obj.find('name').text
  31. labels.append(int(VOC_LABELS[label][0]))
  32. labels_text.append(label.encode('ascii'))
  33.  
  34. if obj.find('difficult'):
  35. difficult.append(int(obj.find('difficult').text))
  36. else:
  37. difficult.append(0)
  38. if obj.find('truncated'):
  39. truncated.append(int(obj.find('truncated').text))
  40. else:
  41. truncated.append(0)
  42.  
  43. bbox = obj.find('bndbox')
  44. bboxes.append((float(bbox.find('ymin').text) / shape[0],
  45. float(bbox.find('xmin').text) / shape[1],
  46. float(bbox.find('ymax').text) / shape[0],
  47. float(bbox.find('xmax').text) / shape[1]
  48. ))
  49. return image_data, shape, bboxes, labels, labels_text, difficult, truncated
  50.  
  51. def _convert_to_example(image_data, labels, labels_text, bboxes, shape,
  52. difficult, truncated):
  53. """Build an Example proto for an image example.
  54.  
  55. Args:
  56. image_data: string, JPEG encoding of RGB image;
  57. labels: list of integers, identifier for the ground truth;
  58. labels_text: list of strings, human-readable labels;
  59. bboxes: list of bounding boxes; each box is a list of integers;
  60. specifying [xmin, ymin, xmax, ymax]. All boxes are assumed to belong
  61. to the same label as the image label.
  62. shape: 3 integers, image shapes in pixels.
  63. Returns:
  64. Example proto
  65. """
  66. xmin = []
  67. ymin = []
  68. xmax = []
  69. ymax = []
  70. for b in bboxes:
  71. assert len(b) == 4
  72. # pylint: disable=expression-not-assigned
  73. [l.append(point) for l, point in zip([ymin, xmin, ymax, xmax], b)]
  74. # pylint: enable=expression-not-assigned
  75.  
  76. image_format = b'JPEG'
  77. example = tf.train.Example(features=tf.train.Features(feature={
  78. 'image/height': int64_feature(shape[0]),
  79. 'image/width': int64_feature(shape[1]),
  80. 'image/channels': int64_feature(shape[2]),
  81. 'image/shape': int64_feature(shape),
  82. 'image/object/bbox/xmin': float_feature(xmin),
  83. 'image/object/bbox/xmax': float_feature(xmax),
  84. 'image/object/bbox/ymin': float_feature(ymin),
  85. 'image/object/bbox/ymax': float_feature(ymax),
  86. 'image/object/bbox/label': int64_feature(labels),
  87. 'image/object/bbox/label_text': bytes_feature(labels_text),
  88. 'image/object/bbox/difficult': int64_feature(difficult),
  89. 'image/object/bbox/truncated': int64_feature(truncated),
  90. 'image/format': bytes_feature(image_format), # 图像编码格式
  91. 'image/encoded': bytes_feature(image_data)})) # 二进制图像数据
  92. return example

至此,数据预处理tfr文件生成步骤就完成了。

附录、Example feature生成函数

具体的example feature生成函数比较简单,为了完整性,下面给出来,位于程序脚本datasets.dataset_utils.py中:

  1. def int64_feature(value):
  2. """Wrapper for inserting int64 features into Example proto.
  3. """
  4. if not isinstance(value, list):
  5. value = [value]
  6. return tf.train.Feature(int64_list=tf.train.Int64List(value=value))
  7.  
  8. def float_feature(value):
  9. """Wrapper for inserting float features into Example proto.
  10. """
  11. if not isinstance(value, list):
  12. value = [value]
  13. return tf.train.Feature(float_list=tf.train.FloatList(value=value))
  14.  
  15. def bytes_feature(value):
  16. """Wrapper for inserting bytes features into Example proto.
  17. """
  18. if not isinstance(value, list):
  19. value = [value]
  20. return tf.train.Feature(bytes_list=tf.train.BytesList(value=value))

标签数字序号对应表

  1. VOC_LABELS = {
  2. 'none': (0, 'Background'),
  3. 'aeroplane': (1, 'Vehicle'),
  4. 'bicycle': (2, 'Vehicle'),
  5. 'bird': (3, 'Animal'),
  6. 'boat': (4, 'Vehicle'),
  7. 'bottle': (5, 'Indoor'),
  8. 'bus': (6, 'Vehicle'),
  9. 'car': (7, 'Vehicle'),
  10. 'cat': (8, 'Animal'),
  11. 'chair': (9, 'Indoor'),
  12. 'cow': (10, 'Animal'),
  13. 'diningtable': (11, 'Indoor'),
  14. 'dog': (12, 'Animal'),
  15. 'horse': (13, 'Animal'),
  16. 'motorbike': (14, 'Vehicle'),
  17. 'person': (15, 'Person'),
  18. 'pottedplant': (16, 'Indoor'),
  19. 'sheep': (17, 'Animal'),
  20. 'sofa': (18, 'Indoor'),
  21. 'train': (19, 'Vehicle'),
  22. 'tvmonitor': (20, 'Indoor'),
  23. }

『TensorFlow』SSD源码学习_其四:数据介绍及TFR文件生成的更多相关文章

  1. 『TensorFlow』SSD源码学习_其一:论文及开源项目文档介绍

    一.论文介绍 读论文系列:Object Detection ECCV2016 SSD 一句话概括:SSD就是关于类别的多尺度RPN网络 基本思路: 基础网络后接多层feature map 多层feat ...

  2. 『TensorFlow』SSD源码学习_其五:TFR数据读取&数据预处理

    Fork版本项目地址:SSD 一.TFR数据读取 创建slim.dataset.Dataset对象 在train_ssd_network.py获取数据操作如下,首先需要slim.dataset.Dat ...

  3. 『TensorFlow』SSD源码学习_其二:基于VGG的SSD网络前向架构

    Fork版本项目地址:SSD 参考自集智专栏 一.SSD基础 在分类器基础之上想要识别物体,实质就是 用分类器扫描整张图像,定位特征位置 .这里的关键就是用什么算法扫描,比如可以将图片分成若干网格,用 ...

  4. 『TensorFlow』SSD源码学习_其七:损失函数

    Fork版本项目地址:SSD 一.损失函数介绍 SSD损失函数分为两个部分:对应搜索框的位置loss(loc)和类别置信度loss(conf).(搜索框指网络生成的网格) 详细的说明如下: i指代搜索 ...

  5. 『TensorFlow』SSD源码学习_其八:网络训练

    Fork版本项目地址:SSD 作者使用了分布式训练的写法,这使得训练部分代码异常臃肿,我给出了部分注释.我对于多机分布式并不很熟,而且不是重点,所以不过多介绍,简单的给出一点训练中作者的优化手段,包含 ...

  6. 『TensorFlow』SSD源码学习_其六:标签整理

    Fork版本项目地址:SSD 一.输入标签生成 在数据预处理之后,图片.类别.真实框格式较为原始,不能够直接作为损失函数的输入标签(ssd向前网络只需要图像就行,这里的处理主要需要满足loss的计算) ...

  7. 『TensorFlow』SSD源码学习_其三:锚框生成

    Fork版本项目地址:SSD 上一节中我们定义了vgg_300的网络结构,实际使用中还需要匹配SSD另一关键组件:被选取特征层的搜索网格.在项目中,vgg_300网络和网格生成都被统一进一个class ...

  8. nginx源码学习_源码结构

    nginx的优秀除了体现在程序结构以及代码风格上,nginx的源码组织也同样简洁明了,目录结构层次结构清晰,值得我们去学习.nginx的源码目录与nginx的模块化以及功能的划分是紧密结合,这也使得我 ...

  9. 『TensorFlow』读书笔记_TFRecord学习

    一.程序介绍 1.包导入 # Author : Hellcat # Time : 17-12-29 import os import numpy as np np.set_printoptions(t ...

随机推荐

  1. sed命令使用详解

        内容来自马哥视频,感谢马哥精彩讲解 sed:编辑器 sed: Stream EDitor, 行编辑器,逐行进行处理 grep:实现文本过滤 awk:文本报告生成器 sed默认不编辑源文件,而是 ...

  2. Linux 服务器 安装 goflyway

    github官方开发主页:https://github.com/coyove/goflyway goflyway的用途就不说了,你能搜到此文章就说明已经知道了. centos和Ubuntu均可使用,其 ...

  3. _equipment

    该表控制切换地图自动更换装备,离开该地图时,装备自动切换为原来.,HEAD - TABARD小于0时取下装备,等于0时不更换,大于0时更换为对应装备. comment 备注 class 职业索引 1- ...

  4. GYM 101064 2016 USP Try-outs G. The Declaration of Independence 主席树

    G. The Declaration of Independence time limit per test 1 second memory limit per test 256 megabytes ...

  5. python,函数的基本用法

    一.函数 函数的概念:对功能或者动作的封装可以帮我们把一段公共的代码提取出来 语法如下 def 函数名(形参): 函数体 函数名(实参) # 函数名() def yue(): print(" ...

  6. PostgreSQL安装及使用教程一(exe安装方式)

    下载安装 百度搜索PostgreSQL,进入官网,选择相应版本的图形化安装程序(BigSQL)安装即可 连接数据库 对数据库操作有两种方式,一种是通过命令行工具psql,另一种是通过图形化界面pgAd ...

  7. Eclipse使用之将Git项目转为Maven项目, ( 注意: 最后没有pom.xml文件的, 要转化下 )

    Eclipse使用之将Git项目转为Maven项目(全图解) 2017年08月11日 09:24:31 阅读数:427 1.打开Eclipse,File->Import 2.Git->Pr ...

  8. 力扣(LeetCode)58. 最后一个单词的长度

    给定一个仅包含大小写字母和空格 ' ' 的字符串,返回其最后一个单词的长度. 如果不存在最后一个单词,请返回 0 . 说明:一个单词是指由字母组成,但不包含任何空格的字符串. 示例: 输入: &quo ...

  9. javascript AOP(面向切面编程)

    var func = function () { console.log("2") } Function.prototype.before = function (beforefn ...

  10. asp.net 虹软人脸识别sdk 释放内存

    初始化时申请内存,用完记得释放,不然就会报“内存已满”的. 使用时: pMem = Marshal.AllocHGlobal(detectSize); 释放内存: Marshal.FreeHGloba ...