生成TFrecords时出现的问题

时间:2019-11-07 16:59:58

标签: python python-3.x tensorflow pandas-groupby

我正在尝试使用tensorflow 2.0生成tfrecord文件,首先我已经正确生成了文件,但是当我尝试再次生成它们时,python控制台显示以下错误:

Traceback (most recent call last):
  File "generate_tfrecordv2.py", line 106, in <module>
    tf.compat.v1.app.run()
  File "C:\Users\LUIS\AppData\Roaming\Python\Python37\site-packages\tensorflow_c ore\python\platform\app.py", line 40, in run
    _run(main=main, argv=argv, flags_parser=_parse_flags_tolerate_undef)
  File "C:\Users\LUIS\AppData\Roaming\Python\Python37\site-packages\absl\app.py" , line 299, in run
    _run_main(main, args)
  File "C:\Users\LUIS\AppData\Roaming\Python\Python37\site-packages\absl\app.py" , line 250, in _run_main
    sys.exit(main(argv))
  File "generate_tfrecordv2.py", line 95, in main
    grouped = split(examples, 'filename')
  File "generate_tfrecordv2.py", line 45, in split
    gb = df.groupby(group)
  File "D:\ProgramData\Anaconda3\lib\site-packages\pandas\core\generic.py", line 7632, in groupby
    observed=observed, **kwargs)
  File "D:\ProgramData\Anaconda3\lib\site-packages\pandas\core\groupby\groupby.p y", line 2110, in
    groupby return klass(obj, by, **kwds)
  File "D:\ProgramData\Anaconda3\lib\site-packages\pandas\core\groupby\groupby.p y", line 360, in __init__
    mutated=self.mutated)
  File "D:\ProgramData\Anaconda3\lib\site-packages\pandas\core\groupby\grouper.p y", line 578, in _get_grouper
    raise KeyError(gpr) KeyError: 'filename'

CSV文件内容就是这样

filename;width;height;class;xmin;ymin;xmax;ymax
19219.jpg;800;600;person;49;49;377;559
19219.jpg;800;600;person;431;131;644;592

您能告诉我这是什么错误吗?我确实使用的命令是这样的:

python generate_tfrecord.py --csv_input=train_labels.csv --image_dir=train --output_path=train.record

这是我的xml示例:

<annotation>

  <folder>data_modified</folder>
  <filename>1_245</filename>
  <path>C:\material\dataset\test\1_245.jpg</path>
  <source>
    <database>Unknown</database>
  </source>
  <size>
    <width>800</width>
    <height>600</height>
    <depth>3</depth>
  </size>
  <segmented>0</segmented>
  <object>
    <name>person</name>
    <pose>Unspecified</pose>
    <truncated>0</truncated>
    <difficult>0</difficult>
    <bndbox>
      <xmin>279</xmin>
      <ymin>116</ymin>
      <xmax>423</xmax>
      <ymax>415</ymax>
    </bndbox>
  </object>
</annotation>

我确实更改了generate_tfrecords.py并重新生成xml_to_csv,但是它不起作用

"""
Usage:
  # From tensorflow/models/
  # Create train data:
  python generate_tfrecord.py --csv_input=data/train_labels.csv  --output_path=train.record
  # Create test data:
  python generate_tfrecord.py --csv_input=data/test_labels.csv  --output_path=test.record
"""
from __future__ import division
from __future__ import print_function
from __future__ import absolute_import

import os
import io
import pandas as pd
import tensorflow as tf

from PIL import Image
#from object_detection.utils import dataset_util
#lc inicio
import dataset_util
#lc fin
from collections import namedtuple, OrderedDict

#lc inicio
#flags = tf.app.flags
flags = tf.compat.v1.flags
#lc fin
flags.DEFINE_string('csv_input', '', 'Path to the CSV input')
flags.DEFINE_string('output_path', '', 'Path to output TFRecord')
flags.DEFINE_string('image_dir', '', 'Path to images')
FLAGS = flags.FLAGS


# TO-DO replace this with label map
def class_text_to_int(row_label):
    if row_label == 'person':
        return 1
    else:
        return None


def split(df, group):
    data = namedtuple('data', ['filename', 'object'])
    gb = df.groupby(group)
    return [data(filename, gb.get_group(x)) for filename, x in zip(gb.groups.keys(), gb.groups)]


def create_tf_example(group, path):
    with tf.compat.v1.gfile.GFile(os.path.join(path, '{}'.format(group.filename)), 'rb') as fid:
        encoded_jpg = fid.read()
    encoded_jpg_io = io.BytesIO(encoded_jpg)
    image = Image.open(encoded_jpg_io)
    width, height = image.size

    filename = group.filename.encode('utf8')
    image_format = b'jpg'
    xmins = []
    xmaxs = []
    ymins = []
    ymaxs = []
    classes_text = []
    classes = []

    for index, row in group.object.iterrows():
        xmins.append(row['xmin'] / width)
        xmaxs.append(row['xmax'] / width)
        ymins.append(row['ymin'] / height)
        ymaxs.append(row['ymax'] / height)
        classes_text.append(row['class'].encode('utf8'))
        classes.append(class_text_to_int(row['class']))

    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_jpg),
        '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 main(_):
    #writer = tf.python_io.TFRecordWriter(FLAGS.output_path)
    writer = tf.compat.v1.python_io.TFRecordWriter(FLAGS.output_path)
    path = os.path.join(FLAGS.image_dir)
    examples = pd.read_csv(FLAGS.csv_input)
    grouped = split(examples, 'filename')
    for group in grouped:
        tf_example = create_tf_example(group, path)
        writer.write(tf_example.SerializeToString())

    writer.close()
    output_path = os.path.join(os.getcwd(), FLAGS.output_path)
    print('Successfully created the TFRecords: {}'.format(output_path))


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

1 个答案:

答案 0 :(得分:0)

我遇到了同样的错误,因为我使用了RectLabel,并且直接从那里导出了CSV文件。

CSV必须首先具有以下行:

文件名,宽度,高度,类,xmin,ymin,xmax,ymax

annotations.csv示例:

filename,width,height,class,xmin,ymin,xmax,ymax
8.jpg,1280,720,label1,427,82,848,578
9.jpg,1280,720,label1,426,87,845,585
28.jpg,1280,720,label1,435,100,847,563
14.jpg,352,640,label2,103,215,276,398
15.jpg,352,640,label2,106,215,279,399
29.jpg,352,640,label2,61,197,270,405
17.jpg,1280,720,label1,471,178,875,671

我使该文件运行以下脚本: https://gist.github.com/iKhushPatel/ed1f837656b155d9b94d45b42e00f5e4

并遵循本教程: https://towardsdatascience.com/custom-object-detection-using-tensorflow-from-scratch-e61da2e10087