一、主要内容
以 OPIXray 数据集(X光目标检测数据集)为例,在 MMdetection 框架中添加新的数据集。
二、添加步骤
1、注册新类
(1)在 mmdet/datasets 目录下创建 opixray.py 文件,创建新类 OPIXrayDataset,文件内容如下(继承 CocoDataset 类,将其中的类别属性进行修改)
from .builder import DATASETS
from .coco import CocoDataset
@DATASETS.register_module()
class OPIXrayDataset(CocoDataset):
CLASSES = ("Folding_Knife", "Straight_Knife", "Scissor", "Utility_Knife", "Multi-tool_Knife")
(2)在 mmdet/datasets/__init__.py 文件中,首先导入新创建的文件中的新类
from .opixray import OPIXrayDataset
之后再在__ all __ 列表中加入新的类名 ‘OPIXrayDataset’(如下,加到了列表的最后面)
__all__ = [
'CustomDataset', 'XMLDataset', 'CocoDataset', 'DeepFashionDataset',
'VOCDataset', 'CityscapesDataset', 'LVISDataset', 'LVISV05Dataset',
'LVISV1Dataset', 'GroupSampler', 'DistributedGroupSampler',
'DistributedSampler', 'build_dataloader', 'ConcatDataset', 'RepeatDataset',
'ClassBalancedDataset', 'WIDERFaceDataset', 'DATASETS', 'PIPELINES',
'build_dataset', 'replace_ImageToTensor', 'get_loading_pipeline',
'NumClassCheckHook', 'CocoPanopticDataset', 'MultiImageMixDataset',
'OpenImagesDataset', 'OpenImagesChallengeDataset',
'OPIXrayDataset'
]
2、数据集配置文件的编写
在 configs/_base_/datasets 目录下创建文件 opixray_detection.py,文件内容如下
dataset_type = 'OPIXrayDataset' # 新类名
data_root = 'data/OPIXray/' # 数据集位置(COCO格式)
img_norm_cfg = dict(
mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True)
img_scale = (1225, 954) # 数据集中图片的输入大小
train_pipeline = [
dict(type='LoadImageFromFile'),
dict(type='LoadAnnotations', with_bbox=True),
dict(type='Resize', img_scale=img_scale, keep_ratio=True),
dict(type='RandomFlip', flip_ratio=0.5),
dict(type='Normalize', **img_norm_cfg),
dict(type='Pad', size_divisor=32),
dict(type='DefaultFormatBundle'),
dict(type='Collect', keys=['img', 'gt_bboxes', 'gt_labels']),
]
test_pipeline = [
dict(type='LoadImageFromFile'),
dict(
type='MultiScaleFlipAug',
img_scale=img_scale,
flip=False,
transforms=[
dict(type='Resize', keep_ratio=True),
dict(type='RandomFlip'),
dict(type='Normalize', **img_norm_cfg),
dict(type='Pad', size_divisor=32),
dict(type='ImageToTensor', keys=['img']),
dict(type='Collect', keys=['img']),
])
]
data = dict(
samples_per_gpu=2,
workers_per_gpu=2,
train=dict(
type=dataset_type,
ann_file=data_root + 'annotations/train_annotation.json', # 训练集的配置文件位置
img_prefix=data_root + 'train/train_image', # 训练集的图片位置
pipeline=train_pipeline),
val=dict(
type=dataset_type,
ann_file=data_root + 'annotations/test_annotation.json',
img_prefix=data_root + 'test/test_image',
pipeline=test_pipeline),
test=dict(
type=dataset_type,
ann_file=data_root + 'annotations/test_annotation.json',
img_prefix=data_root + 'test/test_image',
pipeline=test_pipeline))
evaluation = dict(interval=1, metric='bbox')
3、模型配置文件的编写
在 configs/atss 目录下创建文件 atss_r50_fpn_opixray.py,文件内容如下(复制 configs/atss/atss_r50_fpn_1x_coco.py 文件内容,将类别数进行修改)
模型以 ATSS 为例
_base_ = [
'../_base_/datasets/opixray_detection.py', # 引用步骤2创建的数据集配置文件
'../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py'
]
model = dict(
type='ATSS',
backbone=dict(
type='ResNet',
depth=50,
num_stages=4,
out_indices=(0, 1, 2, 3),
frozen_stages=1,
norm_cfg=dict(type='BN', requires_grad=True),
norm_eval=True,
style='pytorch',
init_cfg=dict(type='Pretrained', checkpoint='torchvision://resnet50')),
neck=dict(
type='FPN',
in_channels=[256, 512, 1024, 2048],
out_channels=256,
start_level=1,
add_extra_convs='on_output',
num_outs=5),
bbox_head=dict(
type='ATSSHead',
num_classes=5, # 类别数修改
in_channels=256,
stacked_convs=4,
feat_channels=256,
anchor_generator=dict(
type='AnchorGenerator',
ratios=[1.0],
octave_base_scale=8,
scales_per_octave=1,
strides=[8, 16, 32, 64, 128]),
bbox_coder=dict(
type='DeltaXYWHBBoxCoder',
target_means=[.0, .0, .0, .0],
target_stds=[0.1, 0.1, 0.2, 0.2]),
loss_cls=dict(
type='FocalLoss',
use_sigmoid=True,
gamma=2.0,
alpha=0.25,
loss_weight=1.0),
loss_bbox=dict(type='GIoULoss', loss_weight=2.0),
loss_centerness=dict(
type='CrossEntropyLoss', use_sigmoid=True, loss_weight=1.0)),
# training and testing settings
train_cfg=dict(
assigner=dict(type='ATSSAssigner', topk=9),
allowed_border=-1,
pos_weight=-1,
debug=False),
test_cfg=dict(
nms_pre=1000,
min_bbox_size=0,
score_thr=0.05,
nms=dict(type='nms', iou_threshold=0.6),
max_per_img=100))
# optimizer
optimizer = dict(type='SGD', lr=0.01, momentum=0.9, weight_decay=0.0001)
4、模型配置文件的使用
训练时,常用的配置文件参数修改
_base_ = '../../../../configs/atss/atss_r50_fpn_1x_coco_opixray.py' # 引用步骤3中创建的模型配置文件(具体需要进行修改)
data = dict(samples_per_gpu=2, workers_per_gpu=2) # 显卡配置
evaluation = dict(interval=1, metric='bbox')
optimizer = dict(type='SGD', lr=0.01, momentum=0.9, weight_decay=0.0001) # 学习率调整
# 训练策略
lr_config = dict(
policy='step',
warmup='linear',
warmup_iters=500,
warmup_ratio=0.001,
step=[8, 10, 12])
runner = dict(type='EpochBasedRunner', max_epochs=12) # 训练轮次
log_config = dict(interval=50, hooks=[dict(type='TextLoggerHook')])
# load_from = ''
# resume_from = ''
fp16 = dict(loss_scale='dynamic') # 混合精度训练
work_dir = '' # 模型、日志保存位置