TFRecord是tensorflow使用的数据格式, 类似于caffe的imdb,mxnet的recordio。使用框架定义的数据格式好处是有强大的框架支持,例如封装了数据解析、多线程等操作, 使用起来方便。坏处主要是需要数据转换,要占用额外的空间。
本文描述将pascal voc数据转换成tfrecord文件的过程,得到的tfrecord可用于训练。 代码主要参考 https://github.com/balancap/SSD-Tensorflow/blob/master/datasets/pascalvoc_to_tfrecords.py
读取图片
import tensorflow as tf
# path
data_dir = '/home/dengdan/dataset_nfs/pascal-voc/voc2007trainval/VOCdevkit/VOC2007'
image_idx = '008541'
image_path = '%s/JPEGImages/%s.jpg'%(data_dir, image_idx)
annotation_path = '%s/Annotations/%s.xml'%(data_dir, image_idx)
# read file
image_data = tf.gfile.FastGFile(image_path, 'r').read()
print type(image_data)
<type 'str'>
tf.gfile.FastGFile(image_path, 'r').read()
读取图片数据并以字符串形式返回. 至于如何编码暂时不用关心, 因为解码的过程也是tf完成。
读取annotation
pascal voc的标注以xml格式的文件存在, 可使用xml.etree.ElementTree
解析
import xml.etree.ElementTree as ET
tree = ET.parse(annotation_path)
root = tree.getroot()
size = root.find('size')
shape = [int(size.find('height').text),
int(size.find(