Windows下MMDetection从安装到跑通第一个目标检测Demo含权重文件下载与路径配置避坑在Windows系统上搭建深度学习环境总是充满挑战尤其是当官方文档默认用户使用Linux时。作为国内最流行的开源目标检测框架之一MMDetection的强大功能吸引着无数开发者但Windows用户在安装过程中往往会遇到各种特色问题——从路径斜杠方向到CUDA版本冲突从权重文件下载缓慢到配置文件路径错误。本文将手把手带你避开这些坑用最直接的方式在原生Windows环境非WSL中完成MMDetection的完整部署并运行第一个目标检测Demo。1. 环境准备打造专属Python沙盒1.1 Conda环境配置Windows下的Python环境管理推荐使用Miniconda3比Anaconda更轻量最新版本可从清华镜像站下载。安装时务必勾选Add to PATH选项这是后续在普通CMD中使用conda命令的关键。# 创建专用于MMDetection的Python环境指定3.8版本更稳定 conda create -n mmdet python3.8 -y conda activate mmdet注意如果后续步骤出现DLL加载错误很可能是环境变量问题。可尝试在Anaconda Prompt中执行conda init然后重新打开终端。1.2 PyTorch与CUDA的版本舞蹈MMDetection对PyTorch和CUDA版本有严格限制以下是经过验证的组合方案组件推荐版本必须匹配项PyTorch2.1.0CUDA运行时版本torchvision0.16.0PyTorch主版本CUDA11.8显卡驱动版本≥522.06安装命令使用国内镜像加速pip install torch2.1.0 torchvision0.16.0 torchaudio2.1.0 --index-url https://mirrors.aliyun.com/pytorch-wheels/cu118/验证安装import torch print(torch.__version__) # 应输出2.1.0 print(torch.cuda.is_available()) # 应输出True2. MMDetection生态链安装指南2.1 核心组件精准安装OpenMMLab系列包的版本必须严格对齐以下是经过测试的黄金组合# 先安装包管理工具MIM pip install -U openmim # 按顺序安装核心组件注意版本号 mim install mmengine0.10.3 mim install mmcv2.1.0 -f https://download.openmmlab.com/mmcv/dist/cu118/torch2.1/index.html mim install mmdet3.3.0常见安装问题排查报错Could not build wheels for mmcv检查VS Build Tools是否安装需要C14支持报错DLL load failed大概率是PyTorch与MMCV版本不匹配使用pip list核对版本2.2 源码获取与路径处理从GitHub克隆MMDetection仓库时Windows用户需特别注意# 推荐使用SSH方式克隆需先配置Git SSH Key git clone gitgithub.com:open-mmlab/mmdetection.git cd mmdetection重要Windows路径建议全部使用原始字符串表示法例如config_file rD:\mmdetection\configs\faster_rcnn\faster-rcnn_r50_fpn_1x_coco.py3. 预训练模型获取与配置技巧3.1 权重文件高速下载官方模型库Model Zoo的权重文件通常存放在海外服务器国内用户可通过以下方式加速使用开源镜像站替换URL原始URLhttps://download.openmmlab.com/mmdetection/v2.0/faster_rcnn/faster_rcnn_r50_fpn_1x_coco/faster_rcnn_r50_fpn_1x_coco_20200130-047c8118.pth 替换为https://openmmlab.oss-cn-hangzhou.aliyuncs.com/mmdetection/v2.0/faster_rcnn/faster_rcnn_r50_fpn_1x_coco/faster_rcnn_r50_fpn_1x_coco_20200130-047c8118.pth使用迅雷等下载工具接管浏览器下载任务3.2 模型文件目录规范建议建立如下目录结构避免路径混乱mmdetection/ ├── configs/ ├── checkpoints/ # 存放所有.pth权重文件 ├── demo/ │ ├── demo.jpg # 测试图片 │ └── result.png # 输出结果 └── outputs/ # 可视化结果保存目录4. 第一个目标检测Demo实战4.1 测试脚本深度适配以下是针对Windows系统优化过的完整测试脚本保存为demo.pyimport mmcv from mmdet.apis import init_detector, inference_detector from mmdet.registry import VISUALIZERS # 使用原始字符串避免转义问题 config rconfigs/faster_rcnn/faster-rcnn_r50_fpn_1x_coco.py checkpoint rcheckpoints/faster_rcnn_r50_fpn_1x_coco_20200130-047c8118.pth img_path rdemo/demo.jpg # 初始化模型自动切换到GPU model init_detector(config, checkpoint, devicecuda:0) # 执行推理 result inference_detector(model, img_path) # 可视化设置 visualizer VISUALIZERS.build(model.cfg.visualizer) visualizer.dataset_meta model.dataset_meta # 保存检测结果 image mmcv.imread(img_path) visualizer.add_datasample( result, image, data_sampleresult, draw_gtFalse, showFalse, # Windows下建议关闭直接显示 out_fileoutputs/result.jpg )4.2 典型报错解决方案问题1RuntimeError: Couldnt load custom C ops原因MMCV编译版本与PyTorch不匹配解决重新安装匹配版本的MMCVmim uninstall mmcv mim install mmcv2.1.0 -f https://download.openmmlab.com/mmcv/dist/cu118/torch2.1/index.html问题2FileNotFoundError配置文件路径错误原因Windows路径分隔符问题解决使用os.path模块处理路径import os config os.path.join(configs, faster_rcnn, faster-rcnn_r50_fpn_1x_coco.py)问题3CUDA out of memory修改配置文件的test_dataloader部分test_dataloader dict( batch_size1, # 改为1 ... )5. 效率优化与进阶技巧5.1 开启DNN加速在configs/_base_/datasets/coco_detection.py中添加model dict( ... dcndict(typeDCNv2, deform_groups1, fallback_on_strideFalse), stage_with_dcn(False, True, True, True))5.2 多GPU训练配置修改tools/train.py启动参数set CUDA_VISIBLE_DEVICES0,1 # 使用前两块GPU python -m torch.distributed.launch --nproc_per_node2 tools/train.py configs/faster_rcnn/faster-rcnn_r50_fpn_1x_coco.py5.3 模型转换与部署将PyTorch模型转换为ONNX格式from mmdet.apis import export_model config_file configs/faster_rcnn/faster-rcnn_r50_fpn_1x_coco.py checkpoint_file checkpoints/faster_rcnn_r50_fpn_1x_coco_20200130-047c8118.pth export_model(config_file, checkpoint_file, faster_rcnn.onnx)6. 可视化增强与结果分析6.1 检测结果二次加工在输出图像上添加自定义信息from PIL import Image, ImageDraw result_img Image.open(outputs/result.jpg) draw ImageDraw.Draw(result_img) # 在左上角添加模型信息 draw.text((10, 10), fModel: Faster R-CNN\nConfidence: {result[0][0][4]:.2f}, fill(255, 0, 0)) result_img.save(outputs/result_with_info.jpg)6.2 性能评估脚本创建eval.py进行定量评估from mmdet.apis import init_detector, inference_detector import time config configs/faster_rcnn/faster-rcnn_r50_fpn_1x_coco.py checkpoint checkpoints/faster_rcnn_r50_fpn_1x_coco_20200130-047c8118.pth model init_detector(config, checkpoint, devicecuda:0) # 预热GPU for _ in range(10): _ inference_detector(model, demo/demo.jpg) # 正式测试 start time.time() for _ in range(100): result inference_detector(model, demo/demo.jpg) elapsed time.time() - start print(fAverage inference time: {elapsed/100:.4f}s)
Windows下MMDetection从安装到跑通第一个目标检测Demo(含权重文件下载与路径配置避坑)
Windows下MMDetection从安装到跑通第一个目标检测Demo含权重文件下载与路径配置避坑在Windows系统上搭建深度学习环境总是充满挑战尤其是当官方文档默认用户使用Linux时。作为国内最流行的开源目标检测框架之一MMDetection的强大功能吸引着无数开发者但Windows用户在安装过程中往往会遇到各种特色问题——从路径斜杠方向到CUDA版本冲突从权重文件下载缓慢到配置文件路径错误。本文将手把手带你避开这些坑用最直接的方式在原生Windows环境非WSL中完成MMDetection的完整部署并运行第一个目标检测Demo。1. 环境准备打造专属Python沙盒1.1 Conda环境配置Windows下的Python环境管理推荐使用Miniconda3比Anaconda更轻量最新版本可从清华镜像站下载。安装时务必勾选Add to PATH选项这是后续在普通CMD中使用conda命令的关键。# 创建专用于MMDetection的Python环境指定3.8版本更稳定 conda create -n mmdet python3.8 -y conda activate mmdet注意如果后续步骤出现DLL加载错误很可能是环境变量问题。可尝试在Anaconda Prompt中执行conda init然后重新打开终端。1.2 PyTorch与CUDA的版本舞蹈MMDetection对PyTorch和CUDA版本有严格限制以下是经过验证的组合方案组件推荐版本必须匹配项PyTorch2.1.0CUDA运行时版本torchvision0.16.0PyTorch主版本CUDA11.8显卡驱动版本≥522.06安装命令使用国内镜像加速pip install torch2.1.0 torchvision0.16.0 torchaudio2.1.0 --index-url https://mirrors.aliyun.com/pytorch-wheels/cu118/验证安装import torch print(torch.__version__) # 应输出2.1.0 print(torch.cuda.is_available()) # 应输出True2. MMDetection生态链安装指南2.1 核心组件精准安装OpenMMLab系列包的版本必须严格对齐以下是经过测试的黄金组合# 先安装包管理工具MIM pip install -U openmim # 按顺序安装核心组件注意版本号 mim install mmengine0.10.3 mim install mmcv2.1.0 -f https://download.openmmlab.com/mmcv/dist/cu118/torch2.1/index.html mim install mmdet3.3.0常见安装问题排查报错Could not build wheels for mmcv检查VS Build Tools是否安装需要C14支持报错DLL load failed大概率是PyTorch与MMCV版本不匹配使用pip list核对版本2.2 源码获取与路径处理从GitHub克隆MMDetection仓库时Windows用户需特别注意# 推荐使用SSH方式克隆需先配置Git SSH Key git clone gitgithub.com:open-mmlab/mmdetection.git cd mmdetection重要Windows路径建议全部使用原始字符串表示法例如config_file rD:\mmdetection\configs\faster_rcnn\faster-rcnn_r50_fpn_1x_coco.py3. 预训练模型获取与配置技巧3.1 权重文件高速下载官方模型库Model Zoo的权重文件通常存放在海外服务器国内用户可通过以下方式加速使用开源镜像站替换URL原始URLhttps://download.openmmlab.com/mmdetection/v2.0/faster_rcnn/faster_rcnn_r50_fpn_1x_coco/faster_rcnn_r50_fpn_1x_coco_20200130-047c8118.pth 替换为https://openmmlab.oss-cn-hangzhou.aliyuncs.com/mmdetection/v2.0/faster_rcnn/faster_rcnn_r50_fpn_1x_coco/faster_rcnn_r50_fpn_1x_coco_20200130-047c8118.pth使用迅雷等下载工具接管浏览器下载任务3.2 模型文件目录规范建议建立如下目录结构避免路径混乱mmdetection/ ├── configs/ ├── checkpoints/ # 存放所有.pth权重文件 ├── demo/ │ ├── demo.jpg # 测试图片 │ └── result.png # 输出结果 └── outputs/ # 可视化结果保存目录4. 第一个目标检测Demo实战4.1 测试脚本深度适配以下是针对Windows系统优化过的完整测试脚本保存为demo.pyimport mmcv from mmdet.apis import init_detector, inference_detector from mmdet.registry import VISUALIZERS # 使用原始字符串避免转义问题 config rconfigs/faster_rcnn/faster-rcnn_r50_fpn_1x_coco.py checkpoint rcheckpoints/faster_rcnn_r50_fpn_1x_coco_20200130-047c8118.pth img_path rdemo/demo.jpg # 初始化模型自动切换到GPU model init_detector(config, checkpoint, devicecuda:0) # 执行推理 result inference_detector(model, img_path) # 可视化设置 visualizer VISUALIZERS.build(model.cfg.visualizer) visualizer.dataset_meta model.dataset_meta # 保存检测结果 image mmcv.imread(img_path) visualizer.add_datasample( result, image, data_sampleresult, draw_gtFalse, showFalse, # Windows下建议关闭直接显示 out_fileoutputs/result.jpg )4.2 典型报错解决方案问题1RuntimeError: Couldnt load custom C ops原因MMCV编译版本与PyTorch不匹配解决重新安装匹配版本的MMCVmim uninstall mmcv mim install mmcv2.1.0 -f https://download.openmmlab.com/mmcv/dist/cu118/torch2.1/index.html问题2FileNotFoundError配置文件路径错误原因Windows路径分隔符问题解决使用os.path模块处理路径import os config os.path.join(configs, faster_rcnn, faster-rcnn_r50_fpn_1x_coco.py)问题3CUDA out of memory修改配置文件的test_dataloader部分test_dataloader dict( batch_size1, # 改为1 ... )5. 效率优化与进阶技巧5.1 开启DNN加速在configs/_base_/datasets/coco_detection.py中添加model dict( ... dcndict(typeDCNv2, deform_groups1, fallback_on_strideFalse), stage_with_dcn(False, True, True, True))5.2 多GPU训练配置修改tools/train.py启动参数set CUDA_VISIBLE_DEVICES0,1 # 使用前两块GPU python -m torch.distributed.launch --nproc_per_node2 tools/train.py configs/faster_rcnn/faster-rcnn_r50_fpn_1x_coco.py5.3 模型转换与部署将PyTorch模型转换为ONNX格式from mmdet.apis import export_model config_file configs/faster_rcnn/faster-rcnn_r50_fpn_1x_coco.py checkpoint_file checkpoints/faster_rcnn_r50_fpn_1x_coco_20200130-047c8118.pth export_model(config_file, checkpoint_file, faster_rcnn.onnx)6. 可视化增强与结果分析6.1 检测结果二次加工在输出图像上添加自定义信息from PIL import Image, ImageDraw result_img Image.open(outputs/result.jpg) draw ImageDraw.Draw(result_img) # 在左上角添加模型信息 draw.text((10, 10), fModel: Faster R-CNN\nConfidence: {result[0][0][4]:.2f}, fill(255, 0, 0)) result_img.save(outputs/result_with_info.jpg)6.2 性能评估脚本创建eval.py进行定量评估from mmdet.apis import init_detector, inference_detector import time config configs/faster_rcnn/faster-rcnn_r50_fpn_1x_coco.py checkpoint checkpoints/faster_rcnn_r50_fpn_1x_coco_20200130-047c8118.pth model init_detector(config, checkpoint, devicecuda:0) # 预热GPU for _ in range(10): _ inference_detector(model, demo/demo.jpg) # 正式测试 start time.time() for _ in range(100): result inference_detector(model, demo/demo.jpg) elapsed time.time() - start print(fAverage inference time: {elapsed/100:.4f}s)