一、安装cuda11.3版的Pytorch
首先创建虚拟环境(我装的python3.7,听说3.9版会有问题),安装cuda11.3版的Pytorch,用官网提供的指令会直接安装cpu版的,应该用
pip3 install torch==1.12.1+cu113 torchvision==0.13.1+cu113 torchaudio==0.12.1 -f https://download.pytorch.org/whl/torch_stable.html
这个指令在Anaconda Prompt 中用,最好以管理员身份运行。
装完之后输入
python
import torch
torch.cuda.is_available()
torch.version.cuda
来验证装的对不对,下图是对的
如果不对,可能是装了CPU版的Pytorch,就重新装创建一个虚拟环境然后重新安装。如果在原环境卸了CPU版的重装cuda版的,不一定能正常用,很麻烦。
二、VS 2019配置环境
接着将D:\InstallMyApp\VS2019\VC\Tools\MSVC\14.29.30133\bin\Hostx86\x64(安装VS2019的位置里找)添加到系统的环境变量中。
输入cl验证是否正确,下图为正确:
三、安装mmcv+mmdetection
然后安装mmcv,又遇到一个问题:需要用Anaconda Powershell Prompt安装,但我以前装的Anaconda是5.3.1版,没有Anaconda Powershell Prompt!
于是我把D:\Anaconda3中的env复制到另一个地方(比如G盘),然后用
卸载Anaconda,再去清华镜像网站根据日期下载最新的Anaconda2023版,网址:Index of /anaconda/archive/ | 清华大学开源软件镜像站 | Tsinghua Open Source Mirror
安装好之后用原env替换掉新的env,这样之前创建的虚拟环境就可以继续用了,不用重新创建了。
后面的mmcv+mmdetection安装都在Anaconda Powershell Prompt中进行,以管理员身份运行,参考:win10 + GTX1660S + CUDA 11.1 + VS 2019 + py3.8+ Pytorch 1.8.1 安装 MMCV + mmdetection + mmsegmentation_1660s pytorch_lebusini的博客-优快云博客
安装好之后,mmdetection2的验证代码不好用了,我用的以下代码:
from mmdet.apis import init_detector, inference_detector
from mmdet.utils import register_all_modules
from mmdet.registry import VISUALIZERS
import mmcv
def main():
config_file = 'D:/PyProject/mmdetection-main/configs/faster_rcnn/faster-rcnn_r50_fpn_1x_coco.py'
# download the checkpoint from model zoo and put it in `checkpoints/`
# url: https://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 = 'D:/PyProject/mmdetection-main/checkpoints/faster_rcnn_r50_fpn_1x_coco_20200130-047c8118.pth'
device = 'cuda:0'
register_all_modules()
# init a detector
model = init_detector(config_file, checkpoint_file, device=device)
# inference the demo image
img = mmcv.imread('D:/PyProject/mmdetection-main/demo/demo.jpg', channel_order='rgb')
result = inference_detector(model, img)
# init the visualizer(execute this block only once)
visualizer = VISUALIZERS.build(model.cfg.visualizer)
# the dataset_meta is loaded from the checkpoint and
# then pass to the model in init_detector
visualizer.dataset_meta = model.dataset_meta
# Let's plot the result
# show the results
visualizer.add_datasample(
'result',
img,
data_sample=result,
draw_gt=False,
wait_time=0,
)
visualizer.show()
if __name__ == '__main__':
main()
运行结果如下:
参考
1. Anaconda虚拟环境中安装torch + cuda + cuDNN_anaconda安装cuda_ligous的博客-优快云博客
2.【Network】win10+cuda11.0+pytorch1.7.1安装mmcv及swin transformer的测试_pytorch安装mmcv_努力的袁的博客-优快云博客