使用Detectron2框架训练自己的数据集

一. 引言

最近在使用detectron2框架学习一些开源算法,一上来,数据加载把我搞的有点懵,再次记录一下,如何修改代码,训练自己的数据集。

二. detectron2 框架安装

git clone https://github.com/facebookresearch/detectron2.git
python -m pip install -e detectron2

三. 数据集注册

本次我的数据是coco数据格式,所以针对coco数据修改代码,其他数据形式,也是类似。
关于数据集的注册和流程可以看看源码,以下4个函数

data/datasets/builtin.py/register_all_coco()
data/datasets/builtin_meta.py/_get_builtin_metadata()
data/datasets/builtin_meta.py/_get_coco_instances_meta() 
data/datasets/register_coco.py/register_coco_instances()

对于数据存储路径格式可以参考 detectron2/datasets/README.md 本次是coco数据格式

coco/
  annotations/
    instances_{train,val}2017.json
    person_keypoints_{train,val}2017.json
  {train,val}2017/
    # image files that are mentioned in the corresponding json

请添加图片描述

注册数据集(本次实验数据集,数据形式是coco格式存储,其余格式需要按照其他格式存储)
   vim ~/detectron2/detectron2/data/datasets/builtin.py #注册数据集
   PREDEFINED_SPLITS_COCO["coco"] = {
    "coco_2014_train": ("coco/train2014", "coco/annotations/instances_train2014.json"),
    "coco_2014_val": ("coco/val2014", "coco/annotations/instances_val2014.json"),
    "coco_2014_minival": ("coco/val2014", "coco/annotations/instances_minival2014.json"),
    "coco_2014_valminusminival": (
        "coco/val2014",
        "coco/annotations/instances_valminusminival2014.json",
    ),
    "coco_2017_train": ("coco/train2017", "coco/annotations/instances_train2017.json"),
    "coco_2017_val": ("coco/val2017", "coco/annotations/instances_val2017.json"),
    "coco_2017_test": ("coco/test2017", "coco/annotations/image_info_test2017.json"),
    "coco_2017_test-dev": ("coco/test2017", "coco/annotations/image_info_test-dev2017.json"),
    "coco_2017_val_100": ("coco/val2017", "coco/annotations/instances_val2017_100.json"),
    
    #我新注册的数据集,注意路径别写错了.
    "coco_zj_train": ('coco/annotations/images', "coco/annotations/zj_train.json"),
    "coco_zj_val": ('coco/annotations/images', 'coco/annotations/zj_val.json'),
    # "coco_zj_train" : 数据集名称
    # 'coco/annotations/images' : 图片存放路径 /coco/annotations/images #datasets前面不用说明
    # 'coco/annotations/zj_train.json' : 标注信息json路径 /coco/annotations/zj_train.json #datasets前面不用说明
}
 vim ~/detectron2/detectron2/data/datasets/builtin_meta.py #给类别定义颜色
 COCO_CATEGORIES_zj = [
    {"color": [220, 20, 60], "isthing": 1, "id": 1, "name": "person"},
    {"color": [119, 11, 32], "isthing": 1, "id": 2, "name": "bicycle"},
    {"color": [0, 0, 142], "isthing": 1, "id": 3, "name": "car"},        
]
   def _get_coco_instances_meta_zj():
    thing_ids = [k["id"] for k in COCO_CATEGORIES_zj if k["isthing"] == 1]
    thing_colors = [k["color"] for k in COCO_CATEGORIES_zj if k["isthing"] == 1]
    assert len(thing_ids) == 3, len(thing_ids)
    # Mapping from the incontiguous COCO category id to an id in [0, 79]
    thing_dataset_id_to_contiguous_id = {k: i for i, k in enumerate(thing_ids)}
    thing_classes = [k["name"] for k in COCO_CATEGORIES_zj if k["isthing"] == 1]
    '''
        _get_coco_instances_meta thing_classes: ['person', 'bicycle', 'car']
    '''    
    ret = {
        "thing_dataset_id_to_contiguous_id": thing_dataset_id_to_contiguous_id,
        "thing_classes": thing_classes,
        "thing_colors": thing_colors,
    }
    '''
        ret = {'thing_dataset_id_to_contiguous_id': {1: 0, 2: 1, 3: 2}, 'thing_classes': ['person', 'bicycle', 'car'], 'thing_colors': [[119, 11, 32], [0, 0, 142], [220, 20, 60]]}
    ''' 
    return ret
