首页 > 解决方案 > 尝试生成 tf_record 文件以构建自定义对象检测器时出现 NotFoundError

问题描述

我正在根据本教程构建自己的自定义对象检测器。图像已成功从 xml 转换为 csv,但我正在尝试将 tf_record 文件生成到它们保存到的同一目录中。

以下脚本用于转换为 csv 文件。在运行脚本之前,我将四张照片及其相应的 .xml 标签文件从我的训练数据集中剪切并粘贴到我的测试数据集中:

import os
import glob
import pandas as pd
import xml.etree.ElementTree as ET


def xml_to_csv(path):
    xml_list = []
    for xml_file in glob.glob(path + '/*.xml'):
        tree = ET.parse(xml_file)
        root = tree.getroot()
        for member in root.findall('object'):
            value = (root.find('filename').text,
                     int(root.find('size')[0].text),
                     int(root.find('size')[1].text),
                     member[0].text,
                     int(member[4][0].text),
                     int(member[4][1].text),
                     int(member[4][2].text),
                     int(member[4][3].text)
                     )
            xml_list.append(value)
    column_name = ['filename', 'width', 'height', 'class', 'xmin', 'ymin', 'xmax', 'ymax']
    xml_df = pd.DataFrame(xml_list, columns=column_name)
    return xml_df


def main():
    for directory in ['train','test']:
        image_path = os.path.join(os.getcwd(), 'images/{}'.format(directory))
        xml_df = xml_to_csv(image_path)
        xml_df.to_csv('data/{}_labels.csv'.format(directory), index=None)
        print('Successfully converted xml to csv.')


main()

这工作得很好,没有问题可言。

我尝试训练的图像的尺寸均为 4000 x 3000 像素,位深为 24(根据图像属性)。图像也是 .png 格式。我使用了以下修改后的代码(更正了旧版本的 tensorflow,并将代码中的所有“jpg”更改为“png”):

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

import os
import io
import pandas as pd
import tensorflow.compat.v1 as tf

from PIL import Image
from object_detection.utils import dataset_util
from collections import namedtuple, OrderedDict

flags = tf.compat.v1.flags
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 == 'weed':
        return 1
    else:
        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.gfile.GFile(os.path.join(path, '{}'.format(group.filename)), 'rb') as fid:
        encoded_png = fid.read()
    encoded_png_io = io.BytesIO(encoded_png)
    image = Image.open(encoded_png_io)
    width, height = image.size

    filename = group.filename.encode('utf8')
    image_format = b'png'
    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_png),
        '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.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()

我唯一的课程是“杂草”,并且

在 anaconda 命令提示符下运行此代码:python generate_tfrecord.py --csv_input=data/test_labels.csv --output_path=data/test.record --image_dir=images/会产生以下错误,以及名为 test.record 的空白 RECORD 文件:

2020-10-15 13:41:53.531027: W tensorflow/stream_executor/platform/default/dso_loader.cc:59] Could not load dynamic library 'cudart64_101.dll'; dlerror: cudart64_101.dll not found
2020-10-15 13:41:53.533142: I tensorflow/stream_executor/cuda/cudart_stub.cc:29] Ignore above cudart dlerror if you do not have a GPU set up on your machine.
Traceback (most recent call last):
  File "generate_tfrecord.py", line 91, in <module>
    tf.compat.v1.app.run()
  File "C:\Users\me\anaconda3\envs\object\lib\site-packages\tensorflow\python\platform\app.py", line 40, in run
    _run(main=main, argv=argv, flags_parser=_parse_flags_tolerate_undef)
  File "C:\Users\me\anaconda3\envs\object\lib\site-packages\absl\app.py", line 300, in run
    _run_main(main, args)
  File "C:\Users\me\anaconda3\envs\object\lib\site-packages\absl\app.py", line 251, in _run_main
    sys.exit(main(argv))
  File "generate_tfrecord.py", line 82, in main
    tf_example = create_tf_example(group, path)
  File "generate_tfrecord.py", line 37, in create_tf_example
    encoded_png = fid.read()
  File "C:\Users\me\anaconda3\envs\object\lib\site-packages\tensorflow\python\lib\io\file_io.py", line 116, in read
    self._preread_check()
  File "C:\Users\me\anaconda3\envs\object\lib\site-packages\tensorflow\python\lib\io\file_io.py", line 79, in _preread_check
    self.__name, 1024 * 512)
tensorflow.python.framework.errors_impl.NotFoundError: NewRandomAccessFile failed to Create/Open: images/weed8089.png : The system cannot find the file specified.
; No such file or directory

“weed8089.png”是我剪切并粘贴到“测试”数据集中的四个图像中的第一个,所以这与问题有关吗?我被这个难住了。

标签: pythontensorflow

解决方案


解决方案是包含所需图像目录的整个路径。例如,为了生成测试标签的记录文件,我运行了以下代码:

python generate_tfrecord.py --csv_input=data/train_labels.csv --output_path=data/train.record --image_dir=C:\Users\me\Documents\weeds\images\train

之后它工作得很好。

更多信息可以在这里找到。


推荐阅读