You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TensorFlow目标检测自定义数据集生成报错:NotFoundError

Fixing NotFoundError When Creating TFRecord for TensorFlow Object Detection

看起来你遇到的这个NotFoundError其实不是图片路径的问题,而是TFRecord输出路径不存在导致的——错误栈里明确显示报错发生在tf.python_io.TFRecordWriter(FLAGS.output_path)这一行,代码还没执行到读取图片的步骤呢。咱们一步步来解决:

第一步:解决TFRecord输出路径问题

当你运行脚本时,要么没指定有效的输出路径,要么路径对应的目录不存在,TensorFlow就会抛出这个错误。你可以这么处理:

1. 自动创建输出目录

在main函数开头添加目录创建逻辑,避免手动创建的麻烦:

import os
# 在main函数最开始加入这段
if FLAGS.output_path:
    output_dir = os.path.dirname(FLAGS.output_path)
    if output_dir and not os.path.exists(output_dir):
        os.makedirs(output_dir)

2. 运行脚本时明确指定输出路径

不要让output_path留空,执行脚本时通过参数指定具体路径,比如:

python your_script.py --output_path ./tf_records/train.record

3. 优先使用绝对路径

相对路径容易因为工作目录不一致出问题,建议直接写绝对路径,比如:

flags.DEFINE_string('output_path', '/home/your_username/tf_records/train.record', 'Path to output TFRecord')

第二步:处理后续的图片路径与数据加载问题

等输出路径的问题解决后,你会遇到LOAD(file_loc)的未实现问题,这里给你一个适配常见标注格式的示例(假设每个图片对应一个同名txt标注文件,格式为xmin ymin xmax ymax class_name):

示例:实现LOAD函数读取图片与标注

def LOAD(image_dir):
    data_list = []
    # 遍历目录下的所有图片文件
    for filename in os.listdir(image_dir):
        if filename.lower().endswith(('.jpg', '.jpeg', '.png')):
            img_path = os.path.join(image_dir, filename)
            # 对应标注文件路径(假设和图片同名,后缀为txt)
            label_path = os.path.splitext(img_path)[0] + '.txt'
            
            if os.path.exists(label_path):
                with open(label_path, 'r') as f:
                    # 读取标注信息(可根据你的实际标注格式调整)
                    xmin, ymin, xmax, ymax, class_name = f.readline().strip().split()
                    xmin, ymin, xmax, ymax = float(xmin), float(ymin), float(xmax), float(ymax)
                    
                    data_list.append({
                        'img_path': img_path,
                        'filename': filename,
                        'bbox': (xmin, ymin, xmax, ymax),
                        'class_name': class_name,
                        'class_id': 1  # 对应你定义的classes列表中的id
                    })
    return data_list

完善create_tf_example函数

还要把函数里的TODO部分补全,读取真实的图片数据和尺寸:

def create_tf_example(label_and_data_info):
    # 读取图片字节数据
    with tf.gfile.GFile(label_and_data_info['img_path'], 'rb') as fid:
        encoded_image_data = fid.read()
    
    # 获取图片真实尺寸
    img = Image.open(label_and_data_info['img_path'])
    width, height = img.size
    
    # 格式化各项信息
    filename = label_and_data_info['filename'].encode('utf8')
    # 归一化 bounding box 坐标(转为0-1之间的数值)
    xmin = label_and_data_info['bbox'][0] / width
    xmax = label_and_data_info['bbox'][2] / width
    ymin = label_and_data_info['bbox'][1] / height
    ymax = label_and_data_info['bbox'][3] / height
    
    image_format = b'jpg' if label_and_data_info['filename'].lower().endswith(('.jpg', '.jpeg')) else b'png'
    classes_text = [label_and_data_info['class_name'].encode('utf8')]
    classes = [label_and_data_info['class_id']]

    tf_label_and_data = 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([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),
    }))
    return tf_label_and_data

最后:验证路径正确性

可以在代码里添加路径打印,确认路径是否正确:

print("Output path (absolute):", os.path.abspath(FLAGS.output_path))
print("Image directory (absolute):", os.path.abspath(file_loc))

这样应该就能解决当前的NotFoundError,以及后续可能遇到的图片加载和数据格式化问题了。

内容的提问来源于stack exchange,提问作者Racoon85

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 08:43:40