为数据集注册元数
def _get_builtin_metadata(dataset_name):
    if dataset_name == "coco":
        return _get_coco_instances_meta_zj() #修改成刚才新命名的函数名
    if dataset_name == "coco_panoptic_separated":
        return _get_coco_panoptic_separated_meta()
    elif dataset_name == "coco_panoptic_standard":
        meta = {}
        # The following metadata maps contiguous id from [0, #thing categories +
        # #stuff categories) to their names and colors. We have to replica of the
        # same name and color under "thing_*" and "stuff_*" because the current
        # visualization function in D2 handles thing and class classes differently
        # due to some heuristic used in Panoptic FPN. We keep the same naming to
        # enable reusing existing visualization functions.
        thing_classes = [k["name"] for k in COCO_CATEGORIES]
        thing_colors = [k["color"] for k in COCO_CATEGORIES]
        stuff_classes = [k["name"] for k in COCO_CATEGORIES]
        stuff_colors = [k["color"] for k in COCO_CATEGORIES]

        meta["thing_classes"] = thing_classes
        meta["thing_colors"] = thing_colors
        meta["stuff_classes"] = stuff_classes
        meta["stuff_colors"] = stuff_colors

        # Convert category id for training:
        #   category id: like semantic segmentation, it is the class id for each
        #   pixel. Since there are some classes not used in evaluation, the category
        #   id is not always contiguous and thus we have two set of category ids:
        #       - original category id: category id in the original dataset, mainly
        #           used for evaluation.
        #       - contiguous category id: [0, #classes), in order to train the linear
        #           softmax classifier.
        thing_dataset_id_to_contiguous_id = {}
        stuff_dataset_id_to_contiguous_id = {}

        for i, cat in enumerate(COCO_CATEGORIES):
            if cat["isthing"]:
                thing_dataset_id_to_contiguous_id[cat["id"]] = i
            else:
                stuff_dataset_id_to_contiguous_id[cat["id"]] = i

        meta["thing_dataset_id_to_contiguous_id"] = thing_dataset_id_to_contiguous_id
        meta["stuff_dataset_id_to_contiguous_id"] = stuff_dataset_id_to_contiguous_id

        return meta
    elif dataset_name == "coco_person":
        return {
            "thing_classes": ["person"],
            "keypoint_names": COCO_PERSON_KEYPOINT_NAMES,
            "keypoint_flip_map": COCO_PERSON_KEYPOINT_FLIP_MAP,
            "keypoint_connection_rules": KEYPOINT_CONNECTION_RULES,
        }
    elif dataset_name == "cityscapes":
        # fmt: off
        CITYSCAPES_THING_CLASSES = [
            "person", "rider", "car", "truck",
            "bus", "train", "motorcycle", "bicycle",
        ]
        CITYSCAPES_STUFF_CLASSES = [
            "road", "sidewalk", "building", "wall", "fence", "pole", "traffic light",
            "traffic sign", "vegetation", "terrain", "sky", "person", "rider", "car",
            "truck", "bus", "train", "motorcycle", "bicycle",
        ]
        # fmt: on
        return {
            "thing_classes": CITYSCAPES_THING_CLASSES,
            "stuff_classes": CITYSCAPES_STUFF_CLASSES,
        }
    raise KeyError("No built-in metadata for dataset {}".format(dataset_name))

请添加图片描述
其余配置文件yaml,参考官方案例,都是详细的说明

开始训练
python detectron2/tools/train_net.py

可以看到以下输出日志
请添加图片描述

