Tensorflow中的object detection API:準(zhǔn)備輸入數(shù)據(jù)

Preparing Inputs

代碼高能預(yù)警

Tensorflow Object Detection API 在讀取數(shù)據(jù)中使用了TFRecord文件格式。API提供了兩個(gè)示例腳本烈拒,(create_pascal_tf_record.pycreate_pet_tf_record.py)荆几。這里我們精讀一下代碼create_pascal_tf_record.py

掌握TFRocord讀取方法的可以跳級(jí)了行拢。
先看一下License

# Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# 

這個(gè)腳本的主要用處是把PASCAL數(shù)據(jù)集轉(zhuǎn)換成TFRecord舟奠。
用法是

  ./create_pascal_tf_record --data_dir=/home/user/VOCdevkit \  --year=VOC2012 \      --output_path=/home/user/pascal.record

引入各種庫

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import hashlib
import io
import logging
import os

from lxml import etree
import PIL.Image
import tensorflow as tf

from object_detection.utils import dataset_util
from object_detection.utils import label_map_util

到這一步沼瘫,程序都在引入各種各樣的庫晕鹊,沒有的裝就是了暴浦。

flags

flags = tf.app.flags
flags.DEFINE_string('data_dir', '', 'Root directory to raw PASCAL VOC dataset.')
flags.DEFINE_string('set', 'train', 'Convert training set, validation set or '
                    'merged set.')
flags.DEFINE_string('annotations_dir', 'Annotations',
                    '(Relative) path to annotations directory.')
flags.DEFINE_string('year', 'VOC2007', 'Desired challenge year.')
flags.DEFINE_string('output_path', '', 'Path to output TFRecord')
flags.DEFINE_string('label_map_path', 'data/pascal_label_map.pbtxt',
                    'Path to label map proto')
flags.DEFINE_boolean('ignore_difficult_instances', False, 'Whether to ignore '
                     'difficult instances')
FLAGS = flags.FLAGS

Tensorflow 中的flags類似于argv歌焦,基本用法是flags.DEFINE_類型('參數(shù)名稱'独撇,'默認(rèn)值','參數(shù)描述')卵史。進(jìn)一步了解flags用法請(qǐng)移步tensorflow 學(xué)習(xí)(三)使用flags定義命令行參數(shù) 搜立。

dict_to_tf_example

SETS = ['train', 'val', 'trainval', 'test']
YEARS = ['VOC2007', 'VOC2012', 'merged']

def dict_to_tf_example(data,
                       dataset_directory,
                       label_map_dict,
                       ignore_difficult_instances=False,
                       image_subdirectory='JPEGImages'):
 
  img_path = os.path.join(data['folder'], image_subdirectory, data['filename'])
  full_path = os.path.join(dataset_directory, img_path)
  with tf.gfile.GFile(full_path, 'rb') as fid:
    encoded_jpg = fid.read()
  encoded_jpg_io = io.BytesIO(encoded_jpg)
  image = PIL.Image.open(encoded_jpg_io)
  if image.format != 'JPEG':
    raise ValueError('Image format not JPEG')
  key = hashlib.sha256(encoded_jpg).hexdigest()

  width = int(data['size']['width'])
  height = int(data['size']['height'])

  xmin = []
  ymin = []
  xmax = []
  ymax = []
  classes = []
  classes_text = []
  truncated = []
  poses = []
  difficult_obj = []
  for obj in data['object']:
    difficult = bool(int(obj['difficult']))
    if ignore_difficult_instances and difficult:
      continue

    difficult_obj.append(int(difficult))

    xmin.append(float(obj['bndbox']['xmin']) / width)
    ymin.append(float(obj['bndbox']['ymin']) / height)
    xmax.append(float(obj['bndbox']['xmax']) / width)
    ymax.append(float(obj['bndbox']['ymax']) / height)
    classes_text.append(obj['name'].encode('utf8'))
    classes.append(label_map_dict[obj['name']])
    truncated.append(int(obj['truncated']))
    poses.append(obj['pose'].encode('utf8'))

  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(
          data['filename'].encode('utf8')),
      'image/source_id': dataset_util.bytes_feature(
          data['filename'].encode('utf8')),
      'image/key/sha256': dataset_util.bytes_feature(key.encode('utf8')),
      'image/encoded': dataset_util.bytes_feature(encoded_jpg),
      'image/format': dataset_util.bytes_feature('jpeg'.encode('utf8')),
      'image/object/bbox/xmin': dataset_util.float_list_feature(xmin),
      'image/object/bbox/xmax': dataset_util.float_list_feature(xmax),
      'image/object/bbox/ymin': dataset_util.float_list_feature(ymin),
      'image/object/bbox/ymax': dataset_util.float_list_feature(ymax),
      'image/object/class/text': dataset_util.bytes_list_feature(classes_text),
      'image/object/class/label': dataset_util.int64_list_feature(classes),
      'image/object/difficult': dataset_util.int64_list_feature(difficult_obj),
      'image/object/truncated': dataset_util.int64_list_feature(truncated),
      'image/object/view': dataset_util.bytes_list_feature(poses),
  }))
  return example

