TensorFlow Object Detection API教程——制作自己的数据集

本文详细介绍了使用TensorFlow目标检测API进行模型训练的过程,包括数据集准备、数据集划分、XML到CSV转换、生成TFRecords文件等关键步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

感想

  1. 前一段时间,利用tensorflow object detection跑了一些demo,然后成功的训练了自己的模型,这里我把我的方法分享出来,希望能够帮助大家。
  2. tensorflow object detection api的github 开源地址为,https://github.com/tensorflow/models,这个模块比较新,有很多都在不断更新。我这里就object detection 来分享一下

1 数据集制作

我这里利用了voc格式的数据,事先要把数据集准备好,我把xml放在了merged_xml文件夹下,把图片放在了images文件夹
我的xml文件示例为:
<?xml version="1.0" ?>
<annotation>
    <folder>VOC2007</folder>
    <filename>000009.jpg</filename>
    <size>
        <depth>3</depth>
        <width>500</width>
        <height>375</height>
    </size>
    <object>
        <name>person</name>
        <pose>Right</pose>
        <truncated>0</truncated>
        <difficult>0</difficult>
        <bndbox>
            <xmin>150</xmin>
            <ymin>141</ymin>
            <xmax>229</xmax>
            <ymax>284</ymax>
        </bndbox>
    </object>
    <object>
        <name>person</name>
        <pose>Right</pose>
        <truncated>0</truncated>
        <difficult>0</difficult>
        <bndbox>
            <xmin>285</xmin>
            <ymin>201</ymin>
            <xmax>327</xmax>
            <ymax>331</ymax>
        </bndbox>
    </object>
    <object>
        <name>person</name>
        <pose>Left</pose>
        <truncated>0</truncated>
        <difficult>0</difficult>
        <bndbox>
            <xmin>258</xmin>
            <ymin>198</ymin>
            <xmax>297</xmax>
            <ymax>329</ymax>
        </bndbox>
    </object>
</annotation>
解析也是按照这个解析的

然后利用下面的train_test_split.py把xml数据集分为了train test validation三部分,代码如下:
import os
import random
import time
import shutil

xmlfilepath=r'merged_xml'
saveBasePath=r"./annotations"

trainval_percent=0.9
train_percent=0.85
total_xml = os.listdir(xmlfilepath)
num=len(total_xml)
list=range(num)
tv=int(num*trainval_percent)
tr=int(tv*train_percent)
trainval= random.sample(list,tv)
train=random.sample(trainval,tr)

print("train and val size",tv)
print("train size",tr)
# print(total_xml[1])
start = time.time()

# print(trainval)
# print(train)

test_num=0
val_num=0
train_num=0
# for directory in ['train','test',"val"]:
#         xml_path = os.path.join(os.getcwd(), 'annotations/{}'.format(directory))
#         if(not os.path.exists(xml_path)):
#             os.mkdir(xml_path)
#         # shutil.copyfile(filePath, newfile)
#         print(xml_path)
for i  in list:
    name=total_xml[i]
            # print(i)
    if i in trainval:  #train and val set
    # ftrainval.write(name)
        if i in train:
            # ftrain.write(name)
            # print("train")
            # print(name)
            # print("train: "+name+" "+str(train_num))
            directory="train"
            train_num+=1
            xml_path = os.path.join(os.getcwd(), 'annotations/{}'.format(directory))
            if(not os.path.exists(xml_path)):
                os.mkdir(xml_path)
            filePath=os.path.join(xmlfilepath,name)
            newfile=os.path.join(saveBasePath,os.path.join(directory,name))
            shutil.copyfile(filePath, newfile)

        else:
            # fval.write(name)
            # print("val")
            # print("val: "+name+" "+str(val_num))
            directory="validation"
            xml_path = os.path.join(os.getcwd(), 'annotations/{}'.format(directory))
            if(not os.path.exists(xml_path)):
                os.mkdir(xml_path)
            val_num+=1
            filePath=os.path.join(xmlfilepath,name)
            newfile=os.path.join(saveBasePath,os.path.join(directory,name))
            shutil.copyfile(filePath, newfile)
            # print(name)
    else:  #test set
        # ftest.write(name)
        # print("test")
        # print("test: "+name+" "+str(test_num))
        directory="test"
        xml_path = os.path.join(os.getcwd(), 'annotations/{}'.format(directory))
        if(not os.path.exists(xml_path)):
            os.mkdir(xml_path)
        test_num+=1
        filePath=os.path.join(xmlfilepath,name)
        newfile=os.path.join(saveBasePath,os.path.join(directory,name))
        shutil.copyfile(filePath, newfile)
            # print(name)

