создать tfrecord для задачи обнаружения объекта - PullRequest
0 голосов
/ 03 июня 2018

Я создаю свой набор данных для задачи тонкой настройки, используя API обнаружения объектов tenorflow.

Моя структура каталогов:

train /

- imgs /

---- img1.jpg

- ann /

---- img1.csv

где CSV, по одному на изображение,label, x, y, w, h

Я использовал этот скрипт для сохранения tfrecord:

    import tensorflow as tf
    from os import listdir
    import os
    from os.path import isfile, join
    import csv
    import json

    from object_detection.utils import dataset_util


    flags = tf.app.flags
    flags.DEFINE_string('output_path', '', 'Path to output TFRecord')
    FLAGS = flags.FLAGS

    LABEL_DICT = {}
    counter = 0

    def create_tf_example(example):
      # TODO(user): Populate the following variables from your example.
      height = 404 # Image height
      width = 720 # Image width
      filename = example['path'].encode('utf-8').strip() # Filename of the image. Empty if image is not from file

      with tf.gfile.GFile(example['path'], 'rb') as fid:
        encoded_image_data = fid.read()

      image_format = 'jpeg'.encode('utf-8').strip() # b'jpeg' or b'png'

      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(int(box['x']) / width))
        xmaxs.append(float(int(box['w']) + int(box['x']) / width))
        ymins.append(float(int(box['y']) / height))
        ymaxs.append(float(int(box['h']) + int(box['y']) / height))
        classes_text.append(box['label'].encode('utf-8'))
        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_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_example

    def ex_info(img_path, ann_path):
      boxes = []
      head = ['label','x','y','w','h']
      with open(ann_path, 'r') as csvfile:
        annreader = csv.DictReader(csvfile, fieldnames=head)
        for box in annreader:
          boxes.append(box)
          LABEL_DICT[box['label']] = LABEL_DICT.get(box['label'], len(LABEL_DICT) + 1)

      ex = {
        "path" : img_path,
        "boxes" : boxes
      }

      return ex

    def main(_):
      writer = tf.python_io.TFRecordWriter(FLAGS.output_path)

      # TODO(user): Write code to read in your dataset to examples variable
      dataset_dir = "train"
      ann_dir = join(dataset_dir, "ann")
      imgs_dir = join(dataset_dir, "imgs")
      labelDest = "tfTrain/data/labels_map.pbtxt"

      imgs = [join(imgs_dir, f) for f in listdir(imgs_dir) if isfile(join(imgs_dir, f))]
      anns = [join(ann_dir, os.path.basename(im).replace("jpg","csv")) for im in imgs]

      for img,ann in zip(imgs,anns):
        example = ex_info(img,ann)
        #tf_example = create_tf_example(example)
        #writer.write(tf_example.SerializeToString())


      with open(labelDest, 'w', encoding='utf-8') as outL:
        for name,key in LABEL_DICT.items():
          outL.write("item { \n  id: " + str(key) + "\n  name: '" + name + "'\n}\n")


      writer.close()


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

, но когда я запустил скрипт поезда, я получил эту ошибку

python train.py --logtostderr --train_dir=rk.python.ops.variables) устарела и будет удалена в следующей версии.Инструкции по обновлению: переключитесь на tf.train.create_global_step Traceback (последний вызов был последним): файл «models / research / object_detection / utils / label_map_util.py", строка 135, в файле load_labelmap text_format.Merge (label_map_string, label_map) File "/home/user/anaconda3/envs/tf/lib/python3.6/site-packages/google/protobuf/text_format.py ", строка 525, в файле Merge descriptor_pool = descriptor_pool)" / home / user / anaconda3 / envs /tf / lib / python3.6 / site-packages / google / protobuf / text_format.py ", строка 579, в MergeLines возвращает parser.MergeLines (строки, сообщение) Файл" / home / user / anaconda3 / envs / tf / lib /python3.6 / site-packages / google / protobuf / text_format.py ", строка 612, в файле MergeLines self._ParseOrMerge (lines, message) Файл" /home/user/anaconda3/envs/tf/lib/python3.6/site-packages / google / protobuf / text_format.py ", строка 627, в файле _ParseOrMerge self._MergeField (tokenizer, message)" /home/user/anaconda3/envs/tf/lib/python3.6/site-packages/google/protobuf / text_format.py ", строка 727, в слиянии _MergeField (дляkenizer, message, field) Файл "/home/user/anaconda3/envs/tf/lib/python3.6/site-packages/google/protobuf/text_format.py", строка 815, в _MergeMessageField self._MergeField (токенайзер, sub_message) Файл "/home/user/anaconda3/envs/tf/lib/python3.6/site-packages/google/protobuf/text_format.py", строка 695, в _MergeField (message_descriptor.full_name, name)) google.protobuf.text_format.ParseError: 23:20: Тип сообщения «object_detection.protos.StringIntLabelMapItem» не имеет поля с именем «s».

Во время обработки вышеуказанного исключения произошло другое исключение:

    Traceback (most recent call last):
      File "train.py", line 184, in <module>
        tf.app.run()
      File "/home/user/anaconda3/envs/tf/lib/python3.6/site-packages/tensorflow/python/platform/app.py",

строка 126, в прогоне _sys.exit (main (argv)) Файл "train.py", строка 180, в основном graph_hook_fn = graph_rewriter_fn) Файл "models / research / object_detection / trainer.py", строка 264, в train train_config.prefetch_queue_capacity, data_augmentation_options) Файл "models / research / object_detection / trainer.py", строка 59, в файле create_input_queue tenor_dict = create_tensor_dict_fn () Файл "train.py", строка 121, в наборе данных get_nextder.build (config)). get_next () Файл «models / research / object_detection / builders / dataset_builder.py», строка 155, в файле build_map_proto_file = label_map_proto_file) Файл «models / research / object_detection / data_decoders / tf_example_decoder.py»строка 245, в init use_display_name) Файл "models / research / object_detection / utils / label_map_util.py", строка 152, в файле get_label_map_dict label_map = load_labelmap (label_map_path) file "models / research / object_detection_ utils / label_map.py ", строка 137, в load_labelmap label_map.ParseFromString (label_map_string) TypeError: требуется объект, похожий на байты, а не 'str'

Я не понимаю, в чем проблема.В записи?в файле label.pbtxt?или в конфигурационном файле?

1 Ответ

0 голосов
/ 04 июня 2018

Хорошо, я только что решил отладку тензорного потока.Законченные мои метки, хотя и в формате utf-8, не легко читаются тензорным потоком из-за некоторых странных символов, таких как & à à.Извлечение из CSV позволяет поезду начать

...