這段主要定義了一個(gè)函數(shù)dict_to_tf_example的函數(shù),用以將PASCAL數(shù)據(jù)集中的XML標(biāo)注文件轉(zhuǎn)換為tf.Example.
輸入?yún)?shù)為:

  • data: 包含標(biāo)注信息的XML文件址晕。PASCAL數(shù)據(jù)集中顿锰,每張圖片的標(biāo)注信息存放于對(duì)應(yīng)的XML文件中。在main函數(shù)中刘陶,data是通過dataset_util.recursive_parse_xml_to_dict的方法將XML中信息導(dǎo)入為字典獲取的易核;
  • dataset_directory: 你懂得浪默;
  • label_map_dict: 為每一個(gè)類別賦予一個(gè)id纳决;由默認(rèn)路徑下已有文本給出碰逸;
  • ignore_difficult_instances: 是否忽略數(shù)據(jù)集中的difficult_instances。 保持默認(rèn)即可阔加;
  • image_subdirectory: 包含Images的PASCAL數(shù)據(jù)集的子文件夾饵史,同樣保持默認(rèn)即可。

在得到圖片的絕對(duì)路徑后(full_path)胜榔,通過GFile實(shí)現(xiàn)對(duì)圖片的讀取胳喷,并用PIL打開成為我們喜聞樂見的[c,h,w]格式。

而后夭织,將data傳過來的信息轉(zhuǎn)化為規(guī)范化的格式(x/width,y/height)添加到列表中吭露。說到這里就不得不夸一下dataset_util.recursive_parse_xml_to_dict這個(gè)配件了,from XML to dict尊惰,很方便的讲竿。

再然后定義了一個(gè)tf.train.Example 實(shí)例example弄屡,將獲得的信息全加進(jìn)去题禀,最后返回example。

def main(_):
  if FLAGS.set not in SETS:
    raise ValueError('set must be in : {}'.format(SETS))
  if FLAGS.year not in YEARS:
    raise ValueError('year must be in : {}'.format(YEARS))

  data_dir = FLAGS.data_dir
  years = ['VOC2007', 'VOC2012']
  if FLAGS.year != 'merged':
    years = [FLAGS.year]

  writer = tf.python_io.TFRecordWriter(FLAGS.output_path)

  label_map_dict = label_map_util.get_label_map_dict(FLAGS.label_map_path)

  for year in years:
    logging.info('Reading from PASCAL %s dataset.', year)
    examples_path = os.path.join(data_dir, year, 'ImageSets', 'Main',
                                 'aeroplane_' + FLAGS.set + '.txt')
    annotations_dir = os.path.join(data_dir, year, FLAGS.annotations_dir)
    examples_list = dataset_util.read_examples_list(examples_path)
    for idx, example in enumerate(examples_list):
      if idx % 100 == 0:
        logging.info('On image %d of %d', idx, len(examples_list))
      path = os.path.join(annotations_dir, example + '.xml')
      with tf.gfile.GFile(path, 'r') as fid:
        xml_str = fid.read()
      xml = etree.fromstring(xml_str)
      data = dataset_util.recursive_parse_xml_to_dict(xml)['annotation']

      tf_example = dict_to_tf_example(data, FLAGS.data_dir, label_map_dict,
                                      FLAGS.ignore_difficult_instances)
      writer.write(tf_example.SerializeToString())

  writer.close()


if __name__ == '__main__':
  tf.app.run()

