openmmlab实战营第五课 MMDetection 代码教学

MMDetection 可以做什么

  • MMDetection 提供400 余个性能优良的预训练模型,开箱即用,几行Python API 即可调用强大的检测能力

  • MMDetection 涵盖60 余个目标检测算法,并提供方便易用的工具,经过简单的配置文件改写和调参就可以训练自己的目标检测模型

MMDetection
任务支持 覆盖广泛 算法丰富 算法丰富
目标检测 440+ 个预训练模型 两阶段检测器 训练工具
目标检测 60+ 篇论文复现 一阶段检测器 测试工具
全景分割 常用学术数据集 级联检测器 推理 API
无锚框检测器
Transformer

OpenMMLab 项目中的重要概念——配置文件

深度学习模型的训练涉及几个方面:
− 模型结构模型有几层、每层多少通道数等等
− 数据集用什么数据训练模型:数据集划分、数据文件路径、数据增强策略等等
− 训练策略梯度下降算法、学习率参数、batch_size、训练总轮次、学习率变化策略等等
− 运行时GPU、分布式环境配置等等
− 一些辅助功能如打印日志、定时保存checkpoint等等

在OpenMMLab 项目中,所有这些项目都涵盖在一个配置文件中,一个配置文件定义了一个完整的训练过程
− model 字段定义模型
− data 字段定义数据
− optimizer、lr_config 等字段定义训练策略
− load_from 字段定义与训练模型的参数文件


 
flowchart LR;
subgraph 配置文件
模型结构
数据集
数据处理策略
学习率策略
优化器策略
运行环境配置
end


subgraph 模型库
预训练模型
end

subgraph 内部模块
A[模型构建]
B[数据加载器构建]
C[优化器构建]
D[Runner]
A-->D
B-->D
C-->D
end

subgraph 工具
训练工具
测试工具
推理工具
end

subgraph 数据文件
COCO
自定义数据
推理工具
S[Pascal VOC]
Cityscapes
end
内部模块 -->工具
数据文件-->内部模块
模型库-->内部模块
配置文件-->内部模块

安装环境

1
2
3
pip install openmim
mim install mmcv-full==1.3.17
mim install mmdet==2.22.0

验证是否成功 参考官方的文档

1
2
3
4
5
6
7
8
9
10
11
12
import torch
from mmdet.apis import init_detector, inference_detector,show_result_pyplot
config_file = '放faster_rcnn_r50_fpn_1x_coco.py的地址'
# 从 model zoo 下载 checkpoint 并放在 `checkpoints/` 文件下
# 网址为: http://download.openmmlab.com/mmdetection/v2.0/faster_rcnn/faster_rcnn_r50_fpn_1x_coco/faster_rcnn_r50_fpn_1x_coco_20200130-047c8118.pth
checkpoint_file = '放faster_rcnn_r50_fpn_1x_coco_20200130-047c8118.pth的地址'
device = 'cuda:0'
# 初始化检测器
model = init_detector(config_file, checkpoint_file, device=device)
# 推理演示图像
result=inference_detector(model, '图像地址可以用demo里的图')
show_result_pyplot(model,'图像地址可以用demo里的图',result) #展示图片

如何把一个新的数据集转化为coco数据集训练 以这次课程的balloon数据集为例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52

import os.path as osp
import mmcv

def convert_balloon_to_coco(ann_file, out_file, image_prefix):
data_infos = mmcv.load(ann_file)

annotations = []
images = []
obj_count = 0
for idx, v in enumerate(mmcv.track_iter_progress(data_infos.values())):
filename = v['filename']
img_path = osp.join(image_prefix, filename)
height, width = mmcv.imread(img_path).shape[:2]

images.append(dict(
id=idx,
file_name=filename,
height=height,
width=width))

bboxes = []
labels = []
masks = []
for _, obj in v['regions'].items():
assert not obj['region_attributes']
obj = obj['shape_attributes']
px = obj['all_points_x']
py = obj['all_points_y']
poly = [(x + 0.5, y + 0.5) for x, y in zip(px, py)]
poly = [p for x in poly for p in x]

x_min, y_min, x_max, y_max = (
min(px), min(py), max(px), max(py))


data_anno = dict(
image_id=idx,
id=obj_count,
category_id=0,
bbox=[x_min, y_min, x_max - x_min, y_max - y_min],
area=(x_max - x_min) * (y_max - y_min),
segmentation=[poly],
iscrowd=0)
annotations.append(data_anno)
obj_count += 1

coco_format_json = dict(
images=images,
annotations=annotations,
categories=[{'id':0, 'name': 'balloon'}])
mmcv.dump(coco_format_json, out_file)

下载已经有的模型 可以用 mim search mmdet --model "模型id"查有的模型

1
mim download mmdet --config mask_rcnn_r50_fpn_2x_coco --desk . 

准备一个配置文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
 这个新的配置文件继承自一个原始配置文件,只需要突出必要的修改部分即可
_base_ = 'mask_rcnn_r50_fpn_2x_coco.py'
# 我们需要对头中的类别数量进行修改来匹配数据集的标注
model = dict(
roi_head=dict(
bbox_head=dict(num_classes=1),
mask_head=dict(num_classes=1)))

dataset_type = 'CocoDataset'
classes = ('balloon',)
data = dict(
train=dict(
img_prefix='/input0/balloon/train/',
classes=classes,
ann_file='/input0/balloon/train/via_region_data2.json'),
val=dict(
img_prefix='/input0/balloon/val/',
classes=classes,
ann_file='/input0/balloon/val/via_region_data2.json'),
test=dict(
img_prefix='/input0/balloon/val/',
classes=classes,
ann_file='/input0/balloon/val/via_region_data2.json'))
#model= dict(bbox_head=dict(num_classes=1))

# 我们可以使用预训练的 Mask R-CNN 来获取更好的性能
load_from ='mask_rcnn_r50_fpn_2x_coco_bbox_mAP-0.392__segm_mAP-0.354_20200505_003907-3e542a40.pth'

训练模型

1
mim train mmdet balloon.py

测试模型

1
mim test mmdet balloon.py --checkpoint work_dirs/balloon/latest.pth --show-dir work_dirs/balloon