请添加图片描述
请添加图片描述

  • 0
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
### 回答1: Detectron2是Facebook AI Research开发的目标检测框架,可以用来训练COCO数据集。 要训练COCO数据集,需要先下载COCO数据集并解压,然后使用Detectron2提供的训练脚本进行训练。 以下是一个简单的训练命令: ``` python -m detectron2.tools.train_net --config-file configs/COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_3x.yaml --num-gpus 8 --train-subdir detectron2_train_coco --eval-subdir detectron2_eval_coco --data-dir path/to/coco/dataset ``` 这个命令是训练用mask_rcnn_R_50_FPN_3x模型进行coco的实例分割任务,需要注意的是,在这个命令,需要指定coco数据集的路径,还要根据实际情况调整参数。 ### 回答2: detectron2是Facebook AI Research推出的一款基于PyTorch的目标检测框架,其具有高效、灵活、易用等优点。其支持多种主流数据集训练,其包括常用的coco数据集。 coco数据集是一个广泛应用于目标检测、实例分割和人体关键点检测等领域的经典数据集,其包含超过330,000张图像和2.5万个类别,是目前公认的最具挑战性的目标检测数据集之一。 那么,如何使用detectron2训练coco数据集呢?以下是详细步骤: 1. 数据准备 在开始训练前,需要确保已经下载了标注好的coco数据集,并将其转换成detectron2可处理的格式,包括分别生成训练集、测试集以及验证集。这部分具体操作可以参考detectron2官方文档或者在GitHub上搜索相关教程。 2. 模型选择 detectron2内置了多种主流目标检测模型,包括Faster R-CNN、Mask R-CNN等,用户可以根据实际需求选择不同的模型进行训练。 3. 模型配置 在配置文件,需要指定数据、模型、训练和测试参数等相关设置,比如coco数据集的路径、评估指标、优化器等等。需要注意的是,detectron2支持通过命令行参数进行配置调整。 4. 训练 在配置完成后,可以启动detectron2进行模型训练。在训练过程,用户可以观察模型的训练指标、损失函数、验证结果等指标,以评估模型的性能。 5. 模型评估 在训练完成后,需要对模型进行评估,以了解其在测试集上的表现。用户可以通过运行detectron2的评估脚本,获取AP、AR等评价指标,进一步优化模型性能。 总的来说,detectron2训练coco数据集并不是一项简单的任务,需要对数据集、模型、参数等都进行深入的分析和优化。而通过细致的配置和训练,可以在coco数据集上获得非常好的性能表现。 ### 回答3: Detectron2是Facebook开源的用于计算机视觉模型训练和推理的框架,提供了许多现代化的算法和工具包,支持多种数据集训练和测试。其,COCO数据集是目前计算机视觉领域最常用的基准数据集之一,它包含了超过300k个标注的图像,共有80类物体,是一个相对完备的数据集Detectron2支持使用COCO数据集训练模型,下面我们来介绍如何训练COCO数据集。 1. 数据集准备:首先需要从COCO官网下载相应的数据集,在Detectron2需要将数据集转换成特定的格式,即使用COCO API将原始数据集转换为json格式,然后再将其转换为Detectron2所需的pkl格式。 2. 配置模型和训练参数:Detectron2提供了许多现代化的模型,如Mask R-CNN、RetinaNet、Faster R-CNN等,我们需要根据需要选择合适的模型,然后设定一些超参数,如学习率、批量大小、训练轮数等。 3. 开始训练:在安装好Detectron2后,我们可以使用命令行工具来启动训练,例如:python tools/train_net.py --config-file configs/COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_1x.yaml。在训练过程Detectron2会不断地更新模型参数,直至训练完成。 4. 评估模型:Detectron2提供了一个方便的工具用于模型的评估,使用命令行工具即可完成,例如:python tools/train_net.py --config-file configs/COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_1x.yaml --eval-only MODEL.WEIGHTS /path/to/checkpoint_file。在评估过程Detectron2会将模型应用于测试集的图像,然后计算相应的指标,如平均精度等。 5. 使用模型:完成训练和评估后,我们可以使用训练好的模型来进行预测任务。Detectron2提供了许多现代化的工具和方法,使得我们可以轻松地加载模型并进行预测,例如:python demo/demo.py --config-file configs/COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_1x.yaml --input /path/to/image.jpg MODEL.WEIGHTS /path/to/checkpoint_file。 以上就是Detectron2训练COCO数据集的主要步骤,当然具体细节还需要根据实际情况进行调整。总的来说,Detectron2是一个非常优秀的框架,它提供了许多现代化的算法和工具包,使得我们可以轻松地进行计算机视觉任务的训练和测试,是一个非常值得使用的工具。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值