使用MMDetection检测器进行推断
两级检测器
在本教程中,我们使用Mask R-CNN,一个简单的两级检测器作为示例。
Mask R-CNN的高级架构如下图所示。
Mask R-CNN基于最初的Faster R-CNN添加了一个mask branch。它还使用RoIAlign,这是RoIPooling的更精确版本,用于RoI特征提取,以提高性能。更多详情可在https://arxiv.org/abs/1703.06870中找到。
首先在mmdetection目录下创建一个文件夹并且下载权重
!mkdir checkpoints
!wget -c https://download.openmmlab.com/mmdetection/v2.0/mask_rcnn/mask_rcnn_r50_caffe_fpn_mstrain-poly_3x_coco/mask_rcnn_r50_caffe_fpn_mstrain-poly_3x_coco_bbox_mAP-0.408__segm_mAP-0.37_20200504_163245-42aa3d00.pth \
-O checkpoints/mask_rcnn_r50_caffe_fpn_mstrain-poly_3x_coco_bbox_mAP-0.408__segm_mAP-0.37_20200504_163245-42aa3d00.pth
import mmcv
from mmcv.runner import load_checkpoint
from mmdet.apis import inference_detector, show_result_pyplot
from mmdet.models import build_detector
# 选择使用配置并初始化检测器
config = '../configs/mask_rcnn/mask_rcnn_r50_caffe_fpn_mstrain-poly_3x_coco.py'
# 设置要加载的权重文件
checkpoint = 'checkpoints/mask_rcnn_r50_caffe_fpn_mstrain-poly_3x_coco_bbox_mAP-0.408__segm_mAP-0.37_20200504_163245-42aa3d00.pth'
# 设置用于计算的设备cpu或gpu
device='cuda:0'
# 加载配置
config = mmcv.Config.fromfile(config)
# 将预训练设置为None,因为这里不需要预训练模型
config.model.pretrained = None
# 初始化检测器
model = build_detector(config.model)
# 加载权重
checkpoint = load_checkpoint(model, checkpoint, map_location=device)
# 设置用于推理的模型类
model.CLASSES = checkpoint['meta']['CLASSES']
# 我们需要设置模型的cfg以进行推理
model.cfg = config
# 将模型放在GPU上
model.to(device)
# 将模型转换为评估模式
model.eval()
开始推理
模型已成功创建并加载,让我们看看它有多好。我们使用MMDetection中实现的高级API推理检测器。创建此API是为了简化推理过程。代码的详细信息可在此处找到。
#Use the detector to do inference
img = 'demo.jpg'
result = inference_detector(model, img)
# 打印图片
show_result_pyplot(model, img, result, score_thr=0.3)
结果如下图所示: