如果最近安装mmdetection的小伙伴们应该都是2.15.0版本,现csdn上面所有的教程均不适用,下面按照官网的整理一下在新版本下自制数据集并训练的方法。
1.自制数据集
注:最新版本mmdetection仅支持COCO格式的数据集训练,不支持VOC格式!!!
我一开始也是用VOC数据集跑不通,后来又将VOC转成COCO格式。VOC转COCO的方法见我的另一篇文章。COCO数据集的目录如下:
mmdetection
|----data(新建)
|----coco
|----annotations
|----instances_train2017.json
|----instances_val2017.json
|----instances_test2017.json(根据自己需要)
|----train2017(存放训练集图片)
|----val2017(存放验证集图片)
|----test2017(存放测试集图片)
例如 instances_train2017.json就是训练集所对应的json文件,里面包含了训练集中所有图片的标注,在json文件中必须含有以下关键字:
{ "images": [image], "annotations": [annotation], "categories": [category] } image = { "id": int, "width": int, "height": int, "file_name": str, } annotation = { "id": int, "image_id": int, "category_id": int, "segmentation": RLE or [polygon], "area": float, "bbox": [x,y,width,height],(图片左下角的xy坐标,以及图片的宽、高) "iscrowd": 0 or 1, } categories = [{ "id": int, "name": str, "supercategory": str, }]
2.错误的训练方法
其他教程所写的方法大概为修改模型的config文件,修改num_classes,修改mmdet/datasets/coco_detection.py、mmdet/core/evaluation/class_names.py等等。这种训练方法在新版本下行不通,如果这样训练的话会出现一下两个错误:
ValueError: need at least one array to concatenate
AssertionError: The num_classes (20) in ....... of MMDataParallel does not matches the length of CLASSES 80) in RepeatDataset
上面第二个问题有教程说在mmdetection目录下运行python setup.py install 就可以解决,但我试了一下依然报错。
3.最新训练方法
参照官网的示例:
不是去修改本来的config文件,而是新建一个py文件,比如retinanet_mydataset.py,可以新建一个文件夹放在里面,比如mmdetection/configs/my_configs/retinanet_mydataset.py。
#此处写你想要的继承的config文件
_base_ = 'configs/retinanet/retinanet_r50_fpn_1x_coco.py'
# model这里不一定这样写,因为我的model报错显示没有roi_head这个属性,建议去掉model这一段,直接找到你的config文件对应的model文件,修改bbox_head中的num_classes即可。还有教程中说num_classes为类别数+1(还有背景),新版本中不需要+1。
model = dict(
roi_head=dict(
bbox_head=dict(num_classes=1),
mask_head=dict(num_classes=1)))
#调整数据集的参数
dataset_type = 'COCODataset'
classes = ('car','person','bench')
#classes = ('balloon',) <---如果只有一个类别需要加一个逗号
data = dict(
train=dict(
img_prefix='data/coco/train2017/',#修改训练集图片的路径(下同)
classes=classes,
ann_file='data/coco/annotations/instances_train2017.json'),#修改训练集json文件的路径(下同)
val=dict(
img_prefix='data/coco/val2017/',
classes=classes,
ann_file='data/coco/annotations/instances_val2017.json'),
test=dict(
img_prefix='data/coco/test2017/',
classes=classes,
ann_file='data/coco/annotations/instances_test2017.json'))
#添加一个checkpoint文件可以提升性能
load_from = 'checkpoints/retinanet_r50_fpn_1x_coco_20200130-c2398f9e.pth'
最后一行的checkpoint文件需要在mmdetection下新建一个checkpoints文件夹放在里面,可以到open-mmlab的官方github上下载自己模型对应的checkpoint文件,你需要找到你的模型文件夹点进去才能看到下载链接。
最后运行如下代码就可以开始训练啦:
python tools/train.py configs/my_configs/retinanet_mydataset.py (根据你自己的文件名修改)