把example保存為TFRecord格式膀捷。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末迈嘹,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子担孔,更是在濱河造成了極大的恐慌江锨,老刑警劉巖,帶你破解...
    沈念sama閱讀 222,252評(píng)論 6 516
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件糕篇,死亡現(xiàn)場(chǎng)離奇詭異啄育,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)拌消,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,886評(píng)論 3 399
  • 文/潘曉璐 我一進(jìn)店門挑豌,熙熙樓的掌柜王于貴愁眉苦臉地迎上來安券,“玉大人,你說我怎么就攤上這事氓英『蠲悖” “怎么了?”我有些...
    開封第一講書人閱讀 168,814評(píng)論 0 361
  • 文/不壞的土叔 我叫張陵铝阐,是天一觀的道長址貌。 經(jīng)常有香客問我,道長徘键,這世上最難降的妖魔是什么练对? 我笑而不...
    開封第一講書人閱讀 59,869評(píng)論 1 299
  • 正文 為了忘掉前任,我火速辦了婚禮吹害,結(jié)果婚禮上螟凭,老公的妹妹穿的比我還像新娘。我一直安慰自己它呀,他們只是感情好螺男,可當(dāng)我...
    茶點(diǎn)故事閱讀 68,888評(píng)論 6 398
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著纵穿,像睡著了一般下隧。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上政恍,一...
    開封第一講書人閱讀 52,475評(píng)論 1 312
  • 那天汪拥,我揣著相機(jī)與錄音,去河邊找鬼篙耗。 笑死迫筑,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的宗弯。 我是一名探鬼主播脯燃,決...
    沈念sama閱讀 41,010評(píng)論 3 422
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼蒙保!你這毒婦竟也來了辕棚?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,924評(píng)論 0 277
  • 序言:老撾萬榮一對(duì)情侶失蹤邓厕,失蹤者是張志新(化名)和其女友劉穎逝嚎,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體详恼,經(jīng)...
    沈念sama閱讀 46,469評(píng)論 1 319
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡补君,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,552評(píng)論 3 342
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了昧互。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片挽铁。...
    茶點(diǎn)故事閱讀 40,680評(píng)論 1 353
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡伟桅,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出叽掘,到底是詐尸還是另有隱情楣铁,我是刑警寧澤,帶...
    沈念sama閱讀 36,362評(píng)論 5 351
  • 正文 年R本政府宣布更扁,位于F島的核電站盖腕,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏浓镜。R本人自食惡果不足惜赊堪,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 42,037評(píng)論 3 335
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望竖哩。 院中可真熱鬧,春花似錦脊僚、人聲如沸相叁。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,519評(píng)論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽增淹。三九已至,卻和暖如春乌企,著一層夾襖步出監(jiān)牢的瞬間虑润,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,621評(píng)論 1 274
  • 我被黑心中介騙來泰國打工加酵, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留拳喻,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 49,099評(píng)論 3 378
  • 正文 我出身青樓猪腕,卻偏偏與公主長得像冗澈,于是被迫代替她去往敵國和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子陋葡,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,691評(píng)論 2 361

推薦閱讀更多精彩內(nèi)容

  • TensorBoard TensorBoard的官網(wǎng)教程如下: https://www.tensorflow.or...
    Faded憔悴不堪閱讀 1,735評(píng)論 0 0
  • MachineLP閱讀 295評(píng)論 0 0
  • 感恩日志 感恩~今天徹底徹底徹底體會(huì)到了療愈清理的巨大效果亚亲,第一次啊,太感恩了感恩療愈清理巨大奇跡巨大奇跡巨大奇跡...
    fc8c4755608d閱讀 353評(píng)論 0 0
  • 白天和黑夜只交替無交換,無法想象對(duì)方的世界岭粤,我們?nèi)詧?jiān)持站在各自的原地惜索。 白天是不懂夜的黑,但卻離不開夜的黑绍在。 沒有...
    散文和詩閱讀 568評(píng)論 1 3
  • 所有的放下都是悄無聲息门扇,在某個(gè)時(shí)刻雹有,突然覺得很沒意思很沒勁,然后自然而然他再也不能讓自己心動(dòng)了~偶爾還是會(huì)翻下他的...
    呼叫史迪仔閱讀 161評(píng)論 0 0