# End time
end = time.time()
seconds=end-start
print("train total : "+str(train_num))
print("validation total : "+str(val_num))
print("test total : "+str(test_num))
total_num=train_num+val_num+test_num
print("total number : "+str(total_num))
print( "Time taken : {0} seconds".format(seconds))

运行完以后,annotations文件夹下就放好了分类的xml,annotations有三个目录,分别是train,test,validation。
然后把xml转换成csv文件,我的代码文件名为xml_to_csv.py,,运行代码前,需要建一个data目录,用来放生成的csv文件,然后我的代码为:
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()
        # print(root)
        print(root.find('filename').text)
        for member in root.findall('object'):
            value = (root.find('filename').text,
                     int(root.find('size')[1].text),   #width
                     int(root.find('size')[2].text),   #height
                     member[0].text,
                     int(member[4][0].text),
                     int(float(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','validation']:
        xml_path = os.path.join(os.getcwd(), 'annotations/{}'.format(directory))
    # image_path = os.path.join(os.getcwd(), 'merged_xml')
        xml_df = xml_to_csv(xml_path)
        # xml_df.to_csv('whsyxt.csv', index=None)
        xml_df.to_csv('data/whsyxt_{}_labels.csv'.format(directory), index=None)
        print('Successfully converted xml to csv.')


main()
做完这一步以后,我们就来生成tfrecords文件,我的python文件名为generate_tfrecord.py,代码为:
"""
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
from collections import namedtuple, OrderedDict

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


# TO-DO replace this with label map
def class_text_to_int(row_label):
    if row_label == 'car':
        return 1
    elif row_label == 'person':
        return 2
    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_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)
    path = os.path.join(os.getcwd(), 'images')
    examples = pd.read_csv(FLAGS.csv_input)
    grouped = split(examples, 'filename')
    num=0
    for group in grouped:
        num+=1
        tf_example = create_tf_example(group, path)
        writer.write(tf_example.SerializeToString())
        if(num%100==0):  #每完成100个转换,打印一次
            print(num)

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


if __name__ == '__main__':
    tf.app.run()
我运行的命令为:
python3 generate_tfrecord.py --csv_input=data/whsyxt_train_labels.csv --output_path=data/whsyxt_train.tfrecord
python3 generate_tfrecord.py --csv_input=data/whsyxt_test_labels.csv --output_path=data/whsyxt_test.tfrecord
python3 generate_tfrecord.py --csv_input=data/whsyxt_validation_labels.csv --output_path=data/whsyxt_validation.tfrecord
然后就获得了这三个训练需要的文件啦,训练方法请见我的下一篇博客

参考文献

[1].Introduction and Use - Tensorflow Object Detection API Tutorial.https://pythonprogramming.net/introduction-use-tensorflow-object-detection-api-tutorial/

### Head2Head 数据集介绍 Head2Head 数据集专注于头部检测及其属性识别的任务。该数据集特别适用于研究和开发涉及人员安全监控的应用程序,尤其是关注工人是否佩戴了必要的防护装备——如安全帽。 #### 数据集特点 - **多样性**: 包含来自不同环境下的图像样本,确保模型能够适应多种场景。 - **标签丰富度**: 所有图像都经过精确标注,提供了两种主要类别:`head`(未戴头盔) 和 `helmet`(已戴头盔)[^1]。 - **格式兼容性**: 标注文件已被转换成标准PASCAL VOC XML格式,便于直接应用于各种目标检测框架中进行训练。 #### 获取方式 对于希望获取此数据集的研究者或开发者来说,通常可以通过官方渠道申请访问权限或者查找是否有公开可用版本提供下载链接。然而,在当前提供的参考资料里并没有提及具体的Head2Head数据集下载地址;仅提到了其他两个相似的数据集(Helmet-Asian与Helmet-Europe),它们同样围绕着头部保护用品的存在与否展开标记工作。 #### 使用方法 为了有效地利用这类数据集开展项目,建议遵循以下指南: - **预处理阶段** - 加载并解析XML格式的标注信息。 - 对原始图片应用相应的边界框来验证标注准确性。 ```python import xml.etree.ElementTree as ET def parse_voc_xml(xml_file_path): tree = ET.parse(xml_file_path) root = tree.getroot() objects = [] for obj in root.findall('object'): label = obj.find('name').text bbox = obj.find('bndbox') xmin = int(bbox.find('xmin').text) ymin = int(bbox.find('ymin').text) xmax = int(bbox.find('xmax').text) ymax = int(bbox.find('ymax').text) objects.append({ 'label': label, 'bbox': (xmin, ymin, xmax, ymax), }) return objects ``` - **建模过程** - 利用现有的深度学习库(例如TensorFlow Object Detection API 或 PyTorch)构建适合于二分类任务的目标检测器。 - 调整超参数以优化性能指标,比如mAP(mean Average Precision).
评论 27
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

农民小飞侠

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值