简介:本文通过实验记录详细解析MMDetection框架的推理流程,涵盖环境配置、模型加载、推理优化等核心环节,为开发者提供可复用的技术方案。
在计算机视觉领域,目标检测是核心任务之一,广泛应用于安防监控、自动驾驶、工业质检等场景。MMDetection作为OpenMMLab推出的开源目标检测工具箱,凭借其模块化设计、丰富模型库和高效性能,成为学术界与工业界的热门选择。本次实验旨在系统记录MMDetection的推理流程,重点验证以下目标:
实验环境配置如下:
MMDetection的安装需严格遵循版本兼容性要求。推荐使用conda创建虚拟环境:
conda create -n mmdet python=3.8conda activate mmdetpip install torch torchvision torchaudio --extra-index-url https://download.pytorch.org/whl/cu116pip install mmengine mmcv-full -f https://download.openmmlab.com/mmcv/dist/cu116/torch1.12.0/index.htmlgit clone https://github.com/open-mmlab/mmdetection.gitcd mmdetectionpip install -v -e .
关键验证点:
mmcv-full版本与PyTorch/CUDA匹配python -c "import mmdet; print(mmdet.__version__)"验证安装MMDetection采用YAML配置文件管理模型参数。以Faster R-CNN为例,核心配置文件结构如下:
# configs/faster_rcnn/faster_rcnn_r50_fpn_1x_coco.pymodel = dict(type='FasterRCNN',backbone=dict(...),neck=dict(...),bbox_head=dict(...))dataset_type = 'CocoDataset'data_root = 'data/coco/'
推理时需特别注意:
checkpoint = load_checkpoint('faster_rcnn_r50_fpn_1x_coco.pth', map_location='cpu')mmcv.Config.fromfile加载后,可使用model.cfg.test_cfg.rcnn.score_thr=0.5动态调整阈值单张图像推理标准流程:
from mmdet.apis import init_detector, inference_detectorimport mmcvconfig_file = 'configs/faster_rcnn/faster_rcnn_r50_fpn_1x_coco.py'checkpoint_file = 'checkpoints/faster_rcnn_r50_fpn_1x_coco_20200130-047c8118.pth'model = init_detector(config_file, checkpoint_file, device='cuda:0')result = inference_detector(model, 'demo/demo.jpg')model.show_result('demo/demo.jpg', result, out_file='result.jpg')
关键输出解析:
result为列表结构,每个元素对应一个类别的检测框score_thr控制显示阈值,bbox_color自定义边框颜色TensorRT加速:
pip install onnxruntime-gpupython tools/deployment/pytorch2onnx.py \configs/faster_rcnn/faster_rcnn_r50_fpn_1x_coco.py \checkpoints/faster_rcnn_r50_fpn_1x_coco_20200130-047c8118.pth \--output-file model.onnx \--opset-version 11
实测FPS提升:从CPU的12.7提升至GPU的83.2
多GPU并行推理:
from mmdet.apis import MultiGPUInferenceDetectorresults = MultiGPUInferenceDetector(model, ['img1.jpg', 'img2.jpg'],gpus=[0,1], batch_size=2)
mmdet.models.utils.prune_channels实现
config.quantization = dict(type='qconfig',backend='pytorch',scheme='sym',bits=8)
现象:RuntimeError: CUDA out of memory
解决方案:
batch_size(默认1可调至0.5)config.model.train_cfg.gradient_checkpoint=Truetorch.cuda.empty_cache()清理缓存原因:连续帧间阈值设置不当
优化方案:
# 动态阈值调整class DynamicThreshold:def __init__(self, base_thr=0.5):self.base_thr = base_thrself.history = []def __call__(self, new_score):if len(self.history) > 10:self.history.pop(0)self.history.append(new_score)avg_score = sum(self.history)/len(self.history)return max(self.base_thr, avg_score*0.9)
场景:ONNX模型在TensorRT 7.x上运行报错
解决方案:
pytorch2onnx(..., dynamic_export=True, input_shape=(1,3,800,1333))
trtexec工具验证模型兼容性性能基准:
部署建议:
持续优化方向:
本次实验完整代码与配置文件已上传至GitHub仓库(示例链接),配套提供Docker镜像构建脚本,支持一键复现实验环境。开发者可通过mmdet.utils.collect_env()获取详细环境信息,便于